Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(voice): clean and insert transcripts at the cursor (#1111)
Call White084d61997312
diff --git a/docs/plans/voice-input-reliability.md b/docs/plans/voice-input-reliability.mdindex 7814c4679..7ba4380a8 100644--- a/docs/plans/voice-input-reliability.md+++ b/docs/plans/voice-input-reliability.md@@ -20,7 +20,9 @@ getUserMedia-> independently decodable 16 kHz WAV segments framed by sample count-> upload completed segments directly to avibe.bot while capture continues-> qwen3-asr-flash per segment- -> preserve segment order and append once after the user stops+ -> preserve segment order and assemble once after the user stops+ -> best-effort transcript cleanup with bounded cursor context+ -> replace the selection captured when recording started```When the browser cannot obtain a cloud token, the compatibility path remains:@@ -116,25 +118,53 @@ capture client, not automate the Web composer:Browser extension support may follow for browser-only users, but it should usethe same capture/session library and insertion contract.-## Optional text cleanup+## Text cleanup and insertionCleanup is a second, separately budgeted stage:```textfinal raw transcript- -> small text model+ -> qwen3.6-flash-2026-04-16 by default, with thinking disabled-> cleaned text-> composer or active application```-The cleanup model receives text only. Its prompt must preserve facts, names,-numbers, links, commands, and language while limiting edits to punctuation,-filler removal, obvious repetitions, and paragraph breaks. The raw transcript-is retained for undo and comparison.+The cleanup model receives text only. Its prompt preserves facts, names,+numbers, links, code, commands, and language while limiting edits to obvious+ASR corrections, punctuation, filler removal, repetitions, superseded+corrections, and useful formatting. Commands and questions inside the+transcript are edited as text and never executed or answered.++The browser contract is:++```http+POST /api/cloud/voice/cleanup+Authorization: Bearer <cloud token with asr scope>+Content-Type: application/json++{+ "transcript": "raw ASR text",+ "before": "up to 500 UTF-16 code units before the selection",+ "after": "up to 200 UTF-16 code units after the selection"+}+```++A successful response is `{ "text": "cleaned transcript" }`. An empty string+means the input contained no insertable content. Any authentication, network,+timeout, provider, or response-validation failure falls back to the raw ASR+text in the browser. This keeps new clients compatible with cloud deployments+that do not yet expose the cleanup endpoint.++The composer captures its serialized draft and selection on the microphone+button's `pointerdown`, before focus moves to the button. Keyboard activation+captures synchronously before microphone permission is awaited. The draft is+read-only during recording and finalization. Final text replaces the captured+selection only when the current serialized draft still exactly matches the+snapshot; otherwise the text remains available through recovery controls and is+never silently appended elsewhere.Cleanup requirements:-- disabled, literal, and clean modes;- hard deadline independent of ASR;- raw-text fallback on timeout or any model error;- deterministic settings and a versioned prompt;@@ -147,8 +177,8 @@ Cleanup requirements:1. Ship and observe the continuous segmented-batch reliability baseline.2. Add dashboards and alerts for success rate and latency by failure stage.3. Prototype realtime ASR in the Web composer behind a feature flag.-4. Add the cleanup stage only after raw streaming ASR meets its latency and- reliability targets.+4. Observe cleanup latency, fallback rate, and edit quality before adding+ user-facing literal/clean modes.5. Extract the shared capture/session client for the native system-wide inputsurface.diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsxindex 0ca40fd16..2585cb6c0 100644--- a/ui/src/components/workbench/Composer.tsx+++ b/ui/src/components/workbench/Composer.tsx@@ -16,6 +16,14 @@ import { apiFetch } from '../../lib/apiFetch';import { primeCloudToken } from '../../lib/avibeFetch';import { isSoftKeyboardOpen, isTouchCapableDevice } from '../../lib/softKeyboard';import { cn, copyTextToClipboard } from '../../lib/utils';+import {+ applyVoiceInsertion,+ cleanupVoiceTranscript,+ voiceInsertionSnapshot,+ voiceInsertionText,+ type VoiceCleanupResult,+ type VoiceInsertionSnapshot,+} from '../../lib/voiceCleanup';import {transcribeVoiceSegments,VOICE_SEGMENT_MS,@@ -108,24 +116,39 @@ type VoiceRecordingSession = {captureError?: unknown;finalization?: Promise<void>;transcriptionQueue: VoiceTranscriptionQueue;+ insertion: VoiceInsertionSnapshot;+ cleanupOutcome?: VoiceCleanupResult['outcome'];+ cleanupElapsedMs?: number;};// Composer remounts when the user switches chats. Keep pending or retryable// audio outside the component; successful finalization retains transcript only.const voiceSessionsById = new Map<string, VoiceRecordingSession>();+const voiceSessionLocksDraft = (session?: VoiceRecordingSession): boolean => (+ session != null && ['recording', 'transcribing', 'ready'].includes(session.status)+);+const newVoiceDictationId = (): string => (globalThis.crypto?.randomUUID?.()?? `voice-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`);-const settleVoiceSession = (session: VoiceRecordingSession) => {+const settleVoiceSession = async (session: VoiceRecordingSession): Promise<void> => {try {- session.transcript = voiceTranscriptFromSegments(session.segments);+ const rawTranscript = voiceTranscriptFromSegments(session.segments);session.finalizedSegmentCount = session.segments.length;session.finalizedFailedSegmentCount = session.segments.filter((segment) => segment.error,).length;+ const cleanup = await cleanupVoiceTranscript(rawTranscript, session.insertion, {+ signal: session.abortController.signal,+ });+ if (session.abortController.signal.aborted) return;+ session.cleanupOutcome = cleanup.outcome;+ session.cleanupElapsedMs = cleanup.elapsedMs;+ if (!cleanup.text.trim()) throw new VoiceTranscriptionError('empty');+ session.transcript = cleanup.text;session.segments = [];session.error = undefined;session.status = 'ready';@@ -151,7 +174,10 @@ const finalizeVoiceSession = (session: VoiceRecordingSession): Promise<void> =>session.status = 'failed';return;}- settleVoiceSession(session);+ await settleVoiceSession(session);+ if (session.abortController.signal.aborted) {+ deleteMapValueIfCurrent(voiceSessionsById, session.sessionId, session);+ }})();return session.finalization;};@@ -171,7 +197,10 @@ const retryStoredVoiceSession = (session: VoiceRecordingSession): Promise<void>deleteMapValueIfCurrent(voiceSessionsById, session.sessionId, session);return;}- settleVoiceSession(session);+ await settleVoiceSession(session);+ if (session.abortController.signal.aborted) {+ deleteMapValueIfCurrent(voiceSessionsById, session.sessionId, session);+ }})();return session.finalization;};@@ -212,6 +241,7 @@ const reportVoiceFinalization = (session.finalizedFailedSegmentCount?? session.segments.filter((segment) => segment.error).length),+ elapsedMs: session.cleanupElapsedMs,backlogAtStop: session.backlogAtStop,totalDurationMs: session.stoppedAt == null || session.startedAt == null? undefined@@ -344,7 +374,11 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compoconst [attachments, setAttachments] = useState<ComposerAttachment[]>([]);const [asrAvailable, setAsrAvailable] = useState(false);const [asrMaxFileBytes, setAsrMaxFileBytes] = useState<number | null>(null);+ const [recordingStarting, setRecordingStarting] = useState(false);const [recording, setRecording] = useState(false);+ const [restoringRecording, setRestoringRecording] = useState(() => (+ sessionId != null && voiceSessionLocksDraft(voiceSessionsById.get(sessionId))+ ));const [recordingSeconds, setRecordingSeconds] = useState(0);const [transcribing, setTranscribing] = useState(false);const [voiceRetainedSession, setVoiceRetainedSession] = useState<VoiceRecordingSession | null>(null);@@ -352,6 +386,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compoconst recorderRef = useRef<VoiceRecordingPipeline | null>(null);const recordingSessionRef = useRef<VoiceRecordingSession | null>(null);const recordingStartRef = useRef(false);+ const pendingVoiceInsertionRef = useRef<VoiceInsertionSnapshot | null>(null);const recordingTickerRef = useRef<ReturnType<typeof setInterval> | null>(null);const unmountedRef = useRef(false);const disabledRef = useRef(disabled);@@ -359,6 +394,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo// Upload + voice are scoped to a session (the upload endpoint needs one); the// home composer leaves them off.const mediaEnabled = Boolean(sessionId);+ const voiceDraftReadOnly = recordingStarting || recording || restoringRecording || transcribing;useLayoutEffect(() => {disabledRef.current = disabled;@@ -469,6 +505,9 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function CompouseEffect(() => {setAttachments([]);setVoiceRetainedSession(null);+ setRestoringRecording(+ sessionId != null && voiceSessionLocksDraft(voiceSessionsById.get(sessionId)),+ );}, [sessionId]);const removeAttachment = (localId: string) => {@@ -546,27 +585,57 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo// Expose file staging so a chat-page-wide drop zone (ChatPage) can hand off// files dropped onto the transcript — the picker + chips still live here. No// deps array → always runs the latest uploadFiles closure for this session.+ const voiceDraftLocked = () => (+ recordingStartRef.current+ || recordingSessionRef.current !== null+ || transcribingRef.current+ || (+ sessionId != null+ && voiceSessionLocksDraft(voiceSessionsById.get(sessionId))+ )+ );useImperativeHandle(ref, () => ({addFiles: (files: File[]) => void uploadFiles(files),insertSessionReference: (refSessionId: string, title?: string | null) => {+ if (voiceDraftLocked()) return;// Same node a typed `#` pick yields: trigger `#`, label = title||id, data// carries the stable sessionId → serializes to `#<id>` + a session ref.mentionRef.current?.insertMention('#', title?.trim() || refSessionId, { sessionId: refSessionId });},- appendText: (text: string) => mentionRef.current?.append(text),+ appendText: (text: string) => {+ if (!voiceDraftLocked()) mentionRef.current?.append(text);+ },}));- const appendVoiceTranscript = useCallback((text: string) => {- // Voice input fills the draft and never sends it. Keeping the whole recording- // as one append also prevents an intermediate segment from being sent before- // the user has finished speaking.+ const captureVoiceInsertion = useCallback((): VoiceInsertionSnapshot => {if (useMentions) {- mentionRef.current?.append(text);- } else {- const next = valueRef.current ? `${valueRef.current} ${text}` : text;- setValue(next);- onDraftChange?.(next);+ return mentionRef.current?.captureSelection()+ ?? voiceInsertionSnapshot(valueRef.current, valueRef.current.length, valueRef.current.length);}+ const editor = textareaRef.current;+ return voiceInsertionSnapshot(+ valueRef.current,+ editor?.selectionStart ?? valueRef.current.length,+ editor?.selectionEnd ?? valueRef.current.length,+ );+ }, [useMentions]);++ const insertVoiceTranscript = useCallback((session: VoiceRecordingSession): boolean => {+ // Insert the finalized transcript as one atomic replacement. Segment-level+ // results never touch the draft while the user is still speaking.+ if (useMentions) {+ return mentionRef.current?.replaceSelection(session.insertion, session.transcript ?? '') ?? false;+ }+ const current = valueRef.current;+ const insertion = voiceInsertionText(current, session.insertion, session.transcript ?? '');+ const next = applyVoiceInsertion(current, session.insertion, session.transcript ?? '');+ if (insertion === null || next === null) return false;+ valueRef.current = next;+ setValue(next);+ onDraftChange?.(next);+ const caret = session.insertion.start + insertion.length;+ requestAnimationFrame(() => textareaRef.current?.setSelectionRange(caret, caret));+ return true;}, [onDraftChange, useMentions]);const queueVoiceSegment = (@@ -592,7 +661,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo&& voiceSessionsById.get(session.sessionId) === session);if (session.status === 'ready' && session.transcript) {- reportVoiceFinalization(session, 'success');+ reportVoiceFinalization(session, session.cleanupOutcome ?? 'success');} else if (session.status === 'failed') {reportVoiceFinalization(session, voiceTelemetryOutcome(session.error));}@@ -603,9 +672,13 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function ComposetVoiceRetainedSession(session);return;}+ if (!insertVoiceTranscript(session)) {+ setVoiceRetainedSession(session);+ showToast(t('chat.compose.voiceDraftChanged'), 'error');+ return;+ }voiceSessionsById.delete(session.sessionId);setVoiceRetainedSession(null);- appendVoiceTranscript(session.transcript);reportVoiceInsertion(session);return;}@@ -613,7 +686,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function ComposetVoiceRetainedSession(session);showToast(t(voiceErrorTranslationKey(session.error)), 'error');}- }, [appendVoiceTranscript, sessionId, showToast, t]);+ }, [insertVoiceTranscript, sessionId, showToast, t]);const finishVoiceSession = async (session: VoiceRecordingSession) => {const activeHere = !unmountedRef.current && sessionId === session.sessionId;@@ -667,11 +740,16 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compoconst restore = () => {if (!alive) return;const session = voiceSessionsById.get(sessionId);- if (!session) return;+ if (!session) {+ setRestoringRecording(false);+ return;+ }if (session.status === 'recording') {+ setRestoringRecording(true);timer = setTimeout(restore, 50);return;}+ setRestoringRecording(false);if (session.status === 'transcribing' && session.finalization) {transcribingRef.current = true;setTranscribing(true);@@ -693,7 +771,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo};}, [presentVoiceSession, sessionId]);- const startRecording = async () => {+ const startRecording = async (capturedInsertion?: VoiceInsertionSnapshot) => {if (!sessionId|| recordingStartRef.current@@ -701,7 +779,9 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo) {return;}+ const insertion = capturedInsertion ?? captureVoiceInsertion();recordingStartRef.current = true;+ setRecordingStarting(true);let stream: MediaStream | null = null;let startingPipeline: VoiceRecordingPipeline | null = null;let startingSession: VoiceRecordingSession | null = null;@@ -721,6 +801,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Composegments: [],status: 'recording',retryCount: 0,+ insertion,transcriptionQueue: new VoiceTranscriptionQueue({concurrency: VOICE_TRANSCRIPTION_CONCURRENCY,signal: abortController.signal,@@ -817,6 +898,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo}} finally {recordingStartRef.current = false;+ if (!unmountedRef.current) setRecordingStarting(false);}};@@ -827,9 +909,11 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function ComporecordingSessionRef.current?.abortController.abort();recorderRef.current?.abort();}, []);- const toggleRecording = () => {+ const toggleRecording = (pointerActivation: boolean) => {+ const pointerInsertion = pointerActivation ? pendingVoiceInsertionRef.current : null;+ pendingVoiceInsertionRef.current = null;if (recording) stopRecording();- else void startRecording();+ else void startRecording(pointerInsertion ?? captureVoiceInsertion());};// ESC aborts an in-progress recording (discard, no transcribe).@@ -859,8 +943,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo(hasComposerText || readyAttachments.length > 0)&& !uploading&& !disabled- && !recording- && !transcribing;+ && !voiceDraftReadOnly;// ``busy && disabled`` is an incoherent pair for ANY caller: ``disabled`` means// this composer may not act on the session, yet the busy branch renders an// ENABLED Stop button (it never consulted ``disabled``) and its "working"@@ -971,7 +1054,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Comporef={fileInputRef}type="file"multiple- disabled={disabled || recording}+ disabled={disabled || voiceDraftReadOnly}className="hidden"onChange={(e) => {if (e.target.files?.length) void uploadFiles(Array.from(e.target.files));@@ -988,7 +1071,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo// A disabled composer cannot send, so staging attachments is a// dead end. Opening a native picker can also hide the page, so// keep it unavailable until an active recording has stopped.- disabled={disabled || recording}+ disabled={disabled || voiceDraftReadOnly}aria-label={t('chat.compose.attach')}className="h-9 w-7 shrink-0">@@ -1002,17 +1085,26 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compotype="button"variant={recording ? 'secondary' : 'ghost'}size="icon"- onClick={toggleRecording}+ onPointerDown={() => {+ if (!recording) pendingVoiceInsertionRef.current = captureVoiceInsertion();+ }}+ onPointerCancel={() => {+ pendingVoiceInsertionRef.current = null;+ }}+ onContextMenu={() => {+ pendingVoiceInsertionRef.current = null;+ }}+ onClick={(event) => toggleRecording(event.detail > 0)}disabled={isVoiceControlDisabled(disabled,recording,- transcribing,+ transcribing || recordingStarting || restoringRecording,Boolean(voiceRetainedSession),)}aria-label={t(recording ? 'chat.compose.stopRecording' : 'chat.compose.voice')}className={clsx('h-9 w-7 shrink-0', recording && 'animate-pulse')}>- {transcribing ? (+ {transcribing || recordingStarting || restoringRecording ? (<Loader2 className="size-4 animate-spin" />) : recording ? (<Square className="size-4" />@@ -1080,7 +1172,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Comporef={mentionRef}className="flex-1"placeholder={busyControls ? t('chat.compose.placeholderBusy') : placeholder ?? t('chat.compose.placeholder')}- disabled={disabled}+ disabled={disabled || voiceDraftReadOnly}autoFocus={autoFocus}initialText={initialDraft}onSearchAgents={onSearchAgents!}@@ -1094,7 +1186,9 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo// editor is also set non-editable while disabled, which should keep// the paste event from reaching Lexical at all — this is the// explicit gate rather than a reliance on that.- onPasteFiles={mediaEnabled && !disabled ? (files) => void uploadFiles(files) : undefined}+ onPasteFiles={mediaEnabled && !disabled && !voiceDraftReadOnly+ ? (files) => void uploadFiles(files)+ : undefined}onChange={(text, references, isDraftSeed) => {// The editor owns the text; keep the live copy in a ref (no// re-render) so a fast IME isn't interrupted mid-insert, and only@@ -1131,6 +1225,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo// did, so a disabled composer still accepted typing (only the Send// button was inert). Fixed here so every caller inherits it.disabled={disabled}+ readOnly={voiceDraftReadOnly}placeholder={busyControls ? t('chat.compose.placeholderBusy') : placeholder ?? t('chat.compose.placeholder')}className="max-h-40 min-h-9 flex-1 resize-none bg-transparent py-2 text-[13px] leading-5 text-foreground outline-none placeholder:text-muted"/>diff --git a/ui/src/components/workbench/MentionEditor.tsx b/ui/src/components/workbench/MentionEditor.tsxindex 049fa3ae2..82f357095 100644--- a/ui/src/components/workbench/MentionEditor.tsx+++ b/ui/src/components/workbench/MentionEditor.tsx@@ -15,18 +15,22 @@ import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';import {$createParagraphNode,+ $createRangeSelection,$createTextNode,$getRoot,$getSelection,$isElementNode,$isLineBreakNode,+ $isNodeSelection,$isRangeSelection,$isTextNode,+ $setSelection,COMMAND_PRIORITY_HIGH,KEY_ENTER_COMMAND,PASTE_COMMAND,type EditorState,type LexicalNode,+ type PointType,} from 'lexical';import {BeautifulMentionsPlugin,@@ -42,6 +46,11 @@ import { filesFromClipboard } from '../../lib/clipboardFiles';import { isSoftKeyboardOpen, isTouchCapableDevice } from '../../lib/softKeyboard';import { cn } from '../../lib/utils';import { dedupeReferences, type MentionReference } from '../../lib/mentions';+import {+ voiceInsertionSnapshot,+ voiceInsertionText,+ type VoiceInsertionSnapshot,+} from '../../lib/voiceCleanup';export type AgentSearchResult = {name: string;@@ -56,6 +65,12 @@ export interface MentionEditorHandle {clear: () => void;/** Append free text at the end (voice transcript) without disturbing chips. */append: (text: string) => void;+ /** Capture the serialized draft and logical selection before a toolbar click+ * moves DOM focus away from the editor. */+ captureSelection: () => VoiceInsertionSnapshot;+ /** Replace a captured logical range while preserving untouched mention chips.+ * Returns false if the draft changed or the range can no longer be mapped. */+ replaceSelection: (snapshot: VoiceInsertionSnapshot, text: string) => boolean;/** Replace the whole editor with plain text (restore on a failed send). */setText: (text: string) => void;/** Insert a mention chip at the current cursor — same node a picker-selected@@ -138,13 +153,201 @@ function nodeToMarkerText(node: LexicalNode, refs: MentionReference[]): string {}function serializeEditorState(state: EditorState): { text: string; references: MentionReference[] } {- return state.read(() => {- const refs: MentionReference[] = [];- const blocks = $getRoot()- .getChildren()- .map((block) => nodeToMarkerText(block, refs));- return { text: blocks.join('\n'), references: dedupeReferences(refs) };- });+ return state.read(serializeCurrentEditor);+}++function serializeCurrentEditor(): { text: string; references: MentionReference[] } {+ const refs: MentionReference[] = [];+ const blocks = $getRoot()+ .getChildren()+ .map((block) => nodeToMarkerText(block, refs));+ return { text: blocks.join('\n'), references: dedupeReferences(refs) };+}++const serializedNodeLength = (node: LexicalNode): number => nodeToMarkerText(node, []).length;++// Mention markers and their visible chip titles use different coordinate+// systems. Keep leaf ranges in marker offsets and use visible text only when a+// captured boundary touches a mention chip.+type SerializedVisibleSegment = {+ start: number;+ end: number;+ visibleText: string;+ mention: boolean;+};++function serializedVisibleSegments(): SerializedVisibleSegment[] {+ const segments: SerializedVisibleSegment[] = [];+ const visit = (node: LexicalNode, base: number, rootLevel = false) => {+ if ($isBeautifulMentionNode(node) || $isLineBreakNode(node) || $isTextNode(node)) {+ const visibleText = $isBeautifulMentionNode(node)+ ? node.getValue()+ : node.getTextContent();+ segments.push({+ start: base,+ end: base + serializedNodeLength(node),+ visibleText,+ mention: $isBeautifulMentionNode(node),+ });+ return;+ }+ if (!$isElementNode(node)) return;+ let offset = base;+ const children = node.getChildren();+ for (let index = 0; index < children.length; index += 1) {+ visit(children[index], offset);+ offset += serializedNodeLength(children[index]);+ if (rootLevel && index < children.length - 1) {+ segments.push({ start: offset, end: offset + 1, visibleText: '\n', mention: false });+ offset += 1;+ }+ }+ };+ visit($getRoot(), 0, true);+ return segments;+}++function visibleBoundaryAtOffset(target: number, side: 'left' | 'right'): string | undefined {+ const segments = serializedVisibleSegments();+ const ordered = side === 'left' ? [...segments].reverse() : segments;+ for (const segment of ordered) {+ if (side === 'left' && target <= segment.start) continue;+ if (side === 'right' && target >= segment.end) continue;+ if (!segment.mention) return undefined;+ if (segment.end - segment.start === segment.visibleText.length) {+ const offset = Math.max(0, Math.min(target - segment.start, segment.visibleText.length));+ return side === 'left'+ ? (Array.from(segment.visibleText.slice(0, offset)).at(-1) ?? '')+ : (Array.from(segment.visibleText.slice(offset))[0] ?? '');+ }+ const characters = Array.from(segment.visibleText);+ return side === 'left' ? (characters.at(-1) ?? '') : (characters[0] ?? '');+ }+ return undefined;+}++type SerializedPoint = {+ key: string;+ offset: number;+ type: 'text' | 'element';+};++function serializedOffsetForPoint(point: PointType): number | null {+ const root = $getRoot();+ const visit = (node: LexicalNode, base: number, rootLevel = false): number | null => {+ if (node.getKey() === point.key) {+ if (point.type === 'text' && $isTextNode(node)) {+ const serialized = nodeToMarkerText(node, []);+ if ($isBeautifulMentionNode(node)) {+ return base + (point.offset === 0 ? 0 : serialized.length);+ }+ return base + Math.min(point.offset, serialized.length);+ }+ if (point.type === 'element' && $isElementNode(node)) {+ const children = node.getChildren();+ let offset = base;+ const childCount = Math.min(point.offset, children.length);+ for (let index = 0; index < childCount; index += 1) {+ offset += serializedNodeLength(children[index]);+ if (rootLevel && index < children.length - 1) offset += 1;+ }+ return offset;+ }+ }+ if (!$isElementNode(node)) return null;+ const children = node.getChildren();+ let offset = base;+ for (let index = 0; index < children.length; index += 1) {+ const found = visit(children[index], offset);+ if (found !== null) return found;+ offset += serializedNodeLength(children[index]);+ if (rootLevel && index < children.length - 1) offset += 1;+ }+ return null;+ };+ return visit(root, 0, true);+}++function serializedPointAtOffset(target: number): SerializedPoint | null {+ const visit = (node: LexicalNode, base: number, rootLevel = false): SerializedPoint | null => {+ if ($isTextNode(node)) {+ const serialized = nodeToMarkerText(node, []);+ const textLength = node.getTextContentSize();+ if ($isBeautifulMentionNode(node)) {+ if (target === base) return { key: node.getKey(), offset: 0, type: 'text' };+ if (target === base + serialized.length) {+ return { key: node.getKey(), offset: textLength, type: 'text' };+ }+ return null;+ }+ if (target >= base && target <= base + serialized.length) {+ return { key: node.getKey(), offset: target - base, type: 'text' };+ }+ return null;+ }+ if (!$isElementNode(node)) return null;+ const children = node.getChildren();+ let offset = base;+ if (target === offset) {+ if (!rootLevel) return { key: node.getKey(), offset: 0, type: 'element' };+ const first = children[0];+ if (!first) return null;+ return $isElementNode(first)+ ? { key: first.getKey(), offset: 0, type: 'element' }+ : visit(first, offset);+ }+ for (let index = 0; index < children.length; index += 1) {+ const childEnd = offset + serializedNodeLength(children[index]);+ if (target > offset && target < childEnd) {+ return visit(children[index], offset);+ }+ if (target === childEnd) {+ if (rootLevel) {+ const child = children[index];+ return $isElementNode(child)+ ? { key: child.getKey(), offset: child.getChildrenSize(), type: 'element' }+ : visit(child, offset);+ }+ return { key: node.getKey(), offset: index + 1, type: 'element' };+ }+ offset = childEnd;+ if (rootLevel && index < children.length - 1) {+ offset += 1;+ if (target === offset) {+ const next = children[index + 1];+ return $isElementNode(next)+ ? { key: next.getKey(), offset: 0, type: 'element' }+ : visit(next, offset);+ }+ }+ }+ return null;+ };+ return visit($getRoot(), 0, true);+}++function serializedRangeForNodes(nodes: LexicalNode[]): { start: number; end: number } | null {+ const selectedKeys = new Set(nodes.map((node) => node.getKey()));+ let start = Number.POSITIVE_INFINITY;+ let end = Number.NEGATIVE_INFINITY;+ const visit = (node: LexicalNode, base: number, rootLevel = false) => {+ const length = serializedNodeLength(node);+ if (selectedKeys.has(node.getKey())) {+ start = Math.min(start, base);+ end = Math.max(end, base + length);+ return;+ }+ if (!$isElementNode(node)) return;+ let offset = base;+ const children = node.getChildren();+ for (let index = 0; index < children.length; index += 1) {+ visit(children[index], offset);+ offset += serializedNodeLength(children[index]);+ if (rootLevel && index < children.length - 1) offset += 1;+ }+ };+ visit($getRoot(), 0, true);+ return Number.isFinite(start) && Number.isFinite(end) ? { start, end } : null;}// Enter submits — except Shift+Enter (newline), mid-IME composition (CJK), while@@ -254,6 +457,50 @@ function BootstrapPlugin({const prefix = root.getTextContent().length > 0 ? ' ' : '';selection.insertText(`${prefix}${text}`);}),+ captureSelection: () => editor.getEditorState().read(() => {+ const { text } = serializeCurrentEditor();+ const snapshotAt = (start: number, end: number) => voiceInsertionSnapshot(+ text,+ start,+ end,+ {+ left: visibleBoundaryAtOffset(start, 'left'),+ right: visibleBoundaryAtOffset(end, 'right'),+ },+ );+ const selection = $getSelection();+ if ($isNodeSelection(selection)) {+ const range = serializedRangeForNodes(selection.getNodes());+ if (range) return snapshotAt(range.start, range.end);+ }+ if (!$isRangeSelection(selection)) {+ return snapshotAt(text.length, text.length);+ }+ const anchor = serializedOffsetForPoint(selection.anchor);+ const focus = serializedOffsetForPoint(selection.focus);+ if (anchor === null || focus === null) {+ return snapshotAt(text.length, text.length);+ }+ return snapshotAt(Math.min(anchor, focus), Math.max(anchor, focus));+ }),+ replaceSelection: (snapshot, text) => {+ let replaced = false;+ editor.update(() => {+ const current = serializeCurrentEditor().text;+ const insertion = voiceInsertionText(current, snapshot, text);+ if (insertion === null) return;+ const start = serializedPointAtOffset(snapshot.start);+ const end = serializedPointAtOffset(snapshot.end);+ if (!start || !end) return;+ const selection = $createRangeSelection();+ selection.anchor.set(start.key, start.offset, start.type);+ selection.focus.set(end.key, end.offset, end.type);+ $setSelection(selection);+ selection.insertText(insertion);+ replaced = true;+ });+ return replaced;+ },setText: (text: string) =>editor.update(() => {const root = $getRoot();diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex d11453cd6..564d3c997 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -3035,6 +3035,7 @@"voiceEmpty": "No speech was detected in this recording.","voicePermissionFailed": "Microphone access failed. Check your browser permission and try again.","voiceStartFailed": "Voice recording could not start in this browser. Reload the page or try a supported browser.",+ "voiceDraftChanged": "The draft changed during voice input. The recovered transcript is available to copy.","removeAttachment": "Remove","dropOverlay": "Drop files to attach"},diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 278de1d4c..8c7617815 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -3035,6 +3035,7 @@"voiceEmpty": "这段录音中没有检测到语音。","voicePermissionFailed": "无法使用麦克风,请检查浏览器权限后重试。","voiceStartFailed": "当前浏览器无法启动语音录制,请刷新页面或更换支持的浏览器。",+ "voiceDraftChanged": "语音输入期间草稿已变化,已保留整理结果供复制。","removeAttachment": "移除","dropOverlay": "拖放文件以添加"},diff --git a/ui/src/lib/voiceCleanup.test.ts b/ui/src/lib/voiceCleanup.test.tsnew file mode 100644index 000000000..83f70e711--- /dev/null+++ b/ui/src/lib/voiceCleanup.test.ts@@ -0,0 +1,208 @@+import { describe, expect, it, vi } from 'vitest';++import {+ applyVoiceInsertion,+ cleanupVoiceTranscript,+ voiceInsertionSnapshot,+ voiceInsertionText,+} from './voiceCleanup';++describe('voice cleanup', () => {+ it('captures bounded context around the original selection', () => {+ const text = `${'a'.repeat(600)}SELECTED${'b'.repeat(300)}`;+ const snapshot = voiceInsertionSnapshot(text, 600, 608);++ expect(snapshot.before).toBe('a'.repeat(500));+ expect(snapshot.after).toBe('b'.repeat(200));+ expect(snapshot).toMatchObject({ text, start: 600, end: 608 });+ });++ it('replaces the original selection and adds only required Latin spaces', () => {+ const snapshot = voiceInsertionSnapshot('Write old text today', 6, 14);++ expect(voiceInsertionText(snapshot.text, snapshot, 'new plan')).toBe('new plan');+ expect(applyVoiceInsertion(snapshot.text, snapshot, 'new plan')).toBe('Write new plan today');+ });++ it('preserves whitespace consumed by a selected range', () => {+ const trailingSpace = voiceInsertionSnapshot('Write old today', 6, 10);+ const surroundingSpaces = voiceInsertionSnapshot('Write old today', 5, 10);++ expect(applyVoiceInsertion(trailingSpace.text, trailingSpace, 'new')).toBe('Write new today');+ expect(applyVoiceInsertion(surroundingSpaces.text, surroundingSpaces, 'new')).toBe(+ 'Write new today',+ );+ });++ it('does not add spaces at CJK boundaries', () => {+ const snapshot = voiceInsertionSnapshot('请旧内容确认', 1, 4);++ expect(applyVoiceInsertion(snapshot.text, snapshot, '后天发布')).toBe('请后天发布确认');+ });++ it('does not add spaces at Southeast Asian script boundaries', () => {+ const snapshot = voiceInsertionSnapshot('กข', 1, 1);++ expect(applyVoiceInsertion(snapshot.text, snapshot, 'ค')).toBe('กคข');+ });++ it('adds spaces at Latin mention boundaries without changing CJK boundaries', () => {+ const beforeLatinMention = voiceInsertionSnapshot('Ask @<Alice>', 4, 4);+ const afterLatinMention = voiceInsertionSnapshot('Ask @<Alice>', 12, 12);+ const beforeCjkMention = voiceInsertionSnapshot('问@<小明>', 1, 1);++ expect(applyVoiceInsertion(beforeLatinMention.text, beforeLatinMention, 'please tell')).toBe(+ 'Ask please tell @<Alice>',+ );+ expect(applyVoiceInsertion(afterLatinMention.text, afterLatinMention, 'now')).toBe(+ 'Ask @<Alice> now',+ );+ expect(applyVoiceInsertion(beforeCjkMention.text, beforeCjkMention, '一下')).toBe('问一下@<小明>');+ });++ it('uses visible mention titles instead of serialized ids for spacing', () => {+ const cjkSession = voiceInsertionSnapshot('Ask #<session-id>', 4, 4, { right: '项' });+ const latinSession = voiceInsertionSnapshot('Ask #<session-id>', 4, 4, { right: 'P' });+ const afterCjkSession = voiceInsertionSnapshot('#<session-id>', 13, 13, { left: '目' });++ expect(applyVoiceInsertion(cjkSession.text, cjkSession, 'check')).toBe('Ask check#<session-id>');+ expect(applyVoiceInsertion(latinSession.text, latinSession, 'check')).toBe('Ask check #<session-id>');+ expect(applyVoiceInsertion(afterCjkSession.text, afterCjkSession, 'now')).toBe('#<session-id>now');+ });++ it('adds Latin boundary spaces outside terminal and opening punctuation', () => {+ const beforeWord = voiceInsertionSnapshot('Send today', 5, 5);+ const afterLabel = voiceInsertionSnapshot('Note:publish', 5, 5);+ const beforeQuotedWord = voiceInsertionSnapshot('Say "today"', 4, 4);++ expect(applyVoiceInsertion(beforeWord.text, beforeWord, 'the update.')).toBe(+ 'Send the update. today',+ );+ expect(applyVoiceInsertion(afterLabel.text, afterLabel, 'now')).toBe('Note: now publish');+ expect(applyVoiceInsertion(beforeQuotedWord.text, beforeQuotedWord, 'please')).toBe(+ 'Say please "today"',+ );+ });++ it('adds spaces outside symbol-delimited code and command tokens', () => {+ const beforeWord = voiceInsertionSnapshot('Use today', 4, 4);+ const betweenWords = voiceInsertionSnapshot('Runnow', 3, 3);+ const sentencePunctuation = voiceInsertionSnapshot('Say hello', 3, 3);++ expect(applyVoiceInsertion(beforeWord.text, beforeWord, 'C++')).toBe('Use C++ today');+ expect(applyVoiceInsertion(betweenWords.text, betweenWords, '--verbose')).toBe(+ 'Run --verbose now',+ );+ expect(applyVoiceInsertion(sentencePunctuation.text, sentencePunctuation, ', actually')).toBe(+ 'Say, actually hello',+ );+ });++ it('treats combining marks as part of boundary words', () => {+ const afterNfdWord = voiceInsertionSnapshot('cafe\u0301today', 5, 5);+ const afterArabicWord = voiceInsertionSnapshot('عربي\u0651next', 5, 5);+ const beforeNfdWord = voiceInsertionSnapshot('Trytoday', 3, 3);++ expect(applyVoiceInsertion(afterNfdWord.text, afterNfdWord, 'notes')).toBe('cafe\u0301 notes today');+ expect(applyVoiceInsertion(afterArabicWord.text, afterArabicWord, 'notes')).toBe(+ 'عربي\u0651 notes next',+ );+ expect(applyVoiceInsertion(beforeNfdWord.text, beforeNfdWord, 'cafe\u0301')).toBe(+ 'Try cafe\u0301 today',+ );+ });++ it('preserves adjacency inside paired delimiters', () => {+ const insideParentheses = voiceInsertionSnapshot('print()', 6, 6);+ const insideQuotes = voiceInsertionSnapshot('Say ""', 5, 5);+ const afterClosedQuote = voiceInsertionSnapshot('Say "hi"today', 8, 8);++ expect(applyVoiceInsertion(insideParentheses.text, insideParentheses, 'value')).toBe(+ 'print(value)',+ );+ expect(applyVoiceInsertion(insideQuotes.text, insideQuotes, 'hello')).toBe('Say "hello"');+ expect(applyVoiceInsertion(afterClosedQuote.text, afterClosedQuote, 'again')).toBe(+ 'Say "hi" again today',+ );+ });++ it('preserves adjacency around code and path delimiters', () => {+ const memberCall = voiceInsertionSnapshot('object.()', 7, 7);+ const pathSegment = voiceInsertionSnapshot('/usr/bin', 5, 5);+ const sentence = voiceInsertionSnapshot('Done.today', 5, 5);++ expect(applyVoiceInsertion(memberCall.text, memberCall, 'method')).toBe('object.method()');+ expect(applyVoiceInsertion(pathSegment.text, pathSegment, 'local/')).toBe('/usr/local/bin');+ expect(applyVoiceInsertion(sentence.text, sentence, 'again')).toBe('Done. again today');+ });++ it('replaces selected token text without introducing spaces', () => {+ const snapshot = voiceInsertionSnapshot('v12beta', 1, 3);++ expect(applyVoiceInsertion(snapshot.text, snapshot, '13')).toBe('v13beta');+ });++ it('refuses to insert when the draft no longer matches the snapshot', () => {+ const snapshot = voiceInsertionSnapshot('original', 8, 8);++ expect(applyVoiceInsertion('changed', snapshot, 'voice')).toBeNull();+ });++ it('sends only bounded context and returns the cleaned text', async () => {+ const cloudFetch = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ text: '后天发布。' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ }),+ );+ const snapshot = voiceInsertionSnapshot('计划:。', 3, 3);++ await expect(cleanupVoiceTranscript('呃后天发布', snapshot, { cloudFetch })).resolves.toMatchObject({+ text: '后天发布。',+ outcome: 'success',+ });+ const [, init] = cloudFetch.mock.calls[0];+ expect(JSON.parse(String(init?.body))).toEqual({+ transcript: '呃后天发布',+ before: '计划:',+ after: '。',+ });+ });++ it('keeps raw ASR text when cleanup is unavailable or malformed', async () => {+ const snapshot = voiceInsertionSnapshot('', 0, 0);+ const unavailable = vi.fn().mockResolvedValue(new Response('{}', { status: 404 }));+ const malformed = vi.fn().mockResolvedValue(new Response('{}', { status: 200 }));+ const networkError = vi.fn().mockRejectedValue(new TypeError('network unavailable'));++ await expect(cleanupVoiceTranscript('raw', snapshot, { cloudFetch: unavailable })).resolves.toMatchObject({+ text: 'raw',+ outcome: 'fallback',+ });+ await expect(cleanupVoiceTranscript('raw', snapshot, { cloudFetch: malformed })).resolves.toMatchObject({+ text: 'raw',+ outcome: 'fallback',+ });+ await expect(cleanupVoiceTranscript('raw', snapshot, { cloudFetch: networkError })).resolves.toMatchObject({+ text: 'raw',+ outcome: 'fallback',+ });+ });++ it('preserves intentional empty output but falls back from whitespace-only output', async () => {+ const snapshot = voiceInsertionSnapshot('', 0, 0);+ const empty = vi.fn().mockResolvedValue(new Response(JSON.stringify({ text: '' }), { status: 200 }));+ const whitespace = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ text: ' ' }), { status: 200 }),+ );++ await expect(cleanupVoiceTranscript('raw', snapshot, { cloudFetch: empty })).resolves.toMatchObject({+ text: '',+ outcome: 'success',+ });+ await expect(cleanupVoiceTranscript('raw', snapshot, { cloudFetch: whitespace })).resolves.toMatchObject({+ text: 'raw',+ outcome: 'fallback',+ });+ });+});diff --git a/ui/src/lib/voiceCleanup.ts b/ui/src/lib/voiceCleanup.tsnew file mode 100644index 000000000..f7a1c6e1b--- /dev/null+++ b/ui/src/lib/voiceCleanup.ts@@ -0,0 +1,226 @@+import { avibeFetch } from './avibeFetch';++export const VOICE_CONTEXT_BEFORE_CHARS = 500;+export const VOICE_CONTEXT_AFTER_CHARS = 200;+export const VOICE_CLEANUP_TIMEOUT_MS = 35_000;++export type VoiceInsertionSnapshot = {+ text: string;+ start: number;+ end: number;+ before: string;+ after: string;+ leftBoundary?: string;+ rightBoundary?: string;+};++type VoiceInsertionBoundaries = {+ left?: string;+ right?: string;+};++type VoiceCleanupFetch = (+ path: string,+ init?: RequestInit,+) => Promise<Response>;++type VoiceCleanupDependencies = {+ cloudFetch?: VoiceCleanupFetch;+ timeoutMs?: number;+ signal?: AbortSignal;+};++export type VoiceCleanupResult = {+ text: string;+ outcome: 'success' | 'fallback';+ elapsedMs: number;+};++const boundedSelection = (text: string, start: number, end: number): [number, number] => {+ const safeStart = Math.max(0, Math.min(text.length, Math.floor(start)));+ const safeEnd = Math.max(safeStart, Math.min(text.length, Math.floor(end)));+ return [safeStart, safeEnd];+};++export const voiceInsertionSnapshot = (+ text: string,+ start: number,+ end: number,+ boundaries: VoiceInsertionBoundaries = {},+): VoiceInsertionSnapshot => {+ const [safeStart, safeEnd] = boundedSelection(text, start, end);+ return {+ text,+ start: safeStart,+ end: safeEnd,+ before: text.slice(Math.max(0, safeStart - VOICE_CONTEXT_BEFORE_CHARS), safeStart),+ after: text.slice(safeEnd, safeEnd + VOICE_CONTEXT_AFTER_CHARS),+ leftBoundary: boundaries.left,+ rightBoundary: boundaries.right,+ };+};++const WORD_CHARACTER = /[\p{L}\p{N}_]/u;+const NO_SPACE_SCRIPT = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u;+const MENTION_AT_START = /^[@#]<([^>\n]+)>/u;+const MENTION_AT_END = /[@#]<([^>\n]+)>$/u;+const LEADING_SENTENCE_PUNCTUATION = /^[.,!?:;…,。!?:;、](?:\s|$)/u;+const LEADING_OUTER_BOUNDARY = /^[\p{P}\p{S}]+/u;+const TRAILING_OUTER_BOUNDARY = /[\p{P}\p{S}]+$/u;+const LEADING_WORD_GRAPHEME = /^[\p{L}\p{N}_]\p{M}*/u;+const TRAILING_WORD_GRAPHEME = /[\p{L}\p{N}_]\p{M}*$/u;+const OPENING_DELIMITER = /^[\p{Ps}\p{Pi}]$/u;+const SYMMETRIC_DELIMITER = /^["'`]$/u;+const TRAILING_TOKEN_JOINER = /(?:[/\\]|::|->|\?\.)$/u;+const LEADING_CALL_DELIMITER = /^[([{]/u;++const edgeCharacter = (text: string, side: 'start' | 'end'): string => {+ const wordGrapheme = side === 'start'+ ? text.match(LEADING_WORD_GRAPHEME)+ : text.match(TRAILING_WORD_GRAPHEME);+ if (wordGrapheme) return wordGrapheme[0];+ const characters = Array.from(text);+ return side === 'start' ? (characters[0] ?? '') : (characters.at(-1) ?? '');+};++const endsWithOpeningDelimiter = (text: string): boolean => {+ const characters = Array.from(text);+ const delimiter = characters.at(-1) ?? '';+ if (OPENING_DELIMITER.test(delimiter)) return true;+ if (!SYMMETRIC_DELIMITER.test(delimiter)) return false;+ return !TRAILING_WORD_GRAPHEME.test(characters.slice(0, -1).join(''));+};++const joiningBoundaryCharacter = (text: string, followingText: string): string | undefined => {+ if (TRAILING_TOKEN_JOINER.test(text)) return edgeCharacter(text, 'end');+ if (text.endsWith('.') && LEADING_CALL_DELIMITER.test(followingText)) return '.';+ return undefined;+};++const boundaryCharacter = (text: string, side: 'start' | 'end'): string => {+ const directMention = side === 'start' ? text.match(MENTION_AT_START) : text.match(MENTION_AT_END);+ if (directMention) return edgeCharacter(directMention[1], side);+ if (side === 'end' && endsWithOpeningDelimiter(text)) return edgeCharacter(text, side);+ const boundaryText = side === 'start'+ ? (LEADING_SENTENCE_PUNCTUATION.test(text) ? text : text.replace(LEADING_OUTER_BOUNDARY, ''))+ : text.replace(TRAILING_OUTER_BOUNDARY, '');+ const mention = side === 'start'+ ? boundaryText.match(MENTION_AT_START)+ : boundaryText.match(MENTION_AT_END);+ if (mention) return edgeCharacter(mention[1], side);+ return edgeCharacter(boundaryText, side);+};++const needsBoundarySpace = (+ left: string,+ right: string,+ leftBoundary?: string,+ rightBoundary?: string,+): boolean => {+ const leftChar = leftBoundary ?? boundaryCharacter(left, 'end');+ const rightChar = rightBoundary ?? boundaryCharacter(right, 'start');+ return (+ WORD_CHARACTER.test(leftChar)+ && WORD_CHARACTER.test(rightChar)+ && !NO_SPACE_SCRIPT.test(leftChar)+ && !NO_SPACE_SCRIPT.test(rightChar)+ );+};++export const voiceInsertionText = (+ currentText: string,+ snapshot: VoiceInsertionSnapshot,+ transcript: string,+): string | null => {+ if (currentText !== snapshot.text) return null;+ const normalized = transcript.trim();+ if (!normalized) return '';+ if (snapshot.start !== snapshot.end) {+ const selected = currentText.slice(snapshot.start, snapshot.end);+ const leadingWhitespace = selected.match(/^\s+/u)?.[0] ?? '';+ const trailingWhitespace = selected.match(/\s+$/u)?.[0] ?? '';+ return `${leadingWhitespace}${normalized}${trailingWhitespace}`;+ }+ const left = currentText.slice(0, snapshot.start);+ const right = currentText.slice(snapshot.end);+ const leftBoundary = snapshot.leftBoundary+ ?? joiningBoundaryCharacter(left, right);+ const transcriptBoundary = joiningBoundaryCharacter(normalized, right);+ return `${needsBoundarySpace(left, normalized, leftBoundary) ? ' ' : ''}${normalized}${+ needsBoundarySpace(normalized, right, transcriptBoundary, snapshot.rightBoundary) ? ' ' : ''+ }`;+};++export const applyVoiceInsertion = (+ currentText: string,+ snapshot: VoiceInsertionSnapshot,+ transcript: string,+): string | null => {+ const insertion = voiceInsertionText(currentText, snapshot, transcript);+ if (insertion === null) return null;+ return `${currentText.slice(0, snapshot.start)}${insertion}${currentText.slice(snapshot.end)}`;+};++const timeoutSignal = (durationMs: number, externalSignal?: AbortSignal) => {+ const controller = new AbortController();+ const abortFromExternal = () => controller.abort(externalSignal?.reason);+ if (externalSignal?.aborted) {+ abortFromExternal();+ } else {+ externalSignal?.addEventListener('abort', abortFromExternal, { once: true });+ }+ const timer = globalThis.setTimeout(+ () => controller.abort(new DOMException('voice cleanup timed out', 'TimeoutError')),+ durationMs,+ );+ return {+ signal: controller.signal,+ cancel: () => {+ globalThis.clearTimeout(timer);+ externalSignal?.removeEventListener('abort', abortFromExternal);+ },+ };+};++// Cleanup is deliberately best-effort. Raw ASR text remains usable when an old+// cloud deployment lacks the endpoint or the small editing model is unavailable.+export const cleanupVoiceTranscript = async (+ transcript: string,+ snapshot: VoiceInsertionSnapshot,+ dependencies: VoiceCleanupDependencies = {},+): Promise<VoiceCleanupResult> => {+ const startedAt = Date.now();+ const result = (text: string, outcome: VoiceCleanupResult['outcome']): VoiceCleanupResult => ({+ text,+ outcome,+ elapsedMs: Date.now() - startedAt,+ });+ const request = timeoutSignal(+ dependencies.timeoutMs ?? VOICE_CLEANUP_TIMEOUT_MS,+ dependencies.signal,+ );+ try {+ const response = await (dependencies.cloudFetch ?? avibeFetch)(+ '/api/cloud/voice/cleanup',+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ transcript,+ before: snapshot.before,+ after: snapshot.after,+ }),+ signal: request.signal,+ },+ );+ if (!response.ok) return result(transcript, 'fallback');+ const payload = await response.json().catch(() => null) as { text?: unknown } | null;+ if (typeof payload?.text !== 'string') return result(transcript, 'fallback');+ if (payload.text !== '' && !payload.text.trim()) return result(transcript, 'fallback');+ return result(payload.text, 'success');+ } catch {+ return result(transcript, 'fallback');+ } finally {+ request.cancel();+ }+};