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
fix(ui): show realtime voice preview inline (#1236)
Call White43a1edc1699b
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsxindex a1443fbb3..ae8745572 100644--- a/ui/src/components/workbench/Composer.tsx+++ b/ui/src/components/workbench/Composer.tsx@@ -17,9 +17,8 @@ import { primeCloudToken } from '../../lib/avibeFetch';import { isSoftKeyboardOpen, isTouchCapableDevice } from '../../lib/softKeyboard';import { cn, copyTextToClipboard } from '../../lib/utils';import {- applyVoiceInsertion,+ applyVoiceInsertionWithSnapshot,voiceInsertionSnapshot,- voiceInsertionText,type VoiceInsertionSnapshot,} from '../../lib/voiceCleanup';import {@@ -122,6 +121,7 @@ type VoiceRecordingSession = {finalization?: Promise<void>;transcriptionQueue: VoiceTranscriptionQueue;insertion: VoiceInsertionSnapshot;+ previewInsertion?: VoiceInsertionSnapshot;cleanupOutcome?: VoiceCleanupOutcome;cleanupElapsedMs?: number;realtime?: VoiceRealtimeSession;@@ -414,7 +414,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function ComposessionId != null && voiceSessionLocksDraft(voiceSessionsById.get(sessionId))));const [recordingSeconds, setRecordingSeconds] = useState(0);- const [realtimePreview, setRealtimePreview] = useState('');+ const [realtimeAnnouncement, setRealtimeAnnouncement] = useState('');const [transcribing, setTranscribing] = useState(false);const [voiceRetainedSession, setVoiceRetainedSession] = useState<VoiceRecordingSession | null>(null);const transcribingRef = useRef(false);@@ -520,6 +520,9 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function CompounmountedRef.current = false;return () => {unmountedRef.current = true;+ if (recordingSessionRef.current) {+ recordingSessionRef.current.previewInsertion = undefined;+ }try {if (recordingStartRef.current) {recordingSessionRef.current?.abortController.abort();@@ -539,7 +542,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo// the composer by session.useEffect(() => {setAttachments([]);- setRealtimePreview('');+ setRealtimeAnnouncement('');setVoiceRetainedSession(null);setRestoringRecording(sessionId != null && voiceSessionLocksDraft(voiceSessionsById.get(sessionId)),@@ -657,23 +660,81 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo}, [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.+ // Replace the active preview (or the original captured range when realtime+ // never produced one) with the finalized transcript as one draft edit.if (useMentions) {- return mentionRef.current?.replaceSelection(session.insertion, session.transcript ?? '') ?? false;+ const inserted = mentionRef.current?.commitVoicePreview(+ session.insertion,+ session.transcript ?? '',+ ) ?? false;+ if (inserted) setRealtimeAnnouncement('');+ return inserted;}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;+ const result = applyVoiceInsertionWithSnapshot(+ current,+ session.previewInsertion ?? session.insertion,+ session.transcript ?? '',+ session.insertion,+ );+ if (result === null) return false;+ session.previewInsertion = undefined;+ valueRef.current = result.text;+ setValue(result.text);+ setRealtimeAnnouncement('');+ onDraftChange?.(result.text);+ const caret = session.insertion.start + result.insertion.length;requestAnimationFrame(() => textareaRef.current?.setSelectionRange(caret, caret));return true;}, [onDraftChange, useMentions]);+ const restoreRealtimePreview = useCallback((session: VoiceRecordingSession): void => {+ setRealtimeAnnouncement('');+ if (useMentions) {+ mentionRef.current?.restoreVoicePreview();+ return;+ }+ const preview = session.previewInsertion;+ session.previewInsertion = undefined;+ if (preview === undefined || valueRef.current !== preview.text) return;+ valueRef.current = session.insertion.text;+ setValue(session.insertion.text);+ }, [useMentions]);++ const showRealtimePreview = useCallback((+ session: VoiceRecordingSession,+ preview: string,+ ): void => {+ const normalized = preview.trim();+ if (!normalized) {+ restoreRealtimePreview(session);+ return;+ }+ if (useMentions) {+ if (mentionRef.current?.showVoicePreview(session.insertion, normalized)) {+ setRealtimeAnnouncement(normalized);+ }+ return;+ }+ const current = valueRef.current;+ const result = applyVoiceInsertionWithSnapshot(+ current,+ session.previewInsertion ?? session.insertion,+ normalized,+ session.insertion,+ );+ if (result === null) return;+ session.previewInsertion = result.snapshot;+ valueRef.current = result.text;+ setValue(result.text);+ setRealtimeAnnouncement(normalized);+ }, [restoreRealtimePreview, useMentions]);++ const retainSettledVoiceSession = useCallback((session: VoiceRecordingSession): void => {+ restoreRealtimePreview(session);+ setVoiceRetainedSession(session);+ }, [restoreRealtimePreview]);+const queueVoiceSegment = (session: VoiceRecordingSession,blob: Blob,@@ -723,11 +784,11 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compoif (session.status === 'ready' && session.transcript) {if (disabledRef.current) {- setVoiceRetainedSession(session);+ retainSettledVoiceSession(session);return;}if (!insertVoiceTranscript(session)) {- setVoiceRetainedSession(session);+ retainSettledVoiceSession(session);showToast(t('chat.compose.voiceDraftChanged'), 'error');return;}@@ -737,10 +798,10 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Comporeturn;}if (session.status === 'failed') {- setVoiceRetainedSession(session);+ retainSettledVoiceSession(session);showToast(t(voiceErrorTranslationKey(session.error)), 'error');}- }, [insertVoiceTranscript, sessionId, showToast, t]);+ }, [insertVoiceTranscript, retainSettledVoiceSession, sessionId, showToast, t]);const finishVoiceSession = async (session: VoiceRecordingSession) => {const activeHere = !unmountedRef.current && sessionId === session.sessionId;@@ -799,7 +860,6 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compoawait session.finalization;presentVoiceSession(session);} finally {- setRealtimePreview('');if (recordingSessionRef.current === session) recordingSessionRef.current = null;if (activeHere) {transcribingRef.current = false;@@ -823,9 +883,10 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compoconst discardVoiceSession = useCallback((session: VoiceRecordingSession) => {session.abortController.abort();+ restoreRealtimePreview(session);deleteMapValueIfCurrent(voiceSessionsById, session.sessionId, session);setVoiceRetainedSession((current) => (current === session ? null : current));- }, []);+ }, [restoreRealtimePreview]);const copyReadyVoiceTranscript = useCallback(async (session: VoiceRecordingSession) => {if (!session.transcript) return;@@ -918,7 +979,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function CompoonPreview: (preview) => {if (recordingSessionRef.current !== session || unmountedRef.current) return;session.realtimeFirstPreviewAt ??= Date.now();- setRealtimePreview(`${preview.text}${preview.stash}`.trim());+ showRealtimePreview(session, `${preview.text}${preview.stash}`.trim());},onError: () => {if (abortController.signal.aborted) return;@@ -979,14 +1040,14 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compoif (reason === 'abort') {session.abortController.abort();session.realtime?.abort();- setRealtimePreview('');+ restoreRealtimePreview(session);deleteMapValueIfCurrent(voiceSessionsById, session.sessionId, session);return;}session.backlogAtStop = (session.backlogAtStop ?? 0) + metadata.pendingSegmentCount;if (!session.segments.length && session.captureError === undefined) {session.realtime?.abort();- setRealtimePreview('');+ restoreRealtimePreview(session);reportVoiceFinalization(session, 'empty');if (!unmountedRef.current && sessionId === session.sessionId) {showToast(t('chat.compose.voiceEmpty'), 'error');@@ -1041,7 +1102,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo// threw. Release it so the mic does not stay on.startingSession?.abortController.abort();startingSession?.realtime?.abort();- setRealtimePreview('');+ if (startingSession) restoreRealtimePreview(startingSession);if (recorderRef.current === startingPipeline) recorderRef.current = null;if (recordingSessionRef.current === startingSession) recordingSessionRef.current = null;clearRecordingTimers();@@ -1212,15 +1273,11 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo))}</div>)}- {recording && realtimePreview && (- <div- className="truncate px-3 text-xs text-muted"- aria-live="polite"- aria-label={t('chat.compose.voicePreview')}- >- {realtimePreview}- </div>- )}+ <div className="sr-only" role="status" aria-live="polite" aria-atomic="true">+ {realtimeAnnouncement+ ? `${t('chat.compose.voicePreview')}: ${realtimeAnnouncement}`+ : ''}+ </div><divclassName={cn('flex w-full items-end gap-1.5 rounded-2xl border border-border-strong bg-surface-2 py-2 pr-2 shadow-[0_-4px_24px_-12px_rgba(0,0,0,0.5)]',@@ -1367,7 +1424,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function CompoonPasteFiles={mediaEnabled && !disabled && !voiceDraftReadOnly? (files) => void uploadFiles(files): undefined}- onChange={(text, references, isDraftSeed) => {+ onChange={(text, references, isDraftSeed, isVoicePreview) => {// 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// re-render when the empty/non-empty state actually flips (React@@ -1379,7 +1436,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo// is at best a redundant write, and under a stale-props remount it// would save the previous session's draft under this session id// (mirrors the plain-textarea path, whose seeding never saves).- if (!isDraftSeed) onDraftChange?.(text);+ if (!isDraftSeed && !isVoicePreview) onDraftChange?.(text);}}onSubmit={submit}/>diff --git a/ui/src/components/workbench/MentionEditor.tsx b/ui/src/components/workbench/MentionEditor.tsxindex fba65053a..d4cf47bed 100644--- a/ui/src/components/workbench/MentionEditor.tsx+++ b/ui/src/components/workbench/MentionEditor.tsx@@ -27,6 +27,8 @@ import {$isTextNode,$setSelection,COMMAND_PRIORITY_HIGH,+ HISTORIC_TAG,+ HISTORY_PUSH_TAG,KEY_ENTER_COMMAND,PASTE_COMMAND,type EditorState,@@ -48,8 +50,8 @@ import { isSoftKeyboardOpen, isTouchCapableDevice } from '../../lib/softKeyboardimport { cn } from '../../lib/utils';import { dedupeReferences, type MentionReference } from '../../lib/mentions';import {+ applyVoiceInsertionWithSnapshot,voiceInsertionSnapshot,- voiceInsertionText,type VoiceInsertionSnapshot,} from '../../lib/voiceCleanup';import { useLatestRef } from '@/lib/useLatestRef';@@ -73,6 +75,15 @@ export interface MentionEditorHandle {/** 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;+ /** Render a transient voice preview inside the captured range. Successive+ * previews replace one another without persisting as draft edits. */+ showVoicePreview: (snapshot: VoiceInsertionSnapshot, text: string) => boolean;+ /** Replace the active preview, or the original captured range, with the final+ * cleaned transcript as one ordinary draft edit. */+ commitVoicePreview: (snapshot: VoiceInsertionSnapshot, text: string) => boolean;+ /** Restore the rich editor state captured before the first voice preview.+ * Refuses to restore if the user has changed the draft since that preview. */+ restoreVoicePreview: () => 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@@ -95,7 +106,12 @@ export interface MentionEditorProps {/** ``isDraftSeed`` flags the change produced by the mount-time draft seed* (BootstrapPlugin), so callers can mirror the value without treating the* restore as a user edit (e.g. skip re-persisting it as a draft). */- onChange: (text: string, references: MentionReference[], isDraftSeed?: boolean) => void;+ onChange: (+ text: string,+ references: MentionReference[],+ isDraftSeed?: boolean,+ isVoicePreview?: boolean,+ ) => void;onSubmit: () => void;onSearchAgents: (query: string) => Promise<AgentSearchResult[]>;onSearchSessions: (query: string) => Promise<SessionSearchResult[]>;@@ -427,6 +443,7 @@ function PasteFilesPlugin({ onPasteFiles }: { onPasteFiles?: (files: File[]) =>// Update tag for the mount-time draft seed, so OnChange can tell "restored a// saved draft" apart from a real user edit (restoring must not re-persist).const DRAFT_SEED_TAG = 'avibe-draft-seed';+const VOICE_PREVIEW_TAG = 'avibe-voice-preview';function BootstrapPlugin({autoFocus,@@ -440,82 +457,141 @@ function BootstrapPlugin({const [editor] = useLexicalComposerContext();const { insertMention: insertBeautifulMention } = useBeautifulMentions();const seeded = useRef(false);+ const voicePreviewRef = useRef<{+ originalState: EditorState;+ insertion: VoiceInsertionSnapshot;+ } | null>(null);useImperativeHandle(bridgeRef,- () => ({- focus: () => editor.focus(),- clear: () =>- editor.update(() => {- const root = $getRoot();- root.clear();- root.append($createParagraphNode());- }),- append: (text: string) =>- editor.update(() => {- const root = $getRoot();- const selection = root.selectEnd();- 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;+ () => {+ const replaceCapturedSelection = (+ replacement: VoiceInsertionSnapshot,+ text: string,+ tag?: string | string[],+ insertion: VoiceInsertionSnapshot = replacement,+ ): VoiceInsertionSnapshot | null => {+ let inserted: VoiceInsertionSnapshot | null = null;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);+ const result = applyVoiceInsertionWithSnapshot(+ current,+ replacement,+ text,+ insertion,+ );+ if (result === null) return;+ const start = serializedPointAtOffset(replacement.start);+ const end = serializedPointAtOffset(replacement.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();- root.clear();- const paragraph = $createParagraphNode();- root.append(paragraph);- if (text) paragraph.selectStart().insertText(text);+ selection.insertText(result.insertion);+ inserted = result.snapshot;+ }, tag ? { tag } : undefined);+ return inserted;+ };++ return {+ focus: () => editor.focus(),+ clear: () => {+ voicePreviewRef.current = null;+ editor.update(() => {+ const root = $getRoot();+ root.clear();+ root.append($createParagraphNode());+ });+ },+ append: (text: string) =>+ editor.update(() => {+ const root = $getRoot();+ const selection = root.selectEnd();+ 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));}),- // Insert at the live selection (Lexical keeps it across DOM blur), then- // focus so the user can keep typing. Produces the same node a typed- // `#`/`@` pick does, so serialization (#<id> + references) is identical.- insertMention: (trigger, value, data) =>- insertBeautifulMention({ trigger, value, data: data ?? {}, focus: true }),- }),+ replaceSelection: (snapshot, text) => replaceCapturedSelection(snapshot, text) !== null,+ showVoicePreview: (snapshot, text) => {+ if (!text.trim()) return voicePreviewRef.current !== null;+ const active = voicePreviewRef.current;+ const originalState = active?.originalState ?? editor.getEditorState();+ const insertion = replaceCapturedSelection(+ active?.insertion ?? snapshot,+ text,+ [VOICE_PREVIEW_TAG, HISTORIC_TAG],+ snapshot,+ );+ if (insertion === null) {+ voicePreviewRef.current = null;+ return false;+ }+ voicePreviewRef.current = { originalState, insertion };+ return true;+ },+ commitVoicePreview: (snapshot, text) => {+ const active = voicePreviewRef.current;+ const inserted = replaceCapturedSelection(+ active?.insertion ?? snapshot,+ text,+ HISTORY_PUSH_TAG,+ snapshot,+ );+ if (inserted !== null) voicePreviewRef.current = null;+ return inserted !== null;+ },+ restoreVoicePreview: () => {+ const active = voicePreviewRef.current;+ if (active === null) return false;+ const current = editor.getEditorState().read(() => serializeCurrentEditor().text);+ voicePreviewRef.current = null;+ if (current !== active.insertion.text) return false;+ editor.setEditorState(active.originalState, { tag: HISTORIC_TAG });+ return true;+ },+ setText: (text: string) => {+ voicePreviewRef.current = null;+ editor.update(() => {+ const root = $getRoot();+ root.clear();+ const paragraph = $createParagraphNode();+ root.append(paragraph);+ if (text) paragraph.selectStart().insertText(text);+ });+ },+ // Insert at the live selection (Lexical keeps it across DOM blur), then+ // focus so the user can keep typing. Produces the same node a typed+ // `#`/`@` pick does, so serialization (#<id> + references) is identical.+ insertMention: (trigger, value, data) =>+ insertBeautifulMention({ trigger, value, data: data ?? {}, focus: true }),+ };+ },[editor, insertBeautifulMention],);@@ -698,7 +774,12 @@ export const MentionEditor = forwardRef<MentionEditorHandle, MentionEditorProps>const handleChange = useCallback((state: EditorState, _editor: unknown, tags: Set<string>) => {const { text, references } = serializeEditorState(state);- onChange(text, references, tags.has(DRAFT_SEED_TAG));+ onChange(+ text,+ references,+ tags.has(DRAFT_SEED_TAG),+ tags.has(VOICE_PREVIEW_TAG),+ );},[onChange],);diff --git a/ui/src/components/workbench/MentionEditor.voicePreview.test.tsx b/ui/src/components/workbench/MentionEditor.voicePreview.test.tsxnew file mode 100644index 000000000..66b30dcf3--- /dev/null+++ b/ui/src/components/workbench/MentionEditor.voicePreview.test.tsx@@ -0,0 +1,142 @@+/* @vitest-environment jsdom */++import { createRef } from 'react';+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++vi.hoisted(() => {+ Object.defineProperty(window, 'matchMedia', {+ configurable: true,+ value: vi.fn().mockReturnValue({ matches: false }),+ });+});++import { voiceInsertionSnapshot } from '../../lib/voiceCleanup';+import { MentionEditor, type MentionEditorHandle } from './MentionEditor';++afterEach(cleanup);++const renderEditor = (initialText = '') => {+ const ref = createRef<MentionEditorHandle>();+ const onChange = vi.fn();+ render(+ <MentionEditor+ ref={ref}+ initialText={initialText}+ placeholder="Message"+ onChange={onChange}+ onSubmit={vi.fn()}+ onSearchAgents={async () => []}+ onSearchSessions={async () => []}+ />,+ );+ return { ref, onChange };+};++describe('MentionEditor voice preview', () => {+ it('replaces successive previews inline before committing the cleaned result', async () => {+ const { ref, onChange } = renderEditor('Plan today');+ const editor = screen.getByLabelText('Message');+ await waitFor(() => expect(editor.textContent).toBe('Plan today'));++ act(() => {+ expect(ref.current?.showVoicePreview(+ voiceInsertionSnapshot('Plan today', 5, 5),+ 'the lau',+ )).toBe(true);+ });+ await waitFor(() => expect(editor.textContent).toBe('Plan the lau today'));++ act(() => {+ expect(ref.current?.showVoicePreview(+ voiceInsertionSnapshot('Plan today', 5, 5),+ 'the launch',+ )).toBe(true);+ });+ await waitFor(() => expect(editor.textContent).toBe('Plan the launch today'));+ expect(onChange.mock.calls.at(-1)?.[3]).toBe(true);++ act(() => {+ expect(ref.current?.commitVoicePreview(+ voiceInsertionSnapshot('Plan today', 5, 5),+ 'The launch is tomorrow.',+ )).toBe(true);+ });+ await waitFor(() => expect(editor.textContent).toBe('Plan The launch is tomorrow. today'));+ expect(onChange.mock.calls.at(-1)?.[3]).toBe(false);+ });++ it('restores the original rich editor state when recording is discarded', async () => {+ const { ref } = renderEditor();+ const editor = screen.getByLabelText('Message');+ await waitFor(() => expect(ref.current).not.toBeNull());++ act(() => {+ ref.current?.setText('Ask ');+ ref.current?.insertMention('@', 'Alice', { agentId: 'agt-alice' });+ });+ await waitFor(() => expect(editor.querySelector('[data-beautiful-mention="@Alice"]')).not.toBeNull());+ const snapshot = ref.current!.captureSelection();++ act(() => {+ expect(ref.current?.showVoicePreview(snapshot, 'the team')).toBe(true);+ });+ await waitFor(() => expect(editor.textContent).toContain('the team'));++ act(() => {+ expect(ref.current?.restoreVoicePreview()).toBe(true);+ });+ await waitFor(() => expect(editor.querySelector('[data-beautiful-mention="@Alice"]')).not.toBeNull());+ });++ it('treats previews as transient while keeping the final transcript undoable', async () => {+ const { ref } = renderEditor('Plan today');+ const editor = screen.getByLabelText('Message');+ await waitFor(() => expect(editor.textContent).toBe('Plan today'));+ const snapshot = voiceInsertionSnapshot('Plan today', 5, 5);++ act(() => {+ ref.current?.showVoicePreview(snapshot, 'the lau');+ });+ await waitFor(() => expect(editor.textContent).toBe('Plan the lau today'));+ act(() => {+ ref.current?.showVoicePreview(snapshot, 'the launch');+ });+ await waitFor(() => expect(editor.textContent).toBe('Plan the launch today'));+ act(() => {+ ref.current?.commitVoicePreview(snapshot, 'The launch is tomorrow.');+ });+ await waitFor(() => expect(editor.textContent).toBe('Plan The launch is tomorrow. today'));++ const apple = /Mac|iPod|iPhone|iPad/.test(navigator.platform);+ fireEvent.keyDown(editor, {+ key: 'z',+ code: 'KeyZ',+ ctrlKey: !apple,+ metaKey: apple,+ });+ await waitFor(() => expect(editor.textContent).toBe('Plan today'));+ });++ it('restores the captured draft when a realtime hypothesis is retracted', async () => {+ const { ref } = renderEditor('Plan today');+ const editor = screen.getByLabelText('Message');+ await waitFor(() => expect(editor.textContent).toBe('Plan today'));+ const snapshot = voiceInsertionSnapshot('Plan today', 5, 5);++ act(() => {+ ref.current?.showVoicePreview(snapshot, 'the lau');+ });+ await waitFor(() => expect(editor.textContent).toBe('Plan the lau today'));++ act(() => {+ expect(ref.current?.restoreVoicePreview()).toBe(true);+ });+ await waitFor(() => expect(editor.textContent).toBe('Plan today'));++ act(() => {+ expect(ref.current?.showVoicePreview(snapshot, 'the launch')).toBe(true);+ });+ await waitFor(() => expect(editor.textContent).toBe('Plan the launch today'));+ });+});diff --git a/ui/src/lib/voiceCleanup.test.ts b/ui/src/lib/voiceCleanup.test.tsindex 8f7aea482..fcd2362f5 100644--- a/ui/src/lib/voiceCleanup.test.ts+++ b/ui/src/lib/voiceCleanup.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import {applyVoiceInsertion,+ applyVoiceInsertionWithSnapshot,voiceInsertionSnapshot,voiceInsertionText,} from './voiceCleanup';@@ -147,4 +148,44 @@ describe('voice cleanup', () => {expect(applyVoiceInsertion('changed', snapshot, 'voice')).toBeNull();});+ it('keeps successive realtime previews in one replaceable draft range', () => {+ const original = voiceInsertionSnapshot('Plan today', 5, 5);+ const first = applyVoiceInsertionWithSnapshot(original.text, original, 'the lau');+ const second = first && applyVoiceInsertionWithSnapshot(+ first.text,+ first.snapshot,+ 'the launch',+ original,+ );+ const final = second && applyVoiceInsertionWithSnapshot(+ second.text,+ second.snapshot,+ 'The launch is tomorrow.',+ original,+ );++ expect(first?.text).toBe('Plan the lau today');+ expect(second?.text).toBe('Plan the launch today');+ expect(final?.text).toBe('Plan The launch is tomorrow. today');+ expect(final?.snapshot).toMatchObject({+ text: 'Plan The launch is tomorrow. today',+ start: 5,+ end: 29,+ });+ });++ it('recomputes final boundary spacing from the original caret', () => {+ const original = voiceInsertionSnapshot('Say hello', 3, 3);+ const preview = applyVoiceInsertionWithSnapshot(original.text, original, 'actually');+ const final = preview && applyVoiceInsertionWithSnapshot(+ preview.text,+ preview.snapshot,+ ', actually',+ original,+ );++ expect(preview?.text).toBe('Say actually hello');+ expect(final?.text).toBe('Say, actually hello');+ });+});diff --git a/ui/src/lib/voiceCleanup.ts b/ui/src/lib/voiceCleanup.tsindex 87ab80d58..c52356d29 100644--- a/ui/src/lib/voiceCleanup.ts+++ b/ui/src/lib/voiceCleanup.ts@@ -11,6 +11,12 @@ export type VoiceInsertionSnapshot = {rightBoundary?: string;};+export type VoiceInsertionResult = {+ text: string;+ insertion: string;+ snapshot: VoiceInsertionSnapshot;+};+type VoiceInsertionBoundaries = {left?: string;right?: string;@@ -131,12 +137,37 @@ export const voiceInsertionText = (}`;};+export const applyVoiceInsertionWithSnapshot = (+ currentText: string,+ replacement: VoiceInsertionSnapshot,+ transcript: string,+ insertion: VoiceInsertionSnapshot = replacement,+): VoiceInsertionResult | null => {+ if (currentText !== replacement.text) return null;+ const insertedText = voiceInsertionText(insertion.text, insertion, transcript);+ if (insertedText === null) return null;+ const text = `${currentText.slice(0, replacement.start)}${insertedText}${+ currentText.slice(replacement.end)+ }`;+ return {+ text,+ insertion: insertedText,+ snapshot: voiceInsertionSnapshot(+ text,+ replacement.start,+ replacement.start + insertedText.length,+ {+ left: insertion.leftBoundary,+ right: insertion.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)}`;+ return applyVoiceInsertionWithSnapshot(currentText, snapshot, transcript)?.text ?? null;};