Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(voice-input): 断网时保留已识别出的语音文字 (#689)

Dash64cf69e360ff
diff --git a/apps/desktop/help-knowledge/voice-input.md b/apps/desktop/help-knowledge/voice-input.md
index 301f88325b..81b8ff64f5 100644
--- a/apps/desktop/help-knowledge/voice-input.md
+++ b/apps/desktop/help-knowledge/voice-input.md
@@ -35,3 +35,4 @@ Voice input lets you dictate instead of typing. Hold a shortcut, talk, release
- Push-and-hold is the primary activation mode; **Fast activation** changes the warm-up behavior, not the trigger itself.
- If the global shortcut fails to register (e.g. it's already taken by another app like an IME), you'll see a warning in the page; pick a different shortcut.
+- If the connection drops mid-dictation, the text recognized up to that point is kept — it lands in the composer (or stays in the overlay with a copy button) alongside the error, instead of being discarded. That salvaged text is raw ASR output: refinement needs the connection that just failed, so it is skipped.
diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
index 78104e5283..d52457548c 100644
--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
@@ -158,7 +158,7 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [
title: "Using voice input (dictation)",
summary: "Push-to-talk dictation that inserts ASR text into the focused composer; configure shortcut, mic, language, refinement, and dictionary in Settings > Voice Input.",
tab: "voice-input",
- content: "Voice input lets you dictate instead of typing. Hold a shortcut, talk, release — the recognized text is inserted into whichever composer has focus.\n\n**Activation:**\n\n- Default shortcut: **Alt+Space** on macOS, **Ctrl+Shift+Space** on Windows. The shortcut is customizable on macOS and Windows. On Linux, global voice shortcuts are not supported yet (the setting is hidden).\n- The shortcut is **global** — it works even when Cindy isn't the focused app, so you can dictate into the composer from anywhere.\n- It's **push-and-hold**: press to start listening, release to stop and submit.\n\n**Settings:**\n\n- **Microphone** — pick a specific device or leave on \"auto\" (system default).\n- **Language** — auto / 中文 (zh-CN) / English / 日本語 / 한국어. Those are the supported recognition locales — there's no free-form locale field.\n- **Refinement** — optional LLM post-process that cleans up the raw ASR text (fixes punctuation, removes ums, joins fragments). You can write a custom refinement prompt to bias it toward your preferences.\n- **Mute system audio while recording** — toggle; reduces feedback / echo from your speakers picking up onto the mic. On by default.\n- **Fast activation** — toggle; keeps the mic warm so press-to-talk has lower latency at the cost of slightly more background mic usage. Off by default.\n- **Interaction sound** — a short sound cue when dictation starts / stops. On by default.\n\n**Dictionary (improves recognition of your terms):**\n\n- **Manual entries** — type terms you want recognized (people's names, product names, jargon).\n- **Learned entries** — when you edit the text shortly after dictation lands in the composer, the external-edit inspector picks up your corrections and feeds them back as automatic dictionary entries. Both manual and learned entries feed the refinement pass.\n\n**Permissions (macOS):**\n\n- **Microphone** — required; the page prompts the OS dialog if you haven't granted it.\n- **Input Monitoring** and **Accessibility** — may be required depending on how the global shortcut is captured. The page shows each permission's status (granted / denied / unknown) so you know what to grant in System Settings.\n\n**Notes:**\n\n- Push-and-hold is the primary activation mode; **Fast activation** changes the warm-up behavior, not the trigger itself.\n- If the global shortcut fails to register (e.g. it's already taken by another app like an IME), you'll see a warning in the page; pick a different shortcut.",
+ content: "Voice input lets you dictate instead of typing. Hold a shortcut, talk, release — the recognized text is inserted into whichever composer has focus.\n\n**Activation:**\n\n- Default shortcut: **Alt+Space** on macOS, **Ctrl+Shift+Space** on Windows. The shortcut is customizable on macOS and Windows. On Linux, global voice shortcuts are not supported yet (the setting is hidden).\n- The shortcut is **global** — it works even when Cindy isn't the focused app, so you can dictate into the composer from anywhere.\n- It's **push-and-hold**: press to start listening, release to stop and submit.\n\n**Settings:**\n\n- **Microphone** — pick a specific device or leave on \"auto\" (system default).\n- **Language** — auto / 中文 (zh-CN) / English / 日本語 / 한국어. Those are the supported recognition locales — there's no free-form locale field.\n- **Refinement** — optional LLM post-process that cleans up the raw ASR text (fixes punctuation, removes ums, joins fragments). You can write a custom refinement prompt to bias it toward your preferences.\n- **Mute system audio while recording** — toggle; reduces feedback / echo from your speakers picking up onto the mic. On by default.\n- **Fast activation** — toggle; keeps the mic warm so press-to-talk has lower latency at the cost of slightly more background mic usage. Off by default.\n- **Interaction sound** — a short sound cue when dictation starts / stops. On by default.\n\n**Dictionary (improves recognition of your terms):**\n\n- **Manual entries** — type terms you want recognized (people's names, product names, jargon).\n- **Learned entries** — when you edit the text shortly after dictation lands in the composer, the external-edit inspector picks up your corrections and feeds them back as automatic dictionary entries. Both manual and learned entries feed the refinement pass.\n\n**Permissions (macOS):**\n\n- **Microphone** — required; the page prompts the OS dialog if you haven't granted it.\n- **Input Monitoring** and **Accessibility** — may be required depending on how the global shortcut is captured. The page shows each permission's status (granted / denied / unknown) so you know what to grant in System Settings.\n\n**Notes:**\n\n- Push-and-hold is the primary activation mode; **Fast activation** changes the warm-up behavior, not the trigger itself.\n- If the global shortcut fails to register (e.g. it's already taken by another app like an IME), you'll see a warning in the page; pick a different shortcut.\n- If the connection drops mid-dictation, the text recognized up to that point is kept — it lands in the composer (or stays in the overlay with a copy button) alongside the error, instead of being discarded. That salvaged text is raw ASR output: refinement needs the connection that just failed, so it is skipped.",
},
{
id: "worktrees",
diff --git a/apps/desktop/src/main/voice-input/index.ts b/apps/desktop/src/main/voice-input/index.ts
index be78ef1b92..da968d566a 100644
--- a/apps/desktop/src/main/voice-input/index.ts
+++ b/apps/desktop/src/main/voice-input/index.ts
@@ -2139,8 +2139,8 @@ export function registerVoiceInputIpc(): void {
});
return true;
},
- onError: (message, code) => {
- if (runId) emit({ type: 'error', runId, message, code });
+ onError: (message, code, details) => {
+ if (runId) emit({ type: 'error', runId, message, code, transcriptKept: details?.transcriptKept });
},
},
});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 67942a8224..b99ef1b47b 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4284,6 +4284,7 @@
"refining": "Refining",
"result": "Voice input",
"inputFailed": "Input failed",
+ "transcriptKept": "Recognized text kept",
"permissionRequired": "Permission required",
"error": "Voice input failed"
},
@@ -4321,7 +4322,11 @@
"apiKeyRequired": "Configure an API Key before using voice input.",
"cindyServiceUnavailable": "The Cindy voice service is unavailable. Check your network or switch service source.",
"asrServiceUnavailable": "Voice recognition service failed to connect. Check your network and try again.",
- "emptyTranscript": "Speech was detected, but no text was recognized. Please try again."
+ "emptyTranscript": "Speech was detected, but no text was recognized. Please try again.",
+ "connectionInterrupted": "The voice connection was interrupted. Check your network and try again.",
+ "recognitionStalled": "Voice recognition stopped returning results. Try again.",
+ "transcriptKept": "{{message}} The text recognized so far was kept — you can edit it directly.",
+ "transcriptKeptOverlay": "{{message}} The text recognized so far was kept — copy it to continue."
},
"chat": {
"askUserQuestion": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 5c5b5ebc6c..ae4a4a8432 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4283,6 +4283,7 @@
"refining": "整えています",
"result": "音声入力",
"inputFailed": "入力に失敗しました",
+ "transcriptKept": "認識したテキストは保持しています",
"permissionRequired": "権限が必要です",
"error": "音声入力に失敗しました"
},
@@ -4320,7 +4321,11 @@
"apiKeyRequired": "音声入力を使用するには、先に API Key を設定してください。",
"cindyServiceUnavailable": "Cindy 音声サービスを利用できません。ネットワークを確認するか、サービス提供元を切り替えてください。",
"asrServiceUnavailable": "音声認識サービスに接続できません。ネットワークを確認してから再試行してください。",
- "emptyTranscript": "音声は検出されましたが、テキストを認識できませんでした。もう一度お試しください。"
+ "emptyTranscript": "音声は検出されましたが、テキストを認識できませんでした。もう一度お試しください。",
+ "connectionInterrupted": "音声接続が中断されました。ネットワークを確認してからやり直してください。",
+ "recognitionStalled": "音声認識の結果が返ってこなくなりました。もう一度お試しください。",
+ "transcriptKept": "{{message}}(ここまで認識したテキストは保持しており、そのまま編集できます)",
+ "transcriptKeptOverlay": "{{message}}(ここまで認識したテキストは保持しており、コピーして続けられます)"
},
"chat": {
"askUserQuestion": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index b48d0792fd..02a806a5e0 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4283,6 +4283,7 @@
"refining": "다듬는 중",
"result": "음성 입력",
"inputFailed": "입력 실패",
+ "transcriptKept": "인식된 텍스트는 유지됨",
"permissionRequired": "권한 필요",
"error": "음성 입력 실패"
},
@@ -4320,7 +4321,11 @@
"apiKeyRequired": "음성 입력을 사용하려면 먼저 API Key를 설정하세요.",
"cindyServiceUnavailable": "Cindy 음성 서비스를 사용할 수 없습니다. 네트워크를 확인하거나 서비스 소스를 전환하세요.",
"asrServiceUnavailable": "음성 인식 서비스에 연결하지 못했습니다. 네트워크를 확인한 뒤 다시 시도하세요.",
- "emptyTranscript": "음성이 감지되었지만 텍스트를 인식하지 못했습니다. 다시 시도하세요."
+ "emptyTranscript": "음성이 감지되었지만 텍스트를 인식하지 못했습니다. 다시 시도하세요.",
+ "connectionInterrupted": "음성 연결이 중단되었습니다. 네트워크를 확인한 뒤 다시 시도하세요.",
+ "recognitionStalled": "음성 인식 결과가 더 이상 오지 않습니다. 다시 시도하세요.",
+ "transcriptKept": "{{message}} 지금까지 인식된 텍스트는 유지했습니다. 바로 이어서 편집할 수 있습니다.",
+ "transcriptKeptOverlay": "{{message}} 지금까지 인식된 텍스트는 유지했습니다. 복사해서 이어가세요."
},
"chat": {
"askUserQuestion": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index d6e300f654..01961a6742 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4283,6 +4283,7 @@
"refining": "正在润色",
"result": "语音输入",
"inputFailed": "输入失败",
+ "transcriptKept": "已保留识别出的文字",
"permissionRequired": "需要授权",
"error": "语音输入失败"
},
@@ -4320,7 +4321,11 @@
"apiKeyRequired": "需要先配置 API Key,才能使用语音输入。",
"cindyServiceUnavailable": "Cindy 官方语音服务暂不可用,请检查网络或切换服务来源。",
"asrServiceUnavailable": "语音识别服务连接失败,请检查网络或稍后重试。",
- "emptyTranscript": "检测到了语音,但没有识别出文字,请重试。"
+ "emptyTranscript": "检测到了语音,但没有识别出文字,请重试。",
+ "connectionInterrupted": "语音连接中断了,请检查网络后重试。",
+ "recognitionStalled": "语音识别没有继续返回结果,请重试。",
+ "transcriptKept": "{{message}}(识别出的文字已经保留,可以直接编辑)",
+ "transcriptKeptOverlay": "{{message}}(识别出的文字已经保留,可以复制后继续用)"
},
"chat": {
"askUserQuestion": {
diff --git a/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx b/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx
index f09a4681a0..32aeb59ebd 100644
--- a/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx
+++ b/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx
@@ -68,7 +68,7 @@ import { formatVoiceInputShortcut } from './shortcut';
import { VoiceInputMicWaveIcon } from './VoiceInputMicWaveIcon';
import { getVoiceInputWorkletUrl } from './workletUrl';
import { VoiceInputPointerHintLayer } from './VoiceInputPointerHintLayer';
-import { isVoiceInputServiceConnectionError } from './overlayErrors';
+import { isVoiceInputServiceConnectionError, VOICE_INPUT_ERROR_CODE_KEYS } from './overlayErrors';
import {
resolveVoiceInputReadinessRecovery,
type VoiceInputRecoverySettingsTab,
@@ -96,7 +96,10 @@ type StartReadyState = {
};
type GlobalOverlayCommand = { type: 'start' | 'submit' | 'cancel' };
type CloseOverlayOptions = { preservePasteTarget?: boolean };
-type PasteErrorCode = 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed';
+// 'retained' is not a paste failure: the dictation session itself died and the
+// recognized text was kept for copying. It reuses the paste-error layout but
+// carries the session's own error text instead of a paste hint.
+type PasteErrorCode = 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed' | 'retained';
type PermissionPromptKind = 'microphone' | 'accessibility';
function resetOverlayFocus(): void {
@@ -142,6 +145,9 @@ function getPasteErrorHintKey(errorCode: PasteErrorCode | null): string {
return 'voiceInputOverlay.pasteErrors.unconfirmed';
case 'permission':
return 'voiceInputOverlay.pasteErrors.permission';
+ case 'retained':
+ // Callers render the session error instead; this is only a safety net.
+ return 'voiceInputOverlay.status.transcriptKept';
case 'failed':
default:
return 'voiceInputOverlay.pasteErrors.failed';
@@ -372,11 +378,30 @@ export function VoiceInputOverlay() {
if (audioMs > 0) recordVoiceInputUsage(audioMs, terminalOutcomeRef.current);
}, []);
- const formatVoiceInputError = useCallback((message: string, code?: VoiceInputErrorCode): string => {
- if (code === 'empty_transcript') return t('voiceInputOverlay.emptyTranscript');
+ const formatVoiceInputStartError = useCallback((message: string): string => {
+ if (isVoiceInputServiceConnectionError(message)) {
+ return t('voiceInputOverlay.asrServiceUnavailable');
+ }
return message;
}, [t]);
+ const formatVoiceInputError = useCallback((
+ message: string,
+ code?: VoiceInputErrorCode,
+ transcriptKept?: boolean,
+ ): string => {
+ // Coded failures carry an English debug `message`; the localized sentence
+ // comes from the code. Uncoded ones come from a provider — normalize them
+ // through the same connection mapping the start path uses, so the identical
+ // transport failure reads the same whether or not salvage happened, and raw
+ // ECONNRESET/"fetch failed" strings never reach the user.
+ const cause = code ? t(VOICE_INPUT_ERROR_CODE_KEYS[code]) : formatVoiceInputStartError(message);
+ // Overlay-specific retention copy: its transcript is a read-only HUD with a
+ // Copy button, so telling users to "edit it directly" (what the composers
+ // say) would name an action they cannot take here.
+ return transcriptKept ? t('voiceInputOverlay.transcriptKeptOverlay', { message: cause }) : cause;
+ }, [formatVoiceInputStartError, t]);
+
const appendAudioChunk = useCallback((chunk: PcmChunk) => {
sentAudioMsRef.current += chunk.trace.durationMs;
window.electronAPI.voiceInput.appendAudio(chunk);
@@ -391,13 +416,6 @@ export function VoiceInputOverlay() {
return false;
}, []);
- const formatVoiceInputStartError = useCallback((message: string): string => {
- if (isVoiceInputServiceConnectionError(message)) {
- return t('voiceInputOverlay.asrServiceUnavailable');
- }
- return message;
- }, [t]);
-
const cancelStartedRun = useCallback((startPromise: Promise<StartVoiceInputResult>) => {
void startPromise
.then((result) => {
@@ -1248,30 +1266,39 @@ export function VoiceInputOverlay() {
case 'error': {
log.warn('global voice input error:', event.message);
terminalOutcomeRef.current = 'failed';
- const formattedMessage = formatVoiceInputError(event.message, event.code);
+ const formattedMessage = formatVoiceInputError(event.message, event.code, event.transcriptKept);
if (promptCodexSessionExpired(formattedMessage)) {
codexSessionPromptActiveRef.current = true;
}
- // Preserve already-recognized text for the user to copy. The
- // overlay's existing "paste failed" UI does exactly this — render
- // the captured draft + a copy button — so reuse that path. The
- // distinction from a real paste failure (no text was ever delivered
- // to the target app vs. paste was rejected by the target) is not
- // worth a separate UI surface; what matters is the user does not
- // lose the transcription they just produced.
+ // Preserve already-recognized text for the user to copy, reusing the
+ // "paste failed" layout (transcript + copy button). It is tagged
+ // 'retained' rather than 'failed' because no paste was attempted:
+ // that distinction drives which hint the panel shows, so a dropped
+ // session is not reported as the target app rejecting input.
const recognizedText = (finalTextRef.current || draftTextRef.current).trim();
- if (closingRef.current && recognizedText) {
+ if (closingRef.current && recognizedText && !event.transcriptKept) {
// Stop-time provider errors can arrive after ASR has produced a
// stable transcript while refinement is still running. Treating
// that late error as completion makes the global overlay paste raw
// ASR text before the refined result arrives. Keep waiting for
// done/refined here; waitForDone still has its timeout fallback.
+ //
+ // A retained-transcript failure is the opposite case: the run is
+ // already terminal, so nothing further will arrive. Skipping the
+ // setup below would leave the overlay open showing the transcript
+ // with no explanation and no copy button (stopAndPaste bails out on
+ // the error state without pasting).
break;
}
- setError(formatVoiceInputStartError(formattedMessage));
+ // formatVoiceInputError already normalized the cause (including the
+ // connection mapping) and appended the retention note, so this must
+ // not run the finished sentence through the start-error mapper again
+ // — that would swap the whole thing for the generic
+ // service-unavailable copy and drop the retention half.
+ setError(formattedMessage);
if (recognizedText) {
pendingPasteTextRef.current = recognizedText;
- setPasteErrorCode('failed');
+ setPasteErrorCode(event.transcriptKept ? 'retained' : 'failed');
setHasPasteError(true);
}
setVoiceState('error');
@@ -1297,7 +1324,7 @@ export function VoiceInputOverlay() {
break;
}
});
- }, [formatVoiceInputError, formatVoiceInputStartError, promptCodexSessionExpired, resolveDoneWaiters, setVoiceState]);
+ }, [formatVoiceInputError, promptCodexSessionExpired, resolveDoneWaiters, setVoiceState]);
useEffect(() => {
const unsubscribe = window.electronAPI.voiceInput.onGlobalOverlayCommand((command: GlobalOverlayCommand) => {
@@ -1393,13 +1420,18 @@ export function VoiceInputOverlay() {
const closeTooltip = t('voiceInputOverlay.closeWithShortcut', { shortcut: 'Esc' });
const statusLabel = useMemo(() => {
if (hasPermissionPrompt) return t('voiceInputOverlay.status.permissionRequired');
+ if (pasteErrorCode === 'retained') return t('voiceInputOverlay.status.transcriptKept');
if (hasPasteError) return t('voiceInputOverlay.status.inputFailed');
if (hasBlockingError) return t('voiceInputOverlay.status.error');
if (state === 'refining') return t('voiceInputOverlay.status.refining');
if (state === 'submitting') return t('voiceInputOverlay.status.submitting');
return t('voiceInputOverlay.status.listening');
- }, [hasBlockingError, hasPasteError, hasPermissionPrompt, state, t]);
- const pasteFailureHint = t(getPasteErrorHintKey(pasteErrorCode));
+ }, [hasBlockingError, hasPasteError, hasPermissionPrompt, pasteErrorCode, state, t]);
+ // The retained-transcript panel shows the session's own error (cause + "text
+ // was kept"); every other code is an actual paste failure with its own hint.
+ const pasteFailureHint = pasteErrorCode === 'retained'
+ ? error ?? t('voiceInputOverlay.status.transcriptKept')
+ : t(getPasteErrorHintKey(pasteErrorCode));
const permissionPromptHint = permissionPrompt
? t(`voiceInputOverlay.permissionPrompts.${permissionPrompt}.hint`)
: '';
diff --git a/apps/desktop/src/renderer/voice-input/__tests__/editorRangeMapping.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/editorRangeMapping.test.ts
new file mode 100644
index 0000000000..92886d8a5c
--- /dev/null
+++ b/apps/desktop/src/renderer/voice-input/__tests__/editorRangeMapping.test.ts
@@ -0,0 +1,75 @@
+/**
+ * editorRangeMapping.test.ts — 语音插入点跟随文档变化的契约
+ * ---------------------------------------------------------------------------
+ * 语音插入点是开始听写时按当时选区记下的两个 offset。听写期间 composer 是只读的,
+ * 但程序化写入(草稿恢复、引用插入等)不受限制,会让这两个数字过期;而断线抢救正是
+ * 在会话已经出问题时拿它去替换文本——错位就等于吃掉用户此刻的文字。
+ *
+ * 这里锁死 ProseMirror mapping 的 association 方向:落在边界上的插入必须留在替换
+ * 区间**外面**。方向写反(-1 / 1)看起来更"直觉",实际会让区间反过来把新文字圈进去,
+ * 下一次替换就把它覆盖掉——这正是本文件要防的回归。
+ */
+import { describe, expect, it } from 'vitest';
+import { Schema } from '@tiptap/pm/model';
+import { EditorState } from '@tiptap/pm/state';
+
+import { mapEditorTextRange } from '../editorRangeMapping';
+
+const schema = new Schema({
+ nodes: {
+ doc: { content: 'paragraph+' },
+ paragraph: { content: 'text*' },
+ text: {},
+ },
+});
+
+function stateWith(text: string): EditorState {
+ return EditorState.create({
+ doc: schema.node('doc', null, [schema.node('paragraph', null, text ? [schema.text(text)] : [])]),
+ });
+}
+
+describe('mapEditorTextRange', () => {
+ it('returns null for a missing range', () => {
+ const state = stateWith('hello');
+ expect(mapEditorTextRange(null, state.tr.insertText('x', 1))).toBeNull();
+ });
+
+ it('keeps a collapsed cursor collapsed after an insertion at that exact spot', () => {
+ const state = stateWith('hello');
+ // Cursor parked right after "hello" (doc positions start at 1).
+ const cursor = { from: 6, to: 6 };
+ const mapped = mapEditorTextRange(cursor, state.tr.insertText('ABC', 6));
+
+ // Still collapsed — a range spanning "ABC" would make the salvage path
+ // replace text this run never produced.
+ expect(mapped).toEqual({ from: 9, to: 9 });
+ });
+
+ it('keeps text inserted at the range start outside the range', () => {
+ const state = stateWith('hello world');
+ const selection = { from: 7, to: 12 }; // "world"
+ const mapped = mapEditorTextRange(selection, state.tr.insertText('XY', 7));
+
+ expect(mapped).toEqual({ from: 9, to: 14 });
+ expect(state.tr.insertText('XY', 7).doc.textBetween(mapped!.from, mapped!.to)).toBe('world');
+ });
+
+ it('keeps text inserted at the range end outside the range', () => {
+ const state = stateWith('hello world');
+ const selection = { from: 1, to: 6 }; // "hello"
+ const mapped = mapEditorTextRange(selection, state.tr.insertText('XY', 6));
+
+ expect(mapped).toEqual({ from: 1, to: 6 });
+ expect(state.tr.insertText('XY', 6).doc.textBetween(mapped!.from, mapped!.to)).toBe('hello');
+ });
+
+ it('shifts the whole range when text lands before it', () => {
+ const state = stateWith('hello world');
+ const selection = { from: 7, to: 12 }; // "world"
+ const mapped = mapEditorTextRange(selection, state.tr.insertText('XY', 1));
+
+ expect(mapped).toEqual({ from: 9, to: 14 });
+ expect(state.tr.insertText('XY', 1).doc.textBetween(mapped!.from, mapped!.to)).toBe('world');
+ });
+});
diff --git a/apps/desktop/src/renderer/voice-input/editorRangeMapping.ts b/apps/desktop/src/renderer/voice-input/editorRangeMapping.ts
new file mode 100644
index 0000000000..74657d8904
--- /dev/null
+++ b/apps/desktop/src/renderer/voice-input/editorRangeMapping.ts
@@ -0,0 +1,31 @@
+import type { Transaction } from '@tiptap/pm/state';
+
+export type EditorTextRange = {
+ from: number;
+ to: number;
+};
+
+/**
+ * Move a stored range through a document change, so offsets captured earlier
+ * keep pointing at the same content.
+ *
+ * The association arguments are what keep text inserted exactly at a boundary
+ * OUTSIDE the range: `1` pushes `from` past such an insertion, `-1` holds `to`
+ * in front of it. (The opposite pair — the intuitive-looking "bias outward" —
+ * grows the range around the new text, which the next replacement would then
+ * overwrite.) A collapsed cursor gets pushed both ways at once and ends up
+ * inverted; keep it collapsed after the insertion rather than letting a
+ * downstream min/max clamp swap it back into a range spanning that text.
+ *
+ * Lives in its own module so it can be tested without pulling in the voice
+ * input hook and its Electron bridge.
+ */
+export function mapEditorTextRange(
+ range: EditorTextRange | null,
+ transaction: Transaction,
+): EditorTextRange | null {
+ if (!range) return null;
+ const from = transaction.mapping.map(range.from, 1);
+ const to = transaction.mapping.map(range.to, -1);
+ return from > to ? { from, to: from } : { from, to };
+}
diff --git a/apps/desktop/src/renderer/voice-input/overlayErrors.ts b/apps/desktop/src/renderer/voice-input/overlayErrors.ts
index a6c6967558..cfb3e08318 100644
--- a/apps/desktop/src/renderer/voice-input/overlayErrors.ts
+++ b/apps/desktop/src/renderer/voice-input/overlayErrors.ts
@@ -1,3 +1,17 @@
+import type { VoiceInputErrorCode } from '@cindy/voice-input-core';
+
+/**
+ * i18n keys for the failures the voice controller classifies itself. Their
+ * `message` is an English debug string, so the user-facing sentence must come
+ * from the code. Uncoded failures originate in a provider (auth, quota,
+ * protocol) and keep their own message — it is the only description we have.
+ */
+export const VOICE_INPUT_ERROR_CODE_KEYS: Record<VoiceInputErrorCode, string> = {
+ empty_transcript: 'voiceInputOverlay.emptyTranscript',
+ connection_interrupted: 'voiceInputOverlay.connectionInterrupted',
+ recognition_stalled: 'voiceInputOverlay.recognitionStalled',
+};
+
const VOICE_INPUT_SERVICE_CONNECTION_ERROR_PATTERN =
/\b(ENOTFOUND|ETIMEDOUT|ECONNRESET|ECONNREFUSED|ENETUNREACH|EAI_AGAIN|TLS)\b|getaddrinfo|network|websocket|timed out|fetch failed|certificate|self[- ]signed/i;
diff --git a/apps/desktop/src/renderer/voice-input/useVoiceInput.ts b/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
index aa6cb1bc91..29c8c764fa 100644
--- a/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
+++ b/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
@@ -59,7 +59,8 @@ import { resolveVoiceInputStartGuards } from './startGuards';
import { getVoiceInputWorkletUrl } from './workletUrl';
import { buildRefinementPreviewText } from './refinementPreviewText';
import { isVoiceInputEventScopeActive, shouldHandleVoiceInputEvent } from './eventScope';
-import { isVoiceInputServiceConnectionError } from './overlayErrors';
+import { mapEditorTextRange, type EditorTextRange } from './editorRangeMapping';
+import { isVoiceInputServiceConnectionError, VOICE_INPUT_ERROR_CODE_KEYS } from './overlayErrors';
import {
VOICE_INPUT_DICTIONARY_LEARNING_TRACK_TIMEOUT_MS,
} from '../../shared/voiceInputDictionaryLearning';
@@ -85,10 +86,7 @@ type SubmittedTextRange = {
historyEntryId: string | null;
};
-export type EditorTextRange = {
- from: number;
- to: number;
-};
+export type { EditorTextRange } from './editorRangeMapping';
type DictionaryLearningWatch = {
segmentId: string;
@@ -189,6 +187,12 @@ export function useVoiceInput(
const startAttemptIdRef = useRef(0);
const startReadyRef = useRef<StartReadyState | null>(null);
const ownedRunIdRef = useRef<string | null>(null);
+ // Whether this run's transcript actually reached the editor. The main-process
+ // onSubmitted bridge is fire-and-forget — it emits the event and synthesizes a
+ // range, so the controller's transcriptKept flag only means "the bridge took
+ // it", not "the composer has it". If the editor was gone (route/session
+ // change), insertSubmittedText() returns null and only this side knows.
+ const transcriptLandedRef = useRef(false);
const stopInFlightRef = useRef(false);
const stopInFlightPromiseRef = useRef<Promise<void> | null>(null);
const inlineErrorDismissTimerRef = useRef<number | null>(null);
@@ -368,17 +372,31 @@ export function useVoiceInput(
}, INLINE_ERROR_AUTO_DISMISS_MS);
}, [clearInlineErrorDismissTimer]);
- const formatVoiceInputError = useCallback((message: string, code?: VoiceInputErrorCode): string => {
- if (code === 'empty_transcript') return t('voiceInputOverlay.emptyTranscript');
- return message;
- }, [t]);
-
const formatVoiceInputStartError = useCallback((message: string): string => {
return isVoiceInputServiceConnectionError(message)
? t('voiceInputOverlay.asrServiceUnavailable')
: message;
}, [t]);
+ const formatVoiceInputError = useCallback((
+ message: string,
+ code?: VoiceInputErrorCode,
+ transcriptKept?: boolean,
+ ): string => {
+ // Coded failures are the controller's own; their `message` is an English
+ // debug string, so the localized sentence has to come from the code.
+ // Uncoded ones come from a provider — run them through the same connection
+ // mapping the start path uses, so one transport failure reads the same on
+ // both paths and raw ECONNRESET/"fetch failed" strings stay out of the UI.
+ // Anything that is not a transport string (auth, quota, protocol) survives
+ // verbatim, since that message is its only description.
+ const cause = code ? t(VOICE_INPUT_ERROR_CODE_KEYS[code]) : formatVoiceInputStartError(message);
+ // Retention is appended to the cause, never substituted for it: the user
+ // still needs to know whether this was a dropped socket or an expired
+ // credential, and they also need to know their words are in the composer.
+ return transcriptKept ? t('voiceInputOverlay.transcriptKept', { message: cause }) : cause;
+ }, [formatVoiceInputStartError, t]);
+
const appendAudioChunk = useCallback((chunk: PcmChunk) => {
sentAudioMsRef.current += chunk.trace.durationMs;
window.electronAPI.voiceInput.appendAudio(chunk);
@@ -933,6 +951,7 @@ export function useVoiceInput(
case 'submitted':
{
const range = insertSubmittedText(event.text);
+ transcriptLandedRef.current = Boolean(range);
if (range) {
const historyEntryId = recordVoiceInputHistory(event.text);
submittedRangesRef.current.set(event.segment.id, {
@@ -1002,7 +1021,12 @@ export function useVoiceInput(
case 'error': {
log.warn('voice input error:', event.message);
terminalOutcomeRef.current = 'failed';
- const formattedMessage = formatVoiceInputError(event.message, event.code);
+ // Only this side knows whether the text really made it into the
+ // editor: the main-process bridge answers onSubmitted synchronously
+ // with a synthesized range, so transcriptKept alone would promise
+ // retention even when insertSubmittedText() found no live editor.
+ const transcriptKept = event.transcriptKept === true && transcriptLandedRef.current;
+ const formattedMessage = formatVoiceInputError(event.message, event.code, transcriptKept);
promptCodexSessionExpired(formattedMessage);
commitUsageStats();
void (async () => {
@@ -1059,6 +1083,15 @@ export function useVoiceInput(
if (!editor) return;
const handleTransaction = ({ transaction }: { transaction: Transaction }) => {
inspectDictionaryLearningTransaction(transaction);
+ // The insertion point is captured from the selection when dictation
+ // starts, and the composer is read-only while it runs — but programmatic
+ // writes (draft restore, quote insertion, …) bypass that and shift every
+ // offset after them. A stale offset is worst exactly where it is used
+ // last: the salvage path replaces that range after a failure, which would
+ // eat whatever text now occupies it. Ride along on ProseMirror's mapping.
+ if (!transaction.docChanged || applyingVoiceTextRef.current) return;
+ insertionRangeRef.current = mapEditorTextRange(insertionRangeRef.current, transaction);
+ draftDisplayRangeRef.current = mapEditorTextRange(draftDisplayRangeRef.current, transaction);
};
editor.on('transaction', handleTransaction);
return () => {
@@ -1339,6 +1372,7 @@ export function useVoiceInput(
runIdRef.current = result.runId;
ownedRunIdRef.current = result.runId;
+ transcriptLandedRef.current = false;
if (!isActiveStartAttempt(attemptId)) {
resolveStartReadyState(attemptId, { ok: false, error: 'Voice input start was cancelled.' });
await stopEngine();
diff --git a/apps/mobile/src/i18n/locales/en/composer.json b/apps/mobile/src/i18n/locales/en/composer.json
index 810bbbc0ef..0103352456 100644
--- a/apps/mobile/src/i18n/locales/en/composer.json
+++ b/apps/mobile/src/i18n/locales/en/composer.json
@@ -97,6 +97,9 @@
"incomplete": "Voice input didn't finish. Try again.",
"missingRefinerTargetProvider": "Mobile voice refinement needs a {{appName}} voice session (refinerTargetProvider is missing).",
"emptyTranscript": "Speech was detected but no text was recognized. Try again.",
+ "connectionInterrupted": "The voice connection was interrupted. Check your network and try again.",
+ "recognitionStalled": "Voice recognition stopped returning results. Try again.",
+ "transcriptKept": "{{message}} The text recognized so far was kept — you can edit it directly.",
"micPermission": "Microphone access is turned off. Allow {{appName}} to use the microphone in system settings.",
"realtimeAudioUnavailable": "This build does not support realtime voice input. Install a test build that includes the native recording module."
}
diff --git a/apps/mobile/src/i18n/locales/ja/composer.json b/apps/mobile/src/i18n/locales/ja/composer.json
index 82bf3651b9..aa4dae295e 100644
--- a/apps/mobile/src/i18n/locales/ja/composer.json
+++ b/apps/mobile/src/i18n/locales/ja/composer.json
@@ -97,6 +97,9 @@
"incomplete": "音声入力が完了しませんでした。もう一度お試しください。",
"missingRefinerTargetProvider": "モバイル版の音声推敲には {{appName}} の音声セッションが必要です(refinerTargetProvider がありません)。",
"emptyTranscript": "音声を検出しましたが、テキストを認識できませんでした。もう一度お試しください。",
+ "connectionInterrupted": "音声接続が中断されました。ネットワークを確認してからやり直してください。",
+ "recognitionStalled": "音声認識の結果が返ってこなくなりました。もう一度お試しください。",
+ "transcriptKept": "{{message}}(ここまで認識したテキストは保持しており、そのまま編集できます)",
"micPermission": "マイクの権限が許可されていません。システム設定で {{appName}} にマイクの使用を許可してください。",
"realtimeAudioUnavailable": "現在のビルドはリアルタイム音声入力に対応していません。ネイティブ録音モジュールを含むテストビルドをインストールしてください。"
}
diff --git a/apps/mobile/src/i18n/locales/ko/composer.json b/apps/mobile/src/i18n/locales/ko/composer.json
index 680f5679c7..0dc903524b 100644
--- a/apps/mobile/src/i18n/locales/ko/composer.json
+++ b/apps/mobile/src/i18n/locales/ko/composer.json
@@ -97,6 +97,9 @@
"incomplete": "음성 입력이 완료되지 않았습니다. 다시 시도하세요.",
"missingRefinerTargetProvider": "모바일 음성 다듬기에는 {{appName}} 음성 세션이 필요합니다(refinerTargetProvider 누락).",
"emptyTranscript": "음성이 감지되었지만 텍스트를 인식하지 못했습니다. 다시 시도해 주세요.",
+ "connectionInterrupted": "음성 연결이 중단되었습니다. 네트워크를 확인한 뒤 다시 시도하세요.",
+ "recognitionStalled": "음성 인식 결과가 더 이상 오지 않습니다. 다시 시도하세요.",
+ "transcriptKept": "{{message}} 지금까지 인식된 텍스트는 유지했습니다. 바로 이어서 편집할 수 있습니다.",
"micPermission": "마이크 권한이 꺼져 있습니다. 시스템 설정에서 {{appName}}의 마이크 사용을 허용해 주세요.",
"realtimeAudioUnavailable": "현재 설치 패키지는 실시간 음성 입력을 지원하지 않습니다. 네이티브 녹음 모듈이 포함된 테스트 빌드를 설치해 주세요."
}
diff --git a/apps/mobile/src/i18n/locales/zh-CN/composer.json b/apps/mobile/src/i18n/locales/zh-CN/composer.json
index 1c7a21c8a7..c3e03f9f7f 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/composer.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/composer.json
@@ -97,6 +97,9 @@
"incomplete": "语音输入未完成,请重试。",
"missingRefinerTargetProvider": "手机版语音润色需要 {{appName}} 语音会话(缺少 refinerTargetProvider)。",
"emptyTranscript": "检测到语音但未识别出文本,请重试。",
+ "connectionInterrupted": "语音连接中断了,请检查网络后重试。",
+ "recognitionStalled": "语音识别没有继续返回结果,请重试。",
+ "transcriptKept": "{{message}}(识别出的文字已经保留,可以直接编辑)",
"micPermission": "麦克风权限未开启,请在系统设置里允许 {{appName}} 使用麦克风。",
"realtimeAudioUnavailable": "当前安装包不支持实时语音输入,请安装包含原生录音模块的测试版。"
}
diff --git a/apps/mobile/src/session/mobileVoiceController.ts b/apps/mobile/src/session/mobileVoiceController.ts
index 2e2ecb4ee8..45f0e805b7 100644
--- a/apps/mobile/src/session/mobileVoiceController.ts
+++ b/apps/mobile/src/session/mobileVoiceController.ts
@@ -23,7 +23,8 @@ import {
buildMobileVoiceRefinementContext,
makeMobileRefinerPromptCacheKey,
MobileLiteLlmTextModelClient,
- mobileVoiceEmptyTranscriptError,
+ mobileVoiceErrorCodeMessage,
+ mobileVoiceTranscriptKeptError,
type MobileVoiceDraftInsertion,
} from '@/session/mobileVoiceInput';
import { startMobileRealtimeAudio } from '@/session/mobileRealtimeAudio';
@@ -386,10 +387,15 @@ export function createMobileVoiceControllerSession(
&& range.segmentIds.every((id, index) => voiceInsertionSegmentIds[index] === id);
return sameRange && !isInsertionIntact(readCurrentDraft(), voiceInsertion);
},
- onError(message, code: VoiceInputErrorCode | undefined) {
- const localizedMessage = code === 'empty_transcript'
- ? mobileVoiceEmptyTranscriptError()
+ onError(message, code: VoiceInputErrorCode | undefined, details) {
+ // 有 code 的是 controller 自己分类的失败(message 是英文调试串),按 code 取
+ // 本地化文案;没有 code 的来自 provider,那条 message 才是唯一的失败描述。
+ const cause = code
+ ? mobileVoiceErrorCodeMessage(code)
: redactMobileVoiceCredentialText(message, options.credential);
+ const localizedMessage = details?.transcriptKept
+ ? mobileVoiceTranscriptKeptError(cause)
+ : cause;
controllerError = new Error(localizedMessage);
options.onError?.(localizedMessage);
},
@@ -569,7 +575,20 @@ export function createMobileVoiceControllerSession(
function recordSubmittedHistory(text: string): void {
if (!options.recordHistory) return;
- historyEntryPromise = Promise.resolve(options.recordHistory(text))
+ // 下面的 .catch 只兜得住异步拒绝;同步抛会顺着 onSubmitted 冒出 controller,
+ // 被当成「宿主没接住这段文本」——文字其实已经写进草稿了,而 controller 还会
+ // 据此认定本次听写失败。历史记录是附带能力,不该有这个权力。
+ let recording: ReturnType<NonNullable<MobileVoiceControllerOptions['recordHistory']>>;
+ try {
+ recording = options.recordHistory(text);
+ } catch (error) {
+ console.warn(
+ '[mobile-voice] record history failed (non-fatal):',
+ error instanceof Error ? error.message : String(error),
+ );
+ return;
+ }
+ historyEntryPromise = Promise.resolve(recording)
.then((entryId) => {
if (typeof entryId === 'string' && entryId.trim()) {
historyEntryId = entryId.trim();
diff --git a/apps/mobile/src/session/mobileVoiceInput.ts b/apps/mobile/src/session/mobileVoiceInput.ts
index 65dd600004..481ed5b9fb 100644
--- a/apps/mobile/src/session/mobileVoiceInput.ts
+++ b/apps/mobile/src/session/mobileVoiceInput.ts
@@ -10,6 +10,7 @@ import {
extractJsonStringFieldSnapshot,
type DictationRefinementContext,
type TextModelClient,
+ type VoiceInputErrorCode,
} from '@cindy/voice-input-core';
import type { StoredMobileVoiceCredential } from '@/session/mobileVoiceCredentialStore';
import type { MobileVoiceCredentialSyncDictionaryEntry as MobileVoiceDictionaryEntry } from '@cindy/maker-shared/device-link-contract';
@@ -25,6 +26,21 @@ export const MOBILE_MAX_VOICE_AUDIO_BYTES = 64 * 1024 * 1024;
export function mobileVoiceEmptyTranscriptError(): string {
return i18n.t('composer.voice.emptyTranscript');
}
+// controller 自己分类的失败:它的 message 是英文调试串,展示文案必须按 code 取。
+// 没有 code 的失败来自 provider(鉴权、配额、协议),那条 message 才是唯一的描述。
+const MOBILE_VOICE_ERROR_CODE_KEYS: Record<VoiceInputErrorCode, string> = {
+ empty_transcript: 'composer.voice.emptyTranscript',
+ connection_interrupted: 'composer.voice.connectionInterrupted',
+ recognition_stalled: 'composer.voice.recognitionStalled',
+};
+export function mobileVoiceErrorCodeMessage(code: VoiceInputErrorCode): string {
+ return i18n.t(MOBILE_VOICE_ERROR_CODE_KEYS[code]);
+}
+// 失败但已识别的文字已经落进输入框:在原始失败原因后面补一句「没丢」。原因不能被
+// 替换掉——凭证过期、配额用尽和断网需要用户做的事完全不同。
+export function mobileVoiceTranscriptKeptError(message: string): string {
+ return i18n.t('composer.voice.transcriptKept', { message });
+}
export function mobileVoiceMicPermissionError(): string {
return i18n.t('composer.voice.micPermission');
}
diff --git a/packages/voice-input-core/src/VoiceInputController.ts b/packages/voice-input-core/src/VoiceInputController.ts
index c971355c0c..c8d29a2472 100644
--- a/packages/voice-input-core/src/VoiceInputController.ts
+++ b/packages/voice-input-core/src/VoiceInputController.ts
@@ -90,6 +90,15 @@ export class VoiceInputController {
private startedAt = 0;
private latestPartial = '';
private latestStable = '';
+ // The most recent transcript regardless of lane, plus which lane produced it.
+ // Salvage cannot prefer `latestStable`: every provider emits both lanes as the
+ // full aggregate transcript, so a partial arriving after a stable (the next
+ // utterance already in progress) is strictly more complete. Preferring the
+ // stable lane would drop that tail — exactly the loss this salvage exists to
+ // prevent. stop() keeps its own stable-first ordering: there the flush is what
+ // produces the authoritative final stable.
+ private latestTranscript = '';
+ private latestTranscriptSource: 'partial' | 'stable' = 'partial';
private firstPartialSeen = false;
private firstAudioChunkSeen = false;
// Run-level speech activity separates an intentional silent stop from an
@@ -120,6 +129,15 @@ export class VoiceInputController {
// event so the next reproduction immediately tells us "session never produced
// anything" vs "stopped after producing some text".
private everSawAsrSignal = false;
+ // Whether this run already handed text to the host via onSubmitted. Guards the
+ // failure-path salvage against double insertion: a recovery that rejects after
+ // stop() already submitted would otherwise insert the same transcript twice.
+ private transcriptEmitted = false;
+ // Set when onSubmitted threw. A callback that throws part-way has already run
+ // an unknown share of its side effects (mobile publishes the draft, then calls
+ // an injected history recorder that can throw), so retrying it through salvage
+ // would run those effects a second time. One attempt per run is the contract.
+ private submitCallbackThrew = false;
constructor(options: VoiceInputControllerOptions) {
this.asr = options.asr;
@@ -146,6 +164,8 @@ export class VoiceInputController {
this.startedAt = performance.now();
this.latestPartial = '';
this.latestStable = '';
+ this.latestTranscript = '';
+ this.latestTranscriptSource = 'partial';
this.firstPartialSeen = false;
this.firstAudioChunkSeen = false;
this.speechActivitySeen = false;
@@ -157,6 +177,8 @@ export class VoiceInputController {
this.networkRecoveryAttempts = 0;
this.networkRecoveryInFlight = false;
this.everSawAsrSignal = false;
+ this.transcriptEmitted = false;
+ this.submitCallbackThrew = false;
this.startStallWatchdog();
this.setState('listening');
this.logger.record({ type: 'start_clicked', runId: this.runId, at: Date.now() });
@@ -214,6 +236,23 @@ export class VoiceInputController {
await this.asr.stop();
+ // Deliberately placed after the LAST provider await in this method, so it
+ // covers a failure landing during any of them. Providers hide such failures
+ // from this path: both flushAudio() and stop() await an in-flight recover()
+ // but swallow its rejection, so those awaits resolve normally on a run that
+ // fail() has already finished (salvaging the transcript and setting the
+ // terminal state). Continuing would submit the same transcript twice and
+ // overwrite 'error' with 'refining'/'done', hiding the failure entirely.
+ // transcriptEmitted is checked too: it is the direct invariant ("this run has
+ // already given the host its text"), so it holds even if a future failure
+ // path leaves the state alone.
+ if (this.leftSubmittingState() || this.transcriptEmitted) {
+ // cancel() also lands here (it moves the run to 'done'); logging that as
+ // a failure would misread the timeline for an intentional abort.
+ this.discardRefinement(runId, optimisticRefinement, this.currentRunCancelled ? 'cancelled' : 'run_failed');
+ return;
+ }
+
if (!text) {
this.discardRefinement(runId, optimisticRefinement, 'no_submitted_text');
if (this.speechActivitySeen) {
@@ -231,7 +270,26 @@ export class VoiceInputController {
text,
updatedAt: Date.now(),
};
- const range = this.callbacks.onSubmitted(text, segment);
+ let range: EditableRange | undefined;
+ try {
+ range = this.callbacks.onSubmitted(text, segment);
+ } catch (error) {
+ // salvageTranscript() already treats a throwing host as a real scenario
+ // (destroyed window, torn-down editor); this path has to survive it too.
+ // Letting the exception escape would reject stop() before any terminal
+ // state is set, stranding the run in 'submitting' — after which start()
+ // refuses to begin a new one and dictation is dead until reload.
+ this.submitCallbackThrew = true;
+ this.discardRefinement(runId, optimisticRefinement, 'run_failed');
+ this.fail(error instanceof Error ? error.message : String(error));
+ return;
+ }
+ // Same acceptance convention as salvageTranscript(): the returned range is
+ // the host's "I took the text" signal, and a host may refuse (mobile stops
+ // writing into the voice insertion once the user has edited it). Marking it
+ // emitted regardless would let a later failure claim transcriptKept for
+ // text that never landed.
+ this.transcriptEmitted = Boolean(range);
this.logger.record({ type: 'submitted', runId, at: Date.now(), text, source });
if (this.refiner && range) {
@@ -250,6 +308,16 @@ export class VoiceInputController {
}
}
+ /**
+ * True when something moved this run out of the state stop() set on entry —
+ * fail() from a rejected recovery, or cancel(). Deliberately a method: inside
+ * stop(), the `state !== 'listening'` guard narrows this.state for the whole
+ * body, so an inline comparison against 'submitting' is a type error.
+ */
+ private leftSubmittingState(): boolean {
+ return this.state !== 'submitting';
+ }
+
async cancel(): Promise<void> {
if (!this.runId) return;
const runId = this.runId;
@@ -280,6 +348,8 @@ export class VoiceInputController {
case 'partial':
if (this.state !== 'listening' && this.state !== 'submitting') return;
this.latestPartial = event.text;
+ this.latestTranscript = event.text;
+ this.latestTranscriptSource = 'partial';
this.resetStallCounters();
if (this.state !== 'listening') return;
if (!this.firstPartialSeen) {
@@ -297,6 +367,8 @@ export class VoiceInputController {
case 'stable':
if (this.state !== 'listening' && this.state !== 'submitting') return;
this.latestStable = event.text;
+ this.latestTranscript = event.text;
+ this.latestTranscriptSource = 'stable';
this.resetStallCounters();
this.logger.record({
type: 'stable_received',
@@ -338,7 +410,10 @@ export class VoiceInputController {
// was supposed to prevent.
if (this.state === 'listening' && this.tryRecover('disconnected')) break;
if (this.state === 'listening') {
- this.fail('Voice input connection was interrupted. Please try again.');
+ this.fail(
+ 'Voice input connection was interrupted. Please try again.',
+ 'connection_interrupted',
+ );
}
break;
}
@@ -452,6 +527,15 @@ export class VoiceInputController {
this.discardRefinement(runId, request, 'cancelled');
return;
}
+ // A failure can land while refinement is in flight (a recovery rejecting
+ // after stop() already submitted). Every exit below writes a terminal state,
+ // so continuing would overwrite 'error' with 'done' and erase the failure
+ // the user was just told about — along with applying refined text to a run
+ // whose host already reported it as failed.
+ if (this.state === 'error') {
+ this.discardRefinement(runId, request, 'run_failed');
+ return;
+ }
if (error) {
this.logger.record({
@@ -516,7 +600,10 @@ export class VoiceInputController {
const emitPreview = (text: string): void => {
const normalized = text.replace(/\r\n?/g, '\n').trim();
if (!normalized || normalized === request.text) return;
- if (runId !== this.runId || this.currentRunCancelled) return;
+ // Same reason as finishRefinement's check: once the run has failed, its
+ // host is showing an error — streaming refinement previews into it would
+ // rewrite text the user was just told the session stopped producing.
+ if (runId !== this.runId || this.currentRunCancelled || this.state === 'error') return;
if (this.callbacks.isRangeUserTouched?.(range) ?? range.userTouched) return;
this.callbacks.onRefinementPreview?.(normalized, {
...segment,
@@ -533,7 +620,7 @@ export class VoiceInputController {
private discardRefinement(
runId: string,
request: PendingRefinement | undefined,
- reason: 'final_text_changed' | 'stale_run' | 'cancelled' | 'no_submitted_text' | 'no_editable_range',
+ reason: 'final_text_changed' | 'stale_run' | 'cancelled' | 'no_submitted_text' | 'no_editable_range' | 'run_failed',
): void {
if (!request) return;
this.logger.record({
@@ -563,8 +650,61 @@ export class VoiceInputController {
}
this.stopStallWatchdog();
this.pendingStableResolvers.splice(0).forEach((resolve) => resolve(undefined));
+ // Salvage before the terminal state: hosts tear the draft down when they see
+ // 'error', so the submitted text has to reach them first.
+ this.salvageTranscript();
this.setState('error', 'failed');
- this.callbacks.onError?.(message, code);
+ // Retention travels as a detail, never as the code: `message` may be the
+ // only thing telling the user their credential expired or their quota ran
+ // out. transcriptEmitted covers both salvage and a stop() that submitted
+ // before the failure landed (a recovery rejecting during refinement).
+ this.callbacks.onError?.(message, code, { transcriptKept: this.transcriptEmitted });
+ }
+
+ /**
+ * Hand already-recognized text to the host before entering the error state.
+ *
+ * A socket that dies mid-dictation used to discard everything the user had
+ * said so far: partials only ever existed as a host-side draft, and fail()
+ * never offered them to onSubmitted. The transcript is worth more than the
+ * dead session, so commit it raw — refinement needs the same network that
+ * just failed — and let the host report the failure with transcriptKept set.
+ *
+ * The host's returned range is the acceptance signal. A host can legitimately
+ * refuse: mobile stops writing into the voice insertion once the user has
+ * edited it, so the text never lands. Claiming retention there would tell the
+ * user their words were kept when the tail was actually dropped.
+ */
+ private salvageTranscript(): boolean {
+ if (this.transcriptEmitted || this.submitCallbackThrew) return false;
+ const text = normalizeSubmittedText(this.latestTranscript);
+ if (!text) return false;
+ const segment: SpeechSegment = {
+ id: createVoiceInputId(),
+ source: 'mic',
+ status: 'submitted',
+ text,
+ updatedAt: Date.now(),
+ };
+ let accepted = false;
+ try {
+ accepted = Boolean(this.callbacks.onSubmitted(text, segment));
+ } catch {
+ // A host that cannot take the text (destroyed window, torn-down editor)
+ // must not also swallow the error report the user is waiting for.
+ accepted = false;
+ }
+ this.logger.record({
+ type: 'transcript_salvaged',
+ runId: this.runId,
+ at: Date.now(),
+ text,
+ source: this.latestTranscriptSource,
+ accepted,
+ });
+ if (!accepted) return false;
+ this.transcriptEmitted = true;
+ return true;
}
private resetStallCounters(): void {
@@ -664,7 +804,7 @@ export class VoiceInputController {
reason,
});
this.stopStallWatchdog();
- this.fail('Voice input stopped receiving recognition. Please try again.');
+ this.fail('Voice input stopped receiving recognition. Please try again.', 'recognition_stalled');
})
.finally(() => {
if (runId !== this.runId) return;
diff --git a/packages/voice-input-core/src/__tests__/VoiceInputController.test.ts b/packages/voice-input-core/src/__tests__/VoiceInputController.test.ts
index 372d389b19..ccd5ed68d6 100644
--- a/packages/voice-input-core/src/__tests__/VoiceInputController.test.ts
+++ b/packages/voice-input-core/src/__tests__/VoiceInputController.test.ts
@@ -23,7 +23,12 @@ class FakeAsrProvider implements AsrProvider {
this.callback({ type: 'connected', at: Date.now() });
}
+ // Real providers await an in-flight recover() inside stop() (swallowing its
+ // rejection), so stop() is another window where a failure can land.
+ public stopHook: () => Promise<void> = async () => {};
+
async stop(): Promise<void> {
+ await this.stopHook();
this.callback({ type: 'disconnected', at: Date.now() });
}
@@ -45,6 +50,18 @@ class FakeAsrProvider implements AsrProvider {
}
}
+// A host that takes the text: salvage treats the returned range as the
+// acceptance signal, so stubs that mean "accepted" must return one.
+function acceptSubmission(text: string, segment: SpeechSegment): EditableRange {
+ return {
+ id: `range-${segment.id}`,
+ segmentIds: [segment.id],
+ startOffset: 0,
+ endOffset: text.length,
+ userTouched: false,
+ };
+}
+
function pcmChunk(amplitude: number): ArrayBuffer {
const samples = new Int16Array(160);
samples.fill(amplitude);
@@ -270,6 +287,483 @@ describe('VoiceInputController', () => {
}]);
});
+ it('keeps the transcript recognized before a fatal transport drop', async () => {
+ const asr = new FakeAsrProvider();
+ const submitted: string[] = [];
+ const errors: Array<{ message: string; code?: string; kept?: boolean }> = [];
+ const timeline: VoiceTimelineEvent[] = [];
+ const controller = new VoiceInputController({
+ asr,
+ logger: new VoiceTimelineLogger((event) => timeline.push(event)),
+ callbacks: {
+ onDraftChanged: () => {},
+ onSubmitted: (text, segment) => {
+ submitted.push(text);
+ return acceptSubmission(text, segment);
+ },
+ onError: (message, code, details) => errors.push({ message, code, kept: details?.transcriptKept }),
+ },
+ });
+
+ await controller.start();
+ asr.emit({ type: 'partial', text: 'half a sentence', at: Date.now() });
+ asr.emit({ type: 'disconnected', at: Date.now() });
+
+ expect(submitted).toEqual(['half a sentence']);
+ expect(errors).toEqual([{
+ message: 'Voice input connection was interrupted. Please try again.',
+ code: 'connection_interrupted',
+ kept: true,
+ }]);
+ expect(controller.currentState).toBe('error');
+ expect(timeline).toContainEqual(expect.objectContaining({
+ type: 'transcript_salvaged',
+ text: 'half a sentence',
+ source: 'partial',
+ }));
+ });
+
+ it('hands the transcript to the host before the terminal error state', async () => {
+ const asr = new FakeAsrProvider();
+ const calls: string[] = [];
+ const controller = new VoiceInputController({
+ asr,
+ logger: new VoiceTimelineLogger(),
+ callbacks: {
+ onStateChanged: (state) => calls.push(`state:${state}`),
+ onDraftChanged: () => {},
+ onSubmitted: (text, segment) => {
+ calls.push('submitted');
+ return acceptSubmission(text, segment);
+ },
+ onError: () => calls.push('error'),
+ },
+ });
+
+ await controller.start();
+ asr.emit({ type: 'stable', text: 'ordering matters', at: Date.now() });
+ asr.emit({ type: 'disconnected', at: Date.now() });
+
+ // Hosts drop their draft on 'error', so the text has to land first.
+ expect(calls).toEqual(['state:listening', 'submitted', 'state:error', 'error']);
+ });
+
+ it('keeps the transcript when stop-time flush fails', async () => {
+ const asr = new FakeAsrProvider();
+ asr.flush = async () => {
+ throw new Error('socket closed');
+ };
+ const submitted: string[] = [];
+ const errors: Array<{ message: string; code?: string; kept?: boolean }> = [];
+ const timeline: VoiceTimelineEvent[] = [];
+ const controller = new VoiceInputController({
+ asr,
+ logger: new VoiceTimelineLogger((event) => timeline.push(event)),
+ callbacks: {
+ onDraftChanged: () => {},
+ onSubmitted: (text, segment) => {
+ submitted.push(text);
+ return acceptSubmission(text, segment);
+ },
+ onError: (message, code, details) => errors.push({ message, code, kept: details?.transcriptKept }),
+ },
+ });
+
+ await controller.start();
+ asr.emit({ type: 'stable', text: 'kept text', at: Date.now() });
+ await controller.stop();
+
+ expect(submitted).toEqual(['kept text']);
+ expect(errors).toEqual([{ message: 'socket closed', code: undefined, kept: true }]);
+ expect(timeline).toContainEqual(expect.objectContaining({
+ type: 'transcript_salvaged',
+ text: 'kept text',
+ source: 'stable',
+ }));
+ });
+
+ it('does not submit twice when recovery rejects after stop already submitted', async () => {
+ const asr = new FakeAsrProvider();
+ let rejectRecover: ((error: Error) => void) | undefined;
+ asr.recover = () => new Promise<void>((_resolve, reject) => {
+ rejectRecover = reject;
+ });
+ const submitted: string[] = [];
+ const errors: Array<{ message: string; code?: string; kept?: boolean }> = [];
+ const controller = new VoiceInputController({
+ asr,
+ logger: new VoiceTimelineLogger(),
+ stableWaitMs: 0,
+ refiner: {
+ refine: () => new Promise<RefinementResult>(() => {}),
+ },
+ callbacks: {
+ onDraftChanged: () => {},
+ onSubmitted: (text, segment) => {
+ submitted.push(text);
+ return {
+ id: 'range-1',
+ segmentIds: [segment.id],
+ startOffset: 0,
+ endOffset: text.length,
+ userTouched: false,
+ };
+ },
+ onError: (message, code, details) => errors.push({ message, code, kept: details?.transcriptKept }),
+ },
+ });
+
+ await controller.start();
+ asr.emit({ type: 'partial', text: 'one submission only', at: Date.now() });
+ asr.emit({ type: 'disconnected', at: Date.now() });
+ await controller.stop();
+
+ expect(controller.currentState).toBe('refining');
+ expect(submitted).toEqual(['one submission only']);
+
+ rejectRecover?.(new Error('network down'));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(submitted).toEqual(['one submission only']);
+ expect(errors).toEqual([{
+ message: 'Voice input stopped receiving recognition. Please try again.',
+ code: 'recognition_stalled',
+ kept: true,
+ }]);
+ });
+
+ it('salvages the newest transcript when a partial follows a stable', async () => {
+ const asr = new FakeAsrProvider();
+ const submitted: string[] = [];
+ const timeline: VoiceTimelineEvent[] = [];
+ const controller = new VoiceInputController({
+ asr,
+ logger: new VoiceTimelineLogger((event) => timeline.push(event)),
+ callbacks: {
+ onDraftChanged: () => {},
+ onSubmitted: (text, segment) => {
+ submitted.push(text);
+ return acceptSubmission(text, segment);
+ },
+ },
+ });
+
+ await controller.start();
+ // Providers emit both lanes as the full aggregate transcript, so the partial
+ // for the utterance in progress already contains the completed one.
+ asr.emit({ type: 'stable', text: 'first sentence.', at: Date.now() });
+ asr.emit({ type: 'partial', text: 'first sentence. second sen', at: Date.now() });
+ asr.emit({ type: 'disconnected', at: Date.now() });
+
+ expect(submitted).toEqual(['first sentence. second sen']);
+ expect(timeline).toContainEqual(expect.objectContaining({
+ type: 'transcript_salvaged',
+ source: 'partial',
+ }));
+ });
+
+ it('does not resubmit when a failure lands while stop is flushing', async () => {
+ const asr = new FakeAsrProvider();
+ let rejectRecover: ((error: Error) => void) | undefined;
+ asr.recover = () => new Promise<void>((_resolve, reject) => {
+ rejectRecover = reject;
+ });
+ let releaseFlush: (() => void) | undefined;
+ asr.flush = () => new Promise<void>((resolve) => {
+ releaseFlush = resolve;
+ });
+ const submitted: string[] = [];
+ const errors: Array<{ message: string; code?: string; kept?: boolean }> = [];
+ const controller = new VoiceInputController({
+ asr,
+ logger: new VoiceTimelineLogger(),
+ stableWaitMs: 0,
+ callbacks: {
+ onDraftChanged: () => {},
+ onSubmitted: (text, segment) => {
+ submitted.push(text);
+ return acceptSubmission(text, segment);
+ },
+ onError: (message, code, details) => errors.push({ message, code, kept: details?.transcriptKept }),
+ },
+ });
+
+ await controller.start();
+ asr.emit({ type: 'partial', text: 'only once', at: Date.now() });
+ asr.emit({ type: 'disconnected', at: Date.now() });
+
+ const stopPromise = controller.stop();
+ await Promise.resolve();
+
+ rejectRecover?.(new Error('network down'));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(submitted).toEqual(['only once']);
+ expect(controller.currentState).toBe('error');
+
+ // Providers await an in-flight recover() during flushAudio() but swallow its
+ // rejection, so stop() resumes on an already-failed run.
+ releaseFlush?.();
+ await stopPromise;
+
+ expect(submitted).toEqual(['only once']);
+ expect(controller.currentState).toBe('error');
+ expect(errors).toEqual([{
+ message: 'Voice input stopped receiving recognition. Please try again.',
+ code: 'recognition_stalled',
+ kept: true,
+ }]);
+ });
+
+ it('does not resubmit when a failure lands while the provider is stopping', async () => {
+ const asr = new FakeAsrProvider();
+ let rejectRecover: ((error: Error) => void) | undefined;
+ asr.recover = () => new Promise<void>((_resolve, reject) => {
+ rejectRecover = reject;
+ });
+ let releaseStop: (() => void) | undefined;
+ asr.stopHook = () => new Promise<void>((resolve) => {
+ releaseStop = resolve;
+ });
+ const submitted: string[] = [];
+ const errors: Array<{ message: string; code?: string; kept?: boolean }> = [];
+ const controller = new VoiceInputController({
+ asr,
+ logger: new VoiceTimelineLogger(),
+ stableWaitMs: 0,
+ callbacks: {
+ onDraftChanged: () => {},
+ onSubmitted: (text, segment) => {
+ submitted.push(text);
+ return acceptSubmission(text, segment);
+ },
+ onError: (message, code, details) => errors.push({ message, code, kept: details?.transcriptKept }),
+ },
+ });
+
+ await controller.start();
+ asr.emit({ type: 'partial', text: 'only once', at: Date.now() });
+ asr.emit({ type: 'disconnected', at: Date.now() });
+
+ const stopPromise = controller.stop();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ // The run fails while stop() is parked on the provider's stop(), i.e. after
+ // the flush window has already closed.
+ rejectRecover?.(new Error('network down'));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(submitted).toEqual(['only once']);
+ expect(controller.currentState).toBe('error');
+
+ releaseStop?.();
+ await stopPromise;
+
+ expect(submitted).toEqual(['only once']);
+ expect(controller.currentState).toBe('error');
+ });
+
+ it('does not strand the run when the host throws on submit', async () => {
+ const asr = new FakeAsrProvider();
+ const errors: Array<{ message: string; code?: string; kept?: boolean }> = [];
+ let submitAttempts = 0;
+ const controller = new VoiceInputController({
+ asr,
+ logger: new VoiceTimelineLogger(),
+ stableWaitMs: 0,
+ callbacks: {
+ onDraftChanged: () => {},
+ onSubmitted: () => {
+ // e.g. the composer's window was destroyed while stop() was in flight
+ submitAttempts += 1;
+ throw new Error('editor is gone');
+ },
+ onError: (message, code, details) => errors.push({ message, code, kept: details?.transcriptKept }),
+ },
+ });
+
+ await controller.start();
+ asr.emit({ type: 'partial', text: 'nowhere to go', at: Date.now() });
+ await expect(controller.stop()).resolves.toBeUndefined();
+
+ // A terminal state is what lets the next dictation start at all.
+ expect(controller.currentState).toBe('error');
+ expect(errors).toEqual([{ message: 'editor is gone', code: undefined, kept: false }]);
+ // Exactly one attempt: a callback that threw part-way has already run an
+ // unknown share of its side effects, so salvage must not run it again.
+ expect(submitAttempts).toBe(1);
+ await expect(controller.start()).resolves.toMatch(/./);
+ });
+
+ it('does not claim retention when the host refuses the salvaged text', async () => {
+ const asr = new FakeAsrProvider();
+ const timeline: VoiceTimelineEvent[] = [];
+ const errors: Array<{ message: string; code?: string; kept?: boolean }> = [];
+ const controller = new VoiceInputController({
+ asr,
+ logger: new VoiceTimelineLogger((event) => timeline.push(event)),
+ callbacks: {
+ onDraftChanged: () => {},
+ // Mobile refuses writes once the user has edited the voice insertion,
+ // so the salvaged text never lands in the composer.
+ onSubmitted: () => undefined,
+ onError: (message, code, details) => errors.push({ message, code, kept: details?.transcriptKept }),
+ },
+ });
+
+ await controller.start();
+ asr.emit({ type: 'partial', text: 'never lands', at: Date.now() });
+ asr.emit({ type: 'disconnected', at: Date.now() });
+
+ expect(errors).toEqual([{
+ message: 'Voice input connection was interrupted. Please try again.',
+ code: 'connection_interrupted',
+ kept: false,
+ }]);
+ expect(timeline).toContainEqual(expect.objectContaining({
+ type: 'transcript_salvaged',
+ accepted: false,
+ }));
+ });
+
+ it('logs an interrupted stop as cancelled when the user cancelled', async () => {
+ const asr = new FakeAsrProvider();
+ // stop() and cancel() each await the provider's stop(); hold both and
+ // release them together, otherwise the first one never settles.
+ const stopResolvers: Array<() => void> = [];
+ asr.stopHook = () => new Promise<void>((resolve) => {
+ stopResolvers.push(resolve);
+ });
+ const timeline: VoiceTimelineEvent[] = [];
+ const controller = new VoiceInputController({
+ asr,
+ logger: new VoiceTimelineLogger((event) => timeline.push(event)),
+ stableWaitMs: 0,
+ refiner: {
+ refine: () => new Promise<RefinementResult>(() => {}),
+ },
+ callbacks: {
+ onDraftChanged: () => {},
+ onSubmitted: (text, segment) => ({
+ id: 'range-1',
+ segmentIds: [segment.id],
+ startOffset: 0,
+ endOffset: text.length,
+ userTouched: false,
+ }),
+ },
+ });
+
+ await controller.start();
+ asr.emit({ type: 'partial', text: 'abandoned', at: Date.now() });
+ const stopPromise = controller.stop();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ const cancelPromise = controller.cancel();
+ stopResolvers.splice(0).forEach((resolve) => resolve());
+ await cancelPromise;
+ stopResolvers.splice(0).forEach((resolve) => resolve());
+ await stopPromise;
+
+ expect(timeline).toContainEqual(expect.objectContaining({
+ type: 'refine_discarded',
+ reason: 'cancelled',
+ }));
+ expect(timeline).not.toContainEqual(expect.objectContaining({
+ type: 'refine_discarded',
+ reason: 'run_failed',
+ }));
+ });
+
+ it('does not let a late refinement overwrite a failed run', async () => {
+ const asr = new FakeAsrProvider();
+ let rejectRecover: ((error: Error) => void) | undefined;
+ asr.recover = () => new Promise<void>((_resolve, reject) => {
+ rejectRecover = reject;
+ });
+ let resolveRefine: ((result: RefinementResult) => void) | undefined;
+ const applied: string[] = [];
+ const states: VoiceInputState[] = [];
+ const controller = new VoiceInputController({
+ asr,
+ logger: new VoiceTimelineLogger(),
+ stableWaitMs: 0,
+ refiner: {
+ refine: () => new Promise<RefinementResult>((resolve) => {
+ resolveRefine = resolve;
+ }),
+ },
+ callbacks: {
+ onStateChanged: (state) => states.push(state),
+ onDraftChanged: () => {},
+ onSubmitted: (text, segment) => ({
+ id: 'range-1',
+ segmentIds: [segment.id],
+ startOffset: 0,
+ endOffset: text.length,
+ userTouched: false,
+ }),
+ applyRefinement: (_range, refinedText) => {
+ applied.push(refinedText);
+ return true;
+ },
+ onError: () => {},
+ },
+ });
+
+ await controller.start();
+ asr.emit({ type: 'partial', text: 'text under refinement', at: Date.now() });
+ asr.emit({ type: 'disconnected', at: Date.now() });
+ await controller.stop();
+ expect(controller.currentState).toBe('refining');
+
+ // Recovery gives up while refinement is still running.
+ rejectRecover?.(new Error('network down'));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(controller.currentState).toBe('error');
+
+ resolveRefine?.({
+ accepted: true,
+ sourceSegmentIds: ['segment-1'],
+ basedOnText: 'text under refinement',
+ refinedText: 'Text under refinement.',
+ elapsedMs: 1,
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ // The user was already told the run failed; refinement must not rewrite
+ // their text nor flip the run back to a success state.
+ expect(applied).toEqual([]);
+ expect(controller.currentState).toBe('error');
+ expect(states.at(-1)).toBe('error');
+ });
+
+ it('reports the original failure cause alongside the retention flag', async () => {
+ const asr = new FakeAsrProvider();
+ const errors: Array<{ message: string; code?: string; kept?: boolean }> = [];
+ const controller = new VoiceInputController({
+ asr,
+ logger: new VoiceTimelineLogger(),
+ callbacks: {
+ onDraftChanged: () => {},
+ onSubmitted: acceptSubmission,
+ onError: (message, code, details) => errors.push({ message, code, kept: details?.transcriptKept }),
+ },
+ });
+
+ await controller.start();
+ asr.emit({ type: 'partial', text: 'said something', at: Date.now() });
+ // An auth/quota failure must not be flattened into "the connection dropped":
+ // retention rides along as a detail so hosts can show both.
+ asr.emit({ type: 'error', message: 'Voice credential expired.', at: Date.now() });
+
+ expect(errors).toEqual([{ message: 'Voice credential expired.', code: undefined, kept: true }]);
+ });
+
it('ignores stop-time ASR errors after transcript text is available', async () => {
const asr = new FakeAsrProvider();
const errors: string[] = [];
diff --git a/packages/voice-input-core/src/types.ts b/packages/voice-input-core/src/types.ts
index 0ff479f82a..902066e394 100644
--- a/packages/voice-input-core/src/types.ts
+++ b/packages/voice-input-core/src/types.ts
@@ -8,7 +8,33 @@ export type VoiceInputState =
export type VoiceInputTerminalOutcome = 'success' | 'no_speech' | 'failed' | 'cancelled';
-export type VoiceInputErrorCode = 'empty_transcript';
+/**
+ * Classifies the failures this controller raises itself, so hosts can show a
+ * localized sentence instead of the English `message` (which stays as the
+ * log/debug string). Failures originating in a provider have no code — their
+ * message is the only description of an auth, quota or protocol problem, so the
+ * controller passes it through unchanged. How it is presented is the host's
+ * call: current hosts still normalize transport strings and redact credentials
+ * before showing it, so "no code" means "the controller has nothing to add",
+ * not "display this raw".
+ */
+export type VoiceInputErrorCode =
+ | 'empty_transcript'
+ | 'connection_interrupted'
+ | 'recognition_stalled';
+
+/**
+ * Side facts about a failure, kept separate from its classification.
+ *
+ * `transcriptKept` means the text recognized before the failure still reached
+ * the host through onSubmitted. It is deliberately NOT an error code: the run
+ * can fail from an expired credential, an exhausted quota or a dropped socket,
+ * and the host must keep telling the user that actual cause — the retention
+ * note belongs alongside it, not instead of it.
+ */
+export type VoiceInputErrorDetails = {
+ transcriptKept: boolean;
+};
export type AsrEvent =
| { type: 'connected'; at: number }
@@ -161,7 +187,7 @@ export type VoiceTimelineEvent =
| { type: 'stable_received'; runId: string; at: number; text: string }
| { type: 'submitted'; runId: string; at: number; text: string; source: 'stable' | 'partial' }
| { type: 'refine_requested'; runId: string; at: number; text: string }
- | { type: 'refine_discarded'; runId: string; at: number; reason: 'final_text_changed' | 'stale_run' | 'cancelled' | 'no_submitted_text' | 'no_editable_range'; basedOnText: string }
+ | { type: 'refine_discarded'; runId: string; at: number; reason: 'final_text_changed' | 'stale_run' | 'cancelled' | 'no_submitted_text' | 'no_editable_range' | 'run_failed'; basedOnText: string }
| { type: 'refine_accepted'; runId: string; at: number; basedOnText: string; refinedText: string; elapsedMs: number }
| {
type: 'refine_rejected';
@@ -198,16 +224,40 @@ export type VoiceTimelineEvent =
| { type: 'asr_recovery_succeeded'; runId: string; at: number; elapsedMs: number }
| { type: 'asr_recovery_failed'; runId: string; at: number; elapsedMs: number; reason: string }
| { type: 'asr_stop_error_ignored'; runId: string; at: number; message: string; textChars: number }
+ // No failure message here: fail() records the 'error' event with the same
+ // runId immediately before salvaging, so the cause is already in the timeline
+ // — and unlike `text`, hosts don't redact this event's other fields.
+ // `accepted` is false when the host refused the text (e.g. the user had
+ // already edited the voice insertion), which is exactly when the retention
+ // flag must NOT be reported to the user.
+ | {
+ type: 'transcript_salvaged';
+ runId: string;
+ at: number;
+ text: string;
+ source: 'stable' | 'partial';
+ accepted: boolean;
+ }
| { type: 'error'; runId: string; at: number; message: string };
export type VoiceInputCallbacks = {
onStateChanged?: (state: VoiceInputState, outcome?: VoiceInputTerminalOutcome) => void;
onDraftChanged: (text: string, segment: SpeechSegment, source: VoiceInputDraftSource) => void;
+ /**
+ * Take the final text. The returned range doubles as the acceptance signal:
+ * return one only when the text actually landed somewhere the user can see,
+ * and `undefined` when it did not (e.g. the user already edited the insertion
+ * region). The controller reports `transcriptKept` from this answer, so a host
+ * that synthesizes a range without knowing the outcome — a bridge that emits
+ * to another process and answers synchronously — will make the controller
+ * promise retention it cannot back. Such hosts must correct the claim on the
+ * side that does know (see the desktop inline composer).
+ */
onSubmitted: (text: string, segment: SpeechSegment) => EditableRange | undefined;
isRangeUserTouched?: (range: EditableRange) => boolean;
onRefinementPreview?: (text: string, segment: SpeechSegment, range: EditableRange) => void;
applyRefinement?: (range: EditableRange, refinedText: string) => boolean;
- onError?: (message: string, code?: VoiceInputErrorCode) => void;
+ onError?: (message: string, code?: VoiceInputErrorCode, details?: VoiceInputErrorDetails) => void;
};
export type RefinementTokenUsage = {
@@ -226,4 +276,4 @@ export type VoiceInputRendererEvent =
| { type: 'refined'; runId: string; text: string; segment: SpeechSegment; range: EditableRange }
| { type: 'usage'; runId: string; refinement: RefinementTokenUsage }
| { type: 'timeline'; runId: string; event: VoiceTimelineEvent }
- | { type: 'error'; runId: string; message: string; code?: VoiceInputErrorCode };
+ | { type: 'error'; runId: string; message: string; code?: VoiceInputErrorCode; transcriptKept?: boolean };