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(ui): bridge Show Page annotation voice input (#1808)
Call Whiteea0a9ce4fdf9
diff --git a/docs/plans/show-annotation-voice-bridge.md b/docs/plans/show-annotation-voice-bridge.mdnew file mode 100644index 000000000..4d689e8ee--- /dev/null+++ b/docs/plans/show-annotation-voice-bridge.md@@ -0,0 +1,54 @@+# Show Page Annotation Voice Bridge++## Goal++Let annotation text fields inside an embedded Show Page use Avibe's existing+voice dictation experience without adding a recording-duration or aggregate-file+limit and without implementing a second transcription stack in Show Runtime.++## Ownership++- The Show Page iframe owns the microphone button, field state, realtime preview,+ and final text insertion.+- The Avibe client owns microphone capture, realtime transcription, internal WAV+ segmentation, HTTP fallback, retry, and cleanup through the same modules used+ by Chat.+- One client-wide capture claim prevents hidden Chat and Show Page recorders from+ running concurrently. The host transfers ownership synchronously when it+ accepts an explicit start, before asynchronous availability or capture setup.+ A newer explicit voice action finishes the previous capture, and a capture+ stopped during setup still completes its buffered-audio finalization.+- The existing same-origin annotation `postMessage` boundary carries lifecycle+ commands and results. No server API or backend behavior changes are required.++## Contract++The iframe sends `query`, `start`, `stop`, `retry`, and `abort` requests with one+bounded request id. Start and retry carry the cleanup context that matches the+current insertion snapshot. The owning Chat frame sends availability, started,+preview, result, and typed error events. Both sides require the expected origin+and iframe window.++An unanswered start handshake times out and aborts without imposing any limit on+recording duration. Reloading the iframe disposes its old voice host, and ASR+availability is shared only while a request is in flight so later requests see+configuration changes and transient recovery.++## Known By Design++Unlimited recordings retain minute-sized browser Blob segments in the+in-session retry batch until transcription succeeds or the user explicitly+discards it. This matches Chat and permits re-upload when the server rejects a+previous segment receipt. The bridge does not persist voice audio to browser+storage and does not add a duration or aggregate-size cap, so memory use grows+with the audio that remains eligible for retry.++## Verification++- Show Runtime unit tests cover bridge validation, lifecycle, retry, punctuation+ insertion, and screenshot-comment field identity.+- Avibe UI tests cover host lifecycle, availability refresh, retry context, and+ client-wide capture ownership, and prove repeated internal minute segments do+ not end a recording.+- Existing Chat voice behavior continues to use the shared recording and+ transcription implementation; only cross-surface capture ownership is added.diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsxindex 3c5baf444..07a3ad75a 100644--- a/ui/src/components/workbench/Composer.tsx+++ b/ui/src/components/workbench/Composer.tsx@@ -42,8 +42,10 @@ import {type VoiceTelemetryOutcome,} from '../../lib/voiceTelemetry';import {+ claimVoiceCapture,deleteMapValueIfCurrent,isVoiceControlDisabled,+ type VoiceCaptureClaim,VoiceRecordingPipeline,} from '../../lib/voiceRecording';import {@@ -430,6 +432,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compoconst [voiceRetainedSession, setVoiceRetainedSession] = useState<VoiceRecordingSession | null>(null);const transcribingRef = useRef(false);const recorderRef = useRef<VoiceRecordingPipeline | null>(null);+ const voiceCaptureClaimRef = useRef<VoiceCaptureClaim | null>(null);const recordingSessionRef = useRef<VoiceRecordingSession | null>(null);const recordingStartRef = useRef(false);const pendingVoiceInsertionRef = useRef<VoiceInsertionSnapshot | null>(null);@@ -547,6 +550,8 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo} catch {/* already stopped */}+ voiceCaptureClaimRef.current?.release();+ voiceCaptureClaimRef.current = null;clearRecordingTimers();};}, [clearRecordingTimers]);@@ -961,9 +966,19 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compolet stream: MediaStream | null = null;let startingPipeline: VoiceRecordingPipeline | null = null;let startingSession: VoiceRecordingSession | null = null;+ const captureClaim = claimVoiceCapture(() => {+ try {+ if (startingPipeline) startingPipeline.finish();+ else stream?.getTracks().forEach((track) => track.stop());+ } catch {+ startingPipeline?.abort();+ stream?.getTracks().forEach((track) => track.stop());+ }+ });+ voiceCaptureClaimRef.current = captureClaim;try {stream = await navigator.mediaDevices.getUserMedia({ audio: true });- if (unmountedRef.current || disabledRef.current) {+ if (!captureClaim.isCurrent() || unmountedRef.current || disabledRef.current) {stream.getTracks().forEach((track) => track.stop());return;}@@ -1044,6 +1059,8 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo}},onStopped: (reason, metadata) => {+ captureClaim.release();+ if (voiceCaptureClaimRef.current === captureClaim) voiceCaptureClaimRef.current = null;if (recorderRef.current === pipeline) recorderRef.current = null;if (recordingSessionRef.current === session) recordingSessionRef.current = null;clearRecordingTimers();@@ -1088,6 +1105,10 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function ComporecorderRef.current = pipeline;const captureActive = await pipeline.start();if (!captureActive) return;+ if (!captureClaim.isCurrent()) {+ pipeline.finish();+ return;+ }if (unmountedRef.current || disabledRef.current) {pipeline.abort();return;@@ -1117,6 +1138,8 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compoif (startingSession) restoreRealtimePreview(startingSession);if (recorderRef.current === startingPipeline) recorderRef.current = null;if (recordingSessionRef.current === startingSession) recordingSessionRef.current = null;+ captureClaim.release();+ if (voiceCaptureClaimRef.current === captureClaim) voiceCaptureClaimRef.current = null;clearRecordingTimers();stream?.getTracks().forEach((track) => track.stop());if (!unmountedRef.current) {@@ -1128,6 +1151,10 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo), 'error');}} finally {+ if (recorderRef.current !== startingPipeline || recordingSessionRef.current !== startingSession) {+ captureClaim.release();+ if (voiceCaptureClaimRef.current === captureClaim) voiceCaptureClaimRef.current = null;+ }recordingStartRef.current = false;if (!unmountedRef.current) setRecordingStarting(false);}diff --git a/ui/src/components/workbench/useShowPageAnnotation.test.ts b/ui/src/components/workbench/useShowPageAnnotation.test.tsindex 4e5c654ab..a004a6465 100644--- a/ui/src/components/workbench/useShowPageAnnotation.test.ts+++ b/ui/src/components/workbench/useShowPageAnnotation.test.ts@@ -3,6 +3,7 @@import { act, renderHook } from '@testing-library/react';import { afterEach, describe, expect, it, vi } from 'vitest';+import { ShowPageVoiceHost } from '../../lib/showPageVoiceBridge';import { useShowPageAnnotation } from './useShowPageAnnotation';let teardown: (() => void) | null = null;@@ -11,6 +12,7 @@ afterEach(() => {teardown?.();teardown = null;document.body.replaceChildren();+ vi.restoreAllMocks();});const mountBridge = (initialSrc: string | null = '/show/session') => {@@ -75,6 +77,90 @@ const dispatchAnnotationShortcut = (target: EventTarget) => {return event;};+const dispatchFrameMessage = (+ iframe: HTMLIFrameElement,+ data: unknown,+ origin = window.location.origin,+ source: MessageEventSource | null = iframe.contentWindow,+) => {+ act(() => {+ window.dispatchEvent(new MessageEvent('message', { data, origin, source }));+ });+};++describe('useShowPageAnnotation voice boundary', () => {+ it('answers voice requests only from the attached same-origin iframe', async () => {+ const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(+ JSON.stringify({ available: false }),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ ));+ const { iframe } = mountBridge();+ const postMessage = vi.spyOn(iframe.contentWindow!, 'postMessage');+ const query = {+ type: 'avibe:annotation:voice:request',+ action: 'query',+ requestId: 'voice-probe',+ };++ dispatchFrameMessage(iframe, query, 'https://foreign.test');+ dispatchFrameMessage(iframe, query, window.location.origin, null);+ await Promise.resolve();+ expect(fetchMock).not.toHaveBeenCalled();++ dispatchFrameMessage(iframe, query);+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledWith(+ '/api/asr/status',+ expect.any(Object),+ ));+ await vi.waitFor(() => expect(postMessage).toHaveBeenCalledWith({+ type: 'avibe:annotation:voice:event',+ kind: 'availability',+ requestId: 'voice-probe',+ available: false,+ }, window.location.origin));+ });++ it('deduplicates only in-flight availability and refreshes after it settles', async () => {+ const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(+ JSON.stringify({ available: true, max_file_bytes: 1_000_000 }),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ ));+ const { iframe } = mountBridge();+ const postMessage = vi.spyOn(iframe.contentWindow!, 'postMessage');+ const statusCalls = () => fetchMock.mock.calls.filter(([url]) => url === '/api/asr/status');++ dispatchFrameMessage(iframe, {+ type: 'avibe:annotation:voice:request',+ action: 'query',+ requestId: 'voice-probe-1',+ });+ await vi.waitFor(() => expect(statusCalls()).toHaveLength(1));+ await vi.waitFor(() => expect(postMessage).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'availability', requestId: 'voice-probe-1' }),+ window.location.origin,+ ));++ dispatchFrameMessage(iframe, {+ type: 'avibe:annotation:voice:request',+ action: 'query',+ requestId: 'voice-probe-2',+ });+ await vi.waitFor(() => expect(statusCalls()).toHaveLength(2));+ });++ it('replaces the voice host and clears stale state on every iframe load', () => {+ const dispose = vi.spyOn(ShowPageVoiceHost.prototype, 'dispose');+ const { iframe, result } = mountBridge();+ reportState(iframe, true);+ dispose.mockClear();++ act(() => result.current.handleIframeLoad());++ expect(dispose).toHaveBeenCalledOnce();+ expect(result.current.state).toBeNull();+ });+});+describe('useShowPageAnnotation shortcut', () => {it('leaves the shortcut to the parent surface outside the Show Page frame', () => {const { iframe } = mountBridge();diff --git a/ui/src/components/workbench/useShowPageAnnotation.ts b/ui/src/components/workbench/useShowPageAnnotation.tsindex 5d4411c2a..a2b982028 100644--- a/ui/src/components/workbench/useShowPageAnnotation.ts+++ b/ui/src/components/workbench/useShowPageAnnotation.ts@@ -1,8 +1,15 @@-import { useCallback, useEffect, useRef, useState } from 'react';+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';import { actionShortcutMatches, isPlainEscape, useActionShortcuts } from '../../lib/actionShortcuts';+import { apiFetch } from '../../lib/apiFetch';+import { primeCloudToken } from '../../lib/avibeFetch';import { useLatestRef } from '../../lib/useLatestRef';import { useRouteSurfaceActive, useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';+import {+ ShowPageVoiceHost,+ type ShowPageVoiceAvailability,+ type ShowPageVoiceEvent,+} from '../../lib/showPageVoiceBridge';import { bindFrameChord } from '../apps/windowChords';// postMessage bridge between the chat host and the annotation overlay running@@ -67,10 +74,12 @@ function annotationShortcutBlocked(target: Element | null): boolean {export function useShowPageAnnotation(src: string | null): AnnotationBridge {const routeSurfaceActive = useRouteSurfaceActive();const iframeRef = useRef<HTMLIFrameElement | null>(null);+ const voiceHostRef = useRef<ShowPageVoiceHost | null>(null);const frameShortcutCleanupRef = useRef<() => void>(() => undefined);const [state, setState] = useState<AnnotationState | null>(null);const [lastSrc, setLastSrc] = useState(src);const { showPageAnnotation: annotationShortcut } = useActionShortcuts();+ const routeSurfaceActiveRef = useLatestRef(routeSurfaceActive);const stateRef = useLatestRef(state);const shortcutRef = useLatestRef(annotationShortcut);@@ -94,12 +103,16 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {const data = event.data as| { type?: unknown; enabled?: unknown; mode?: unknown; available?: unknown }| null;- if (!data || data.type !== 'avibe:annotation:state') return;- setState({- enabled: data.enabled === true,- mode: data.mode === 'screenshot' ? 'screenshot' : 'smart',- available: data.available === true,- });+ if (!data) return;+ if (data.type === 'avibe:annotation:state') {+ setState({+ enabled: data.enabled === true,+ mode: data.mode === 'screenshot' ? 'screenshot' : 'smart',+ available: data.available === true,+ });+ return;+ }+ voiceHostRef.current?.handle(event.data);}, []);const listeningRef = useRef(false);@@ -156,6 +169,50 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {if (win) win.postMessage(message, window.location.origin);}, []);+ const createVoiceHost = useCallback((iframe: HTMLIFrameElement): ShowPageVoiceHost => {+ let availability: Promise<ShowPageVoiceAvailability> | null = null;+ const loadAvailability = async (): Promise<ShowPageVoiceAvailability> => {+ try {+ const response = await apiFetch('/api/asr/status');+ const data = response.ok ? await response.json() : null;+ const available = data?.available === true;+ if (available) primeCloudToken();+ return {+ available,+ maxFileBytes: (+ typeof data?.max_file_bytes === 'number'+ && Number.isFinite(data.max_file_bytes)+ && data.max_file_bytes > 0+ )+ ? Math.floor(data.max_file_bytes)+ : null,+ };+ } catch {+ return { available: false, maxFileBytes: null };+ }+ };+ return new ShowPageVoiceHost({+ post: (event: ShowPageVoiceEvent) => {+ iframe.contentWindow?.postMessage(event, window.location.origin);+ },+ availability: () => {+ if (availability) return availability;+ const pending = loadAvailability();+ availability = pending;+ void pending.finally(() => {+ if (availability === pending) availability = null;+ });+ return pending;+ },+ });+ }, []);++ useLayoutEffect(() => {+ const iframe = iframeRef.current;+ voiceHostRef.current?.dispose();+ voiceHostRef.current = iframe ? createVoiceHost(iframe) : null;+ }, [createVoiceHost, src]);+const enable = useCallback((mode?: AnnotationMode) =>post(@@ -195,16 +252,19 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {(iframe) => {frameShortcutCleanupRef.current();frameShortcutCleanupRef.current = () => undefined;+ voiceHostRef.current?.dispose();+ voiceHostRef.current = null;iframeRef.current = iframe;if (!iframe) return;startListening();+ voiceHostRef.current = createVoiceHost(iframe);frameShortcutCleanupRef.current = bindFrameChord(iframe,(event, activeInFrame) => {return (!event.defaultPrevented&& !event.repeat- && routeSurfaceActive+ && routeSurfaceActiveRef.current&& stateRef.current?.available === true&& stateRef.current.enabled !== true&& actionShortcutMatches(event, shortcutRef.current)@@ -216,18 +276,28 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {},[enableFromShortcut,- routeSurfaceActive,+ createVoiceHost,+ routeSurfaceActiveRef,shortcutRef,startListening,stateRef,],);- useEffect(() => () => frameShortcutCleanupRef.current(), []);+ useEffect(() => () => {+ frameShortcutCleanupRef.current();+ voiceHostRef.current?.dispose();+ }, []);// On (re)load the overlay broadcasts its state on mount, but the parent// listener is already attached, so we also query as a backstop (§3).- const handleIframeLoad = useCallback(() => post({ type: 'avibe:annotation:query' }), [post]);+ const handleIframeLoad = useCallback(() => {+ const iframe = iframeRef.current;+ voiceHostRef.current?.dispose();+ voiceHostRef.current = iframe ? createVoiceHost(iframe) : null;+ setState(null);+ post({ type: 'avibe:annotation:query' });+ }, [createVoiceHost, post]);return {state,diff --git a/ui/src/lib/showPageVoiceBridge.test.ts b/ui/src/lib/showPageVoiceBridge.test.tsnew file mode 100644index 000000000..83d9243de--- /dev/null+++ b/ui/src/lib/showPageVoiceBridge.test.ts@@ -0,0 +1,251 @@+import { describe, expect, it, vi } from 'vitest';++import {+ ANNOTATION_VOICE_EVENT_MESSAGE,+ ANNOTATION_VOICE_REQUEST_MESSAGE,+ ShowPageVoiceHost,+ showPageVoiceRequestFromPayload,+ type ShowPageVoiceEvent,+ type ShowPageVoiceSession,+} from './showPageVoiceBridge';+import { claimVoiceCapture } from './voiceRecording';++type Deferred<T> = {+ promise: Promise<T>;+ resolve: (value: T) => void;+ reject: (error: unknown) => void;+};++const deferred = <T>(): Deferred<T> => {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((nextResolve, nextReject) => {+ resolve = nextResolve;+ reject = nextReject;+ });+ return { promise, resolve, reject };+};++class FakeVoiceSession implements ShowPageVoiceSession {+ readonly result = deferred<string>();+ readonly retryResult = deferred<string>();+ readonly done = this.result.promise;+ readonly start = vi.fn(async () => undefined);+ readonly finish = vi.fn();+ readonly canRetry = vi.fn(() => true);+ readonly retry = vi.fn((_context: { before: string; after: string }) => this.retryResult.promise);+ readonly abort = vi.fn();+}++describe('Show Page voice request boundary', () => {+ it('accepts the protocol and rejects oversized context or identifiers', () => {+ expect(showPageVoiceRequestFromPayload({+ type: ANNOTATION_VOICE_REQUEST_MESSAGE,+ action: 'start',+ requestId: 'voice-1',+ before: 'before',+ after: 'after',+ })).toMatchObject({ action: 'start', requestId: 'voice-1' });+ expect(showPageVoiceRequestFromPayload({+ type: ANNOTATION_VOICE_REQUEST_MESSAGE,+ action: 'start',+ requestId: 'voice-1',+ before: 'x'.repeat(501),+ after: '',+ })).toBeUndefined();+ expect(showPageVoiceRequestFromPayload({+ type: ANNOTATION_VOICE_REQUEST_MESSAGE,+ action: 'query',+ requestId: 'x'.repeat(129),+ })).toBeUndefined();+ });+});++describe('ShowPageVoiceHost', () => {+ it('reports availability without starting a microphone session', async () => {+ const events: ShowPageVoiceEvent[] = [];+ const createSession = vi.fn();+ const host = new ShowPageVoiceHost({+ post: (event) => events.push(event),+ availability: async () => ({ available: true, maxFileBytes: null }),+ createSession,+ });++ host.handle({+ type: ANNOTATION_VOICE_REQUEST_MESSAGE,+ action: 'query',+ requestId: 'probe-1',+ });+ await vi.waitFor(() => expect(events).toContainEqual({+ type: ANNOTATION_VOICE_EVENT_MESSAGE,+ kind: 'availability',+ requestId: 'probe-1',+ available: true,+ }));+ expect(createSession).not.toHaveBeenCalled();+ });++ it('owns start, preview, stop, and result for one iframe session', async () => {+ const events: ShowPageVoiceEvent[] = [];+ const session = new FakeVoiceSession();+ let preview: ((text: string) => void) | undefined;+ const host = new ShowPageVoiceHost({+ post: (event) => events.push(event),+ availability: async () => ({ available: true, maxFileBytes: 1_000_000 }),+ createSession: (input) => {+ preview = input.onPreview;+ expect(input.captureClaim?.isCurrent()).toBe(true);+ expect(input).toMatchObject({+ before: 'before',+ after: 'after',+ maxFileBytes: 1_000_000,+ });+ return session;+ },+ });+ const request = {+ type: ANNOTATION_VOICE_REQUEST_MESSAGE,+ action: 'start',+ requestId: 'voice-1',+ before: 'before',+ after: 'after',+ } as const;++ host.handle(request);+ await vi.waitFor(() => expect(events).toContainEqual({+ type: ANNOTATION_VOICE_EVENT_MESSAGE,+ kind: 'started',+ requestId: 'voice-1',+ }));+ preview?.('live words');+ expect(events.at(-1)).toEqual({+ type: ANNOTATION_VOICE_EVENT_MESSAGE,+ kind: 'preview',+ requestId: 'voice-1',+ text: 'live words',+ });++ host.handle({ ...request, action: 'stop' });+ expect(session.finish).toHaveBeenCalledOnce();+ session.result.resolve('final words');+ await vi.waitFor(() => expect(events.at(-1)).toEqual({+ type: ANNOTATION_VOICE_EVENT_MESSAGE,+ kind: 'result',+ requestId: 'voice-1',+ text: 'final words',+ }));+ });++ it('cancels microphone startup while availability is still pending', async () => {+ const events: ShowPageVoiceEvent[] = [];+ const availability = deferred<{ available: boolean; maxFileBytes: null }>();+ const createSession = vi.fn(() => new FakeVoiceSession());+ const host = new ShowPageVoiceHost({+ post: (event) => events.push(event),+ availability: () => availability.promise,+ createSession,+ });+ const start = {+ type: ANNOTATION_VOICE_REQUEST_MESSAGE,+ action: 'start',+ requestId: 'voice-1',+ before: '',+ after: '',+ } as const;++ host.handle(start);+ host.handle({ ...start, requestId: 'voice-2' });+ expect(events.at(-1)).toMatchObject({+ kind: 'error',+ requestId: 'voice-2',+ code: 'failed',+ retryable: false,+ });++ host.handle({ ...start, action: 'abort' });+ availability.reject(new Error('late availability failure'));+ await expect(availability.promise).rejects.toThrow('late availability failure');+ await Promise.resolve();++ expect(createSession).not.toHaveBeenCalled();+ expect(events.filter((event) => event.requestId === 'voice-1')).toEqual([]);+ });++ it('takes microphone ownership before awaiting availability', async () => {+ const availability = deferred<{ available: boolean; maxFileBytes: null }>();+ const previousFinish = vi.fn();+ const previousClaim = claimVoiceCapture(previousFinish);+ const createSession = vi.fn(() => new FakeVoiceSession());+ const host = new ShowPageVoiceHost({+ post: () => undefined,+ availability: () => availability.promise,+ createSession,+ });+ const start = {+ type: ANNOTATION_VOICE_REQUEST_MESSAGE,+ action: 'start',+ requestId: 'voice-1',+ before: '',+ after: '',+ } as const;++ host.handle(start);++ expect(previousFinish).toHaveBeenCalledOnce();+ expect(createSession).not.toHaveBeenCalled();+ host.handle({ ...start, action: 'abort' });+ availability.resolve({ available: true, maxFileBytes: null });+ await availability.promise;+ await Promise.resolve();+ expect(createSession).not.toHaveBeenCalled();+ previousClaim.release();+ });++ it('retains a failed transcription for retry and aborts on disposal', async () => {+ const events: ShowPageVoiceEvent[] = [];+ const session = new FakeVoiceSession();+ const host = new ShowPageVoiceHost({+ post: (event) => events.push(event),+ availability: async () => ({ available: true, maxFileBytes: null }),+ createSession: () => session,+ });+ const start = {+ type: ANNOTATION_VOICE_REQUEST_MESSAGE,+ action: 'start',+ requestId: 'voice-1',+ before: '',+ after: '',+ } as const;+ host.handle(start);+ await vi.waitFor(() => expect(session.start).toHaveBeenCalledOnce());+ session.result.reject(new Error('network'));+ await vi.waitFor(() => expect(events.at(-1)).toMatchObject({+ kind: 'error',+ requestId: 'voice-1',+ code: 'failed',+ retryable: true,+ }));++ host.handle({ ...start, action: 'retry', before: 'latest before', after: 'latest after' });+ expect(session.retry).toHaveBeenCalledWith({+ before: 'latest before',+ after: 'latest after',+ });+ session.retryResult.resolve('recovered');+ await vi.waitFor(() => expect(events.at(-1)).toMatchObject({+ kind: 'result',+ text: 'recovered',+ }));++ const replacement = new FakeVoiceSession();+ const nextHost = new ShowPageVoiceHost({+ post: () => undefined,+ availability: async () => ({ available: true, maxFileBytes: null }),+ createSession: () => replacement,+ });+ nextHost.handle({ ...start, requestId: 'voice-2' });+ await vi.waitFor(() => expect(replacement.start).toHaveBeenCalledOnce());+ nextHost.dispose();+ expect(replacement.abort).toHaveBeenCalledOnce();+ });+});diff --git a/ui/src/lib/showPageVoiceBridge.ts b/ui/src/lib/showPageVoiceBridge.tsnew file mode 100644index 000000000..d7a5a83cd--- /dev/null+++ b/ui/src/lib/showPageVoiceBridge.ts@@ -0,0 +1,359 @@+import {+ ShowPageVoiceDictation,+ type ShowPageVoiceDictationInput,+} from './showPageVoiceDictation';+import {+ VoiceTranscriptionError,+ type VoiceTranscriptionErrorCode,+} from './voiceTranscription';+import {+ claimVoiceCapture,+ type VoiceCaptureClaim,+} from './voiceRecording';++export const ANNOTATION_VOICE_REQUEST_MESSAGE = 'avibe:annotation:voice:request';+export const ANNOTATION_VOICE_EVENT_MESSAGE = 'avibe:annotation:voice:event';+const MAX_REQUEST_ID_CHARS = 128;+const MAX_CONTEXT_BEFORE_CHARS = 500;+const MAX_CONTEXT_AFTER_CHARS = 200;++export type ShowPageVoiceErrorCode = VoiceTranscriptionErrorCode | 'permission' | 'start_failed';++export type ShowPageVoiceRequest =+ | { type: typeof ANNOTATION_VOICE_REQUEST_MESSAGE; action: 'query'; requestId: string }+ | {+ type: typeof ANNOTATION_VOICE_REQUEST_MESSAGE;+ action: 'start';+ requestId: string;+ before: string;+ after: string;+ }+ | {+ type: typeof ANNOTATION_VOICE_REQUEST_MESSAGE;+ action: 'stop' | 'abort';+ requestId: string;+ }+ | {+ type: typeof ANNOTATION_VOICE_REQUEST_MESSAGE;+ action: 'retry';+ requestId: string;+ before: string;+ after: string;+ };++export type ShowPageVoiceEvent =+ | {+ type: typeof ANNOTATION_VOICE_EVENT_MESSAGE;+ kind: 'availability';+ requestId: string;+ available: boolean;+ }+ | {+ type: typeof ANNOTATION_VOICE_EVENT_MESSAGE;+ kind: 'started' | 'preview' | 'result';+ requestId: string;+ text?: string;+ }+ | {+ type: typeof ANNOTATION_VOICE_EVENT_MESSAGE;+ kind: 'error';+ requestId: string;+ code: ShowPageVoiceErrorCode;+ retryable: boolean;+ };++export type ShowPageVoiceAvailability = {+ available: boolean;+ maxFileBytes: number | null;+};++export type ShowPageVoiceSession = {+ readonly done: Promise<string>;+ start(): Promise<void>;+ finish(): void;+ canRetry(): boolean;+ retry(context: { before: string; after: string }): Promise<string>;+ abort(): void;+};++export type ShowPageVoiceHostDependencies = {+ post: (event: ShowPageVoiceEvent) => void;+ availability: () => Promise<ShowPageVoiceAvailability>;+ createSession?: (input: ShowPageVoiceDictationInput) => ShowPageVoiceSession;+};++type StartingVoiceSession = {+ requestId: string;+ cancelled: boolean;+ captureClaim: VoiceCaptureClaim;+ session: ShowPageVoiceSession | null;+};++type ActiveVoiceSession = {+ requestId: string;+ captureClaim: VoiceCaptureClaim;+ session: ShowPageVoiceSession;+};++const boundedString = (value: unknown, maxChars: number): string | undefined => (+ typeof value === 'string' && value.length <= maxChars ? value : undefined+);++export function showPageVoiceRequestFromPayload(value: unknown): ShowPageVoiceRequest | undefined {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;+ const payload = value as Record<string, unknown>;+ if (payload.type !== ANNOTATION_VOICE_REQUEST_MESSAGE) return undefined;+ const requestId = boundedString(payload.requestId, MAX_REQUEST_ID_CHARS);+ if (!requestId) return undefined;+ if (payload.action === 'query') {+ return { type: ANNOTATION_VOICE_REQUEST_MESSAGE, action: 'query', requestId };+ }+ if (payload.action === 'start') {+ const before = boundedString(payload.before, MAX_CONTEXT_BEFORE_CHARS);+ const after = boundedString(payload.after, MAX_CONTEXT_AFTER_CHARS);+ if (before === undefined || after === undefined) return undefined;+ return {+ type: ANNOTATION_VOICE_REQUEST_MESSAGE,+ action: 'start',+ requestId,+ before,+ after,+ };+ }+ if (payload.action === 'retry') {+ const before = boundedString(payload.before, MAX_CONTEXT_BEFORE_CHARS);+ const after = boundedString(payload.after, MAX_CONTEXT_AFTER_CHARS);+ if (before === undefined || after === undefined) return undefined;+ return {+ type: ANNOTATION_VOICE_REQUEST_MESSAGE,+ action: 'retry',+ requestId,+ before,+ after,+ };+ }+ if (payload.action === 'stop' || payload.action === 'abort') {+ return { type: ANNOTATION_VOICE_REQUEST_MESSAGE, action: payload.action, requestId };+ }+ return undefined;+}++const voiceErrorCode = (error: unknown, starting = false): ShowPageVoiceErrorCode => {+ if (error instanceof VoiceTranscriptionError) return error.code;+ const name = error && typeof error === 'object'+ ? (error as { name?: unknown }).name+ : undefined;+ if (name === 'NotAllowedError' || name === 'SecurityError') return 'permission';+ return starting ? 'start_failed' : 'failed';+};++/** One voice owner for one mounted Show Page iframe. */+export class ShowPageVoiceHost {+ private readonly dependencies: Required<ShowPageVoiceHostDependencies>;+ private active: ActiveVoiceSession | null = null;+ private starting: StartingVoiceSession | null = null;+ private disposed = false;++ constructor(dependencies: ShowPageVoiceHostDependencies) {+ this.dependencies = {+ ...dependencies,+ createSession: dependencies.createSession+ ?? ((input) => new ShowPageVoiceDictation(input)),+ };+ }++ handle(value: unknown): void {+ const request = showPageVoiceRequestFromPayload(value);+ if (!request || this.disposed) return;+ if (request.action === 'query') {+ void this.replyAvailability(request.requestId);+ } else if (request.action === 'start') {+ void this.start(request);+ } else if (request.action === 'stop') {+ if (this.active?.requestId === request.requestId) this.active.session.finish();+ } else if (request.action === 'retry') {+ if (this.active?.requestId === request.requestId) void this.retry(this.active, request);+ } else {+ if (this.starting?.requestId === request.requestId) {+ this.starting.cancelled = true;+ this.starting.captureClaim.release();+ this.starting = null;+ }+ if (this.active?.requestId === request.requestId) {+ this.active.session.abort();+ this.active.captureClaim.release();+ this.active = null;+ }+ }+ }++ dispose(): void {+ this.disposed = true;+ if (this.starting) {+ this.starting.cancelled = true;+ this.starting.captureClaim.release();+ }+ this.starting = null;+ this.active?.session.abort();+ this.active?.captureClaim.release();+ this.active = null;+ }++ private async replyAvailability(requestId: string): Promise<void> {+ try {+ const availability = await this.dependencies.availability();+ if (!this.disposed) {+ this.dependencies.post({+ type: ANNOTATION_VOICE_EVENT_MESSAGE,+ kind: 'availability',+ requestId,+ available: availability.available,+ });+ }+ } catch {+ if (!this.disposed) {+ this.dependencies.post({+ type: ANNOTATION_VOICE_EVENT_MESSAGE,+ kind: 'availability',+ requestId,+ available: false,+ });+ }+ }+ }++ private async start(request: Extract<ShowPageVoiceRequest, { action: 'start' }>): Promise<void> {+ if (this.active || this.starting) {+ this.postError(request.requestId, 'failed', false);+ return;+ }+ const captureClaim = claimVoiceCapture(() => this.finishCapture(request.requestId));+ const pending: StartingVoiceSession = {+ requestId: request.requestId,+ cancelled: false,+ captureClaim,+ session: null,+ };+ this.starting = pending;+ try {+ const availability = await this.dependencies.availability();+ if (this.disposed || pending.cancelled || this.starting !== pending) return;+ if (!availability.available) {+ this.postError(request.requestId, 'unavailable', false);+ return;+ }+ const session = this.dependencies.createSession({+ before: request.before,+ after: request.after,+ captureClaim,+ maxFileBytes: availability.maxFileBytes,+ onPreview: (text) => {+ if (this.active?.requestId !== request.requestId || this.disposed) return;+ this.dependencies.post({+ type: ANNOTATION_VOICE_EVENT_MESSAGE,+ kind: 'preview',+ requestId: request.requestId,+ text,+ });+ },+ });+ pending.session = session;+ const active = { requestId: request.requestId, captureClaim, session };+ this.starting = null;+ this.active = active;+ try {+ await session.start();+ } catch (error) {+ const stillActive = this.active === active;+ if (stillActive) this.active = null;+ captureClaim.release();+ if (stillActive) {+ this.postError(request.requestId, voiceErrorCode(error, true), false);+ }+ return;+ }+ if (this.disposed || this.active !== active) {+ session.abort();+ captureClaim.release();+ return;+ }+ this.dependencies.post({+ type: ANNOTATION_VOICE_EVENT_MESSAGE,+ kind: 'started',+ requestId: request.requestId,+ });+ void session.done.then(+ (text) => this.postResult(active, text),+ (error) => this.postSessionError(active, error),+ );+ } catch (error) {+ if (!pending.cancelled) {+ this.postError(request.requestId, voiceErrorCode(error, true), false);+ }+ } finally {+ if (this.starting === pending) this.starting = null;+ if (!pending.session) captureClaim.release();+ }+ }++ private finishCapture(requestId: string): void {+ if (this.active?.requestId === requestId) {+ this.active.session.finish();+ return;+ }+ if (this.starting?.requestId !== requestId) return;+ this.starting.cancelled = true;+ this.starting = null;+ this.postError(requestId, 'cancelled', false);+ }++ private async retry(+ active: ActiveVoiceSession,+ request: Extract<ShowPageVoiceRequest, { action: 'retry' }>,+ ): Promise<void> {+ try {+ const text = await active.session.retry({ before: request.before, after: request.after });+ this.postResult(active, text);+ } catch (error) {+ this.postSessionError(active, error);+ }+ }++ private postResult(+ active: ActiveVoiceSession,+ text: string,+ ): void {+ if (this.disposed || this.active !== active) return;+ active.captureClaim.release();+ this.active = null;+ this.dependencies.post({+ type: ANNOTATION_VOICE_EVENT_MESSAGE,+ kind: 'result',+ requestId: active.requestId,+ text,+ });+ }++ private postSessionError(+ active: ActiveVoiceSession,+ error: unknown,+ ): void {+ if (this.disposed || this.active !== active) return;+ active.captureClaim.release();+ const code = voiceErrorCode(error);+ const retryable = code !== 'cancelled' && code !== 'empty' && active.session.canRetry();+ if (!retryable) this.active = null;+ this.postError(active.requestId, code, retryable);+ }++ private postError(requestId: string, code: ShowPageVoiceErrorCode, retryable: boolean): void {+ if (this.disposed) return;+ this.dependencies.post({+ type: ANNOTATION_VOICE_EVENT_MESSAGE,+ kind: 'error',+ requestId,+ code,+ retryable,+ });+ }+}diff --git a/ui/src/lib/showPageVoiceDictation.test.ts b/ui/src/lib/showPageVoiceDictation.test.tsnew file mode 100644index 000000000..4c2a3d863--- /dev/null+++ b/ui/src/lib/showPageVoiceDictation.test.ts@@ -0,0 +1,263 @@+import { describe, expect, it, vi } from 'vitest';++import { ShowPageVoiceDictation } from './showPageVoiceDictation';+import { claimVoiceCapture, type VoiceRecordingPipelineOptions } from './voiceRecording';+import type { VoiceRealtimeOptions } from './voiceRealtime';+import { VoiceTranscriptionError, type VoiceTranscriptionSegment } from './voiceTranscription';++type Deferred<T> = {+ promise: Promise<T>;+ resolve: (value: T) => void;+};++const deferred = <T>(): Deferred<T> => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((nextResolve) => {+ resolve = nextResolve;+ });+ return { promise, resolve };+};++const fakeStream = () => {+ const stop = vi.fn();+ return {+ stream: { getTracks: () => [{ stop }] } as unknown as MediaStream,+ stop,+ };+};++describe('ShowPageVoiceDictation', () => {+ it('uses the existing realtime pipeline without an aggregate recording limit', async () => {+ const { stream } = fakeStream();+ let pipelineOptions: VoiceRecordingPipelineOptions | null = null;+ let realtimeOptions: VoiceRealtimeOptions | null = null;+ const realtimeFinish = vi.fn(async () => ({+ text: 'final realtime words',+ cleanup: 'success' as const,+ }));+ const dictation = new ShowPageVoiceDictation({+ before: 'before',+ after: 'after',+ maxFileBytes: null,+ }, {+ getUserMedia: async () => stream,+ createRealtime: (options) => {+ realtimeOptions = options;+ return {+ start: async () => undefined,+ sendPcm: vi.fn(() => true),+ finish: realtimeFinish,+ abort: vi.fn(),+ };+ },+ createPipeline: (options) => {+ pipelineOptions = options;+ return {+ start: async () => true,+ abort: vi.fn(),+ finish: () => {+ options.onSegment(new Blob(['tail'], { type: 'audio/wav' }), {+ durationMs: 12_000,+ final: true,+ });+ options.onStopped('finish', { pendingSegmentCount: 1 });+ },+ };+ },+ createQueue: () => ({ enqueue: async () => undefined }),+ newDictationId: () => 'dictation-1',+ });++ await dictation.start();+ expect(pipelineOptions).toMatchObject({ segmentMs: 60_000, maxFileBytes: null });+ expect(realtimeOptions).toMatchObject({ before: 'before', after: 'after' });++ // Internal minute-sized segments may repeat indefinitely; none finishes the+ // user recording. Only the explicit finish below is terminal.+ pipelineOptions!.onSegment(new Blob(['minute-1'], { type: 'audio/wav' }), {+ durationMs: 60_000,+ });+ pipelineOptions!.onSegment(new Blob(['minute-2'], { type: 'audio/wav' }), {+ durationMs: 60_000,+ overlapMs: 500,+ });+ let settled = false;+ void dictation.done.finally(() => { settled = true; });+ await Promise.resolve();+ expect(settled).toBe(false);++ dictation.finish();+ await expect(dictation.done).resolves.toBe('final realtime words');+ expect(realtimeFinish).toHaveBeenCalledOnce();+ });++ it('finishes capture when another client surface takes microphone ownership', async () => {+ const { stream } = fakeStream();+ const finish = vi.fn();+ const abort = vi.fn();+ const dictation = new ShowPageVoiceDictation({ before: '', after: '' }, {+ getUserMedia: async () => stream,+ createRealtime: () => ({+ start: async () => undefined,+ sendPcm: vi.fn(() => true),+ finish: async () => ({ text: 'done', cleanup: 'success' as const }),+ abort: vi.fn(),+ }),+ createPipeline: () => ({ start: async () => true, finish, abort }),+ createQueue: () => ({ enqueue: async () => undefined }),+ });++ await dictation.start();+ const nextSurface = claimVoiceCapture(vi.fn());++ expect(finish).toHaveBeenCalledOnce();+ nextSurface.release();+ dictation.abort();+ expect(abort).toHaveBeenCalledOnce();+ });++ it('preserves finalization when ownership changes during capture startup', async () => {+ const { stream } = fakeStream();+ const captureStarted = deferred<boolean>();+ const pipelineReady = deferred<void>();+ const realtimeAbort = vi.fn();+ const pipelineFinish = vi.fn();+ const dictation = new ShowPageVoiceDictation({ before: '', after: '' }, {+ getUserMedia: async () => stream,+ createRealtime: () => ({+ start: async () => undefined,+ sendPcm: vi.fn(() => true),+ finish: async () => ({ text: 'buffered words', cleanup: 'success' as const }),+ abort: realtimeAbort,+ }),+ createPipeline: (options) => {+ pipelineReady.resolve(undefined);+ return {+ start: () => captureStarted.promise,+ abort: vi.fn(),+ finish: () => {+ pipelineFinish();+ options.onSegment(new Blob(['tail'], { type: 'audio/wav' }), {+ durationMs: 2_000,+ final: true,+ });+ options.onStopped('finish', { pendingSegmentCount: 1 });+ },+ };+ },+ createQueue: () => ({ enqueue: async () => undefined }),+ });++ const starting = dictation.start();+ await pipelineReady.promise;+ const nextSurface = claimVoiceCapture(vi.fn());+ expect(pipelineFinish).toHaveBeenCalledOnce();++ captureStarted.resolve(false);+ await expect(starting).resolves.toBeUndefined();+ await expect(dictation.done).resolves.toBe('buffered words');+ expect(realtimeAbort).not.toHaveBeenCalled();+ nextSurface.release();+ });++ it('falls back through the existing segment queue and finalizer', async () => {+ const { stream } = fakeStream();+ const queued: number[] = [];+ const finalize = vi.fn(async (segments: VoiceTranscriptionSegment[]) => {+ expect(segments.map(({ sequence, final, receipt }) => ({ sequence, final, receipt }))).toEqual([+ { sequence: 0, final: false, receipt: 'receipt-0' },+ { sequence: 1, final: true, receipt: undefined },+ ]);+ return { text: 'HTTP fallback words', cleanup: 'success' as const };+ });+ const dictation = new ShowPageVoiceDictation({ before: '', after: '' }, {+ getUserMedia: async () => stream,+ createRealtime: (options) => ({+ start: async () => {+ options.onError?.(new Error('realtime unavailable'));+ throw new Error('realtime unavailable');+ },+ sendPcm: vi.fn(() => false),+ finish: async () => { throw new Error('realtime unavailable'); },+ abort: vi.fn(),+ }),+ createQueue: () => ({+ enqueue: async (segment) => {+ queued.push(segment.sequence);+ segment.receipt = `receipt-${segment.sequence}`;+ },+ }),+ createPipeline: (options) => ({+ start: async () => true,+ abort: vi.fn(),+ finish: () => {+ options.onSegment(new Blob(['segment'], { type: 'audio/wav' }), {+ durationMs: 60_000,+ });+ options.onSegment(new Blob(['tail'], { type: 'audio/wav' }), {+ durationMs: 4_000,+ final: true,+ });+ options.onStopped('finish', { pendingSegmentCount: 2 });+ },+ }),+ finalize,+ newDictationId: () => 'dictation-2',+ });++ await dictation.start();+ dictation.finish();+ await expect(dictation.done).resolves.toBe('HTTP fallback words');+ expect(queued).toEqual([0]);+ expect(finalize).toHaveBeenCalledOnce();+ });++ it('uses the latest draft context when retrying retained audio', async () => {+ const { stream } = fakeStream();+ const finalize = vi.fn()+ .mockRejectedValueOnce(new VoiceTranscriptionError('timeout'))+ .mockResolvedValueOnce({ text: 'recovered', cleanup: 'success' as const });+ const dictation = new ShowPageVoiceDictation({+ before: 'original before',+ after: 'original after',+ }, {+ getUserMedia: async () => stream,+ createRealtime: (options) => ({+ start: async () => {+ options.onError?.(new Error('realtime unavailable'));+ throw new Error('realtime unavailable');+ },+ sendPcm: vi.fn(() => false),+ finish: async () => { throw new Error('realtime unavailable'); },+ abort: vi.fn(),+ }),+ createQueue: () => ({ enqueue: async () => undefined }),+ createPipeline: (options) => ({+ start: async () => true,+ abort: vi.fn(),+ finish: () => {+ options.onSegment(new Blob(['tail'], { type: 'audio/wav' }), {+ durationMs: 4_000,+ final: true,+ });+ options.onStopped('finish', { pendingSegmentCount: 1 });+ },+ }),+ finalize,+ transcribeSegments: async () => undefined,+ });++ await dictation.start();+ dictation.finish();+ await expect(dictation.done).rejects.toMatchObject({ code: 'timeout' });+ await expect(dictation.retry({+ before: 'latest before',+ after: 'latest after',+ })).resolves.toBe('recovered');++ expect(finalize.mock.calls.map(([, context]) => context)).toEqual([+ expect.objectContaining({ before: 'original before', after: 'original after' }),+ expect.objectContaining({ before: 'latest before', after: 'latest after' }),+ ]);+ });+});diff --git a/ui/src/lib/showPageVoiceDictation.ts b/ui/src/lib/showPageVoiceDictation.tsnew file mode 100644index 000000000..eaf080753--- /dev/null+++ b/ui/src/lib/showPageVoiceDictation.ts@@ -0,0 +1,326 @@+import {+ finalizeVoiceDictation,+ transcribeVoiceSegments,+ VOICE_SEGMENT_MS,+ VOICE_TRANSCRIPTION_CONCURRENCY,+ VoiceTranscriptionError,+ VoiceTranscriptionQueue,+ type VoiceTranscriptionSegment,+} from './voiceTranscription';+import {+ claimVoiceCapture,+ VoiceRecordingPipeline,+ type VoiceCaptureClaim,+ type VoiceRecordingPipelineOptions,+} from './voiceRecording';+import {+ VoiceRealtimeSession,+ type VoiceRealtimeOptions,+} from './voiceRealtime';++type PendingVoiceSegment = VoiceTranscriptionSegment & {+ task: Promise<void>;+ transcriptionStarted?: boolean;+};++type VoicePipeline = Pick<VoiceRecordingPipeline, 'abort' | 'finish' | 'start'>;+type VoiceRealtime = Pick<VoiceRealtimeSession, 'abort' | 'finish' | 'sendPcm' | 'start'>;+type VoiceQueue = Pick<VoiceTranscriptionQueue, 'enqueue'>;++export type ShowPageVoiceDictationInput = {+ before: string;+ after: string;+ captureClaim?: VoiceCaptureClaim;+ maxFileBytes?: number | null;+ onPreview?: (text: string) => void;+};++export type ShowPageVoiceDictationDependencies = {+ getUserMedia?: () => Promise<MediaStream>;+ createPipeline?: (options: VoiceRecordingPipelineOptions) => VoicePipeline;+ createRealtime?: (options: VoiceRealtimeOptions) => VoiceRealtime;+ createQueue?: (options: {+ concurrency: number;+ signal: AbortSignal;+ dictationId: string;+ }) => VoiceQueue;+ finalize?: typeof finalizeVoiceDictation;+ transcribeSegments?: typeof transcribeVoiceSegments;+ newDictationId?: () => string;+};++const newDictationId = (): string => (+ globalThis.crypto?.randomUUID?.()+ ?? `show-voice-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`+);++const cancelledError = (): VoiceTranscriptionError => new VoiceTranscriptionError('cancelled');++/**+ * One Show Page dictation backed by the exact recording, realtime, segmentation,+ * and HTTP fallback primitives used by Chat. Segment duration is internal; the+ * user-facing recording has no duration or aggregate-size limit.+ */+export class ShowPageVoiceDictation {+ private readonly input: ShowPageVoiceDictationInput;+ private readonly dependencies: Required<ShowPageVoiceDictationDependencies>;+ private readonly abortController = new AbortController();+ private readonly dictationId: string;+ private readonly segments: PendingVoiceSegment[] = [];+ private readonly queue: VoiceQueue;+ private cleanupContext: { before: string; after: string };+ private captureClaim: VoiceCaptureClaim | null = null;+ private pipeline: VoicePipeline | null = null;+ private realtime: VoiceRealtime | null = null;+ private realtimeState: 'connecting' | 'active' | 'failed' = 'connecting';+ private stream: MediaStream | null = null;+ private captureError: unknown;+ private stopped = false;+ private settled = false;+ private resolveDone!: (text: string) => void;+ private rejectDone!: (error: unknown) => void;+ readonly done: Promise<string>;++ constructor(+ input: ShowPageVoiceDictationInput,+ dependencies: ShowPageVoiceDictationDependencies = {},+ ) {+ this.input = input;+ this.cleanupContext = { before: input.before, after: input.after };+ this.dependencies = {+ getUserMedia: dependencies.getUserMedia+ ?? (() => navigator.mediaDevices.getUserMedia({ audio: true })),+ createPipeline: dependencies.createPipeline+ ?? ((options) => new VoiceRecordingPipeline(options)),+ createRealtime: dependencies.createRealtime+ ?? ((options) => new VoiceRealtimeSession(options)),+ createQueue: dependencies.createQueue+ ?? ((options) => new VoiceTranscriptionQueue(options)),+ finalize: dependencies.finalize ?? finalizeVoiceDictation,+ transcribeSegments: dependencies.transcribeSegments ?? transcribeVoiceSegments,+ newDictationId: dependencies.newDictationId ?? newDictationId,+ };+ this.dictationId = this.dependencies.newDictationId();+ this.queue = this.dependencies.createQueue({+ concurrency: VOICE_TRANSCRIPTION_CONCURRENCY,+ signal: this.abortController.signal,+ dictationId: this.dictationId,+ });+ this.done = new Promise<string>((resolve, reject) => {+ this.resolveDone = resolve;+ this.rejectDone = reject;+ });+ void this.done.catch(() => undefined);+ }++ async start(): Promise<void> {+ if (this.pipeline || this.stream) throw new Error('show page voice dictation already started');+ const captureClaim = this.input.captureClaim ?? claimVoiceCapture(() => {+ try {+ if (this.pipeline) this.pipeline.finish();+ else this.abortController.abort();+ } catch {+ this.abortController.abort();+ this.pipeline?.abort();+ this.stream?.getTracks().forEach((track) => track.stop());+ }+ });+ this.captureClaim = captureClaim;+ try {+ const stream = await this.dependencies.getUserMedia();+ if (this.abortController.signal.aborted || !captureClaim.isCurrent()) {+ stream.getTracks().forEach((track) => track.stop());+ throw cancelledError();+ }+ this.stream = stream;+ const realtime = this.dependencies.createRealtime({+ before: this.input.before,+ after: this.input.after,+ signal: this.abortController.signal,+ onPreview: (preview) => this.input.onPreview?.(`${preview.text}${preview.stash}`.trim()),+ onError: () => {+ if (this.abortController.signal.aborted) return;+ this.realtimeState = 'failed';+ this.activateHttpFallback();+ },+ });+ this.realtime = realtime;+ void realtime.start().then(() => {+ if (!this.abortController.signal.aborted) this.realtimeState = 'active';+ }).catch(() => {+ if (this.abortController.signal.aborted) return;+ this.realtimeState = 'failed';+ this.activateHttpFallback();+ });++ const pipeline = this.dependencies.createPipeline({+ stream,+ segmentMs: VOICE_SEGMENT_MS,+ maxFileBytes: this.input.maxFileBytes,+ onSegment: (blob, metadata) => this.queueSegment(+ blob,+ metadata.durationMs,+ metadata.overlapMs,+ metadata.final,+ ),+ onPcm: (samples) => {+ if (this.realtimeState !== 'failed') realtime.sendPcm(samples);+ },+ onError: (error) => {+ this.captureError = error;+ this.realtimeState = 'failed';+ realtime.abort();+ this.activateHttpFallback();+ },+ onStopped: (reason) => {+ this.stopped = true;+ this.releaseCaptureClaim();+ if (reason === 'abort') {+ this.reject(cancelledError());+ return;+ }+ void this.finalize().then(+ (text) => this.resolve(text),+ (error) => this.reject(error),+ );+ },+ });+ this.pipeline = pipeline;+ const active = await pipeline.start();+ if (!active) return;+ if (!captureClaim.isCurrent()) {+ pipeline.finish();+ }+ } catch (error) {+ this.abortController.abort();+ this.realtime?.abort();+ this.stream?.getTracks().forEach((track) => track.stop());+ this.stream = null;+ this.releaseCaptureClaim();+ throw error;+ }+ }++ finish(): void {+ this.pipeline?.finish();+ }++ abort(): void {+ if (this.abortController.signal.aborted) return;+ this.abortController.abort();+ this.realtime?.abort();+ this.pipeline?.abort();+ this.stream?.getTracks().forEach((track) => track.stop());+ this.releaseCaptureClaim();+ this.reject(cancelledError());+ }++ canRetry(): boolean {+ return this.stopped+ && this.captureError === undefined+ && !this.abortController.signal.aborted;+ }++ async retry(context: { before: string; after: string }): Promise<string> {+ if (!this.canRetry()) {+ throw this.captureError ?? cancelledError();+ }+ this.cleanupContext = context;+ await this.dependencies.transcribeSegments(this.segments, {+ concurrency: VOICE_TRANSCRIPTION_CONCURRENCY,+ signal: this.abortController.signal,+ dictationId: this.dictationId,+ });+ return this.finalizeHttp();+ }++ private queueSegment(+ blob: Blob,+ durationMs: number,+ overlapMs?: number,+ final = false,+ ): void {+ const segment: PendingVoiceSegment = {+ blob,+ sequence: this.segments.length,+ final,+ durationMs,+ overlapMs,+ task: Promise.resolve(),+ };+ this.segments.push(segment);+ if (this.realtimeState !== 'failed' || final) return;+ segment.transcriptionStarted = true;+ segment.task = this.queue.enqueue(segment);+ }++ private activateHttpFallback(): void {+ for (const segment of this.segments) {+ if (segment.final || segment.transcriptionStarted || !segment.blob) continue;+ segment.transcriptionStarted = true;+ segment.task = this.queue.enqueue(segment);+ }+ }++ private ensureFinalSegment(): void {+ if (this.segments.at(-1)?.final) return;+ this.segments.push({+ blob: null,+ sequence: this.segments.length,+ final: true,+ durationMs: 0,+ task: Promise.resolve(),+ });+ }++ private async finalize(): Promise<string> {+ if (!this.segments.length && this.captureError === undefined) {+ throw new VoiceTranscriptionError('empty');+ }+ this.ensureFinalSegment();+ if (this.realtime && this.realtimeState !== 'failed' && this.captureError === undefined) {+ try {+ const result = await this.realtime.finish();+ if (!result.text.trim()) throw new VoiceTranscriptionError('empty');+ return result.text;+ } catch {+ if (this.abortController.signal.aborted) throw cancelledError();+ this.realtimeState = 'failed';+ this.activateHttpFallback();+ }+ }+ return this.finalizeHttp();+ }++ private async finalizeHttp(): Promise<string> {+ this.activateHttpFallback();+ await Promise.all(this.segments.map((segment) => segment.task));+ if (this.abortController.signal.aborted) throw cancelledError();+ if (this.captureError !== undefined) throw this.captureError;+ const result = await this.dependencies.finalize(this.segments, {+ dictationId: this.dictationId,+ before: this.cleanupContext.before,+ after: this.cleanupContext.after,+ }, {+ signal: this.abortController.signal,+ });+ return result.text;+ }++ private resolve(text: string): void {+ if (this.settled) return;+ this.settled = true;+ this.resolveDone(text);+ }++ private reject(error: unknown): void {+ if (this.settled) return;+ this.settled = true;+ this.rejectDone(error);+ }++ private releaseCaptureClaim(): void {+ this.captureClaim?.release();+ this.captureClaim = null;+ }+}diff --git a/ui/src/lib/voiceRecording.test.ts b/ui/src/lib/voiceRecording.test.tsindex 2b1b1a1a5..e11cd2351 100644--- a/ui/src/lib/voiceRecording.test.ts+++ b/ui/src/lib/voiceRecording.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest';import {+ claimVoiceCapture,deleteMapValueIfCurrent,isVoiceControlDisabled,VOICE_CAPTURE_STOP_TIMEOUT_MS,@@ -648,6 +649,27 @@ describe('deleteMapValueIfCurrent', () => {});});+describe('voice capture ownership', () => {+ it('finishes the previous surface and ignores its stale release', () => {+ const finishChat = vi.fn();+ const finishShowPage = vi.fn();+ const chat = claimVoiceCapture(finishChat);+ const showPage = claimVoiceCapture(finishShowPage);++ expect(finishChat).toHaveBeenCalledOnce();+ expect(chat.isCurrent()).toBe(false);+ expect(showPage.isCurrent()).toBe(true);++ chat.release();+ expect(showPage.isCurrent()).toBe(true);++ showPage.release();+ const next = claimVoiceCapture(vi.fn());+ expect(finishShowPage).not.toHaveBeenCalled();+ next.release();+ });+});+describe('isVoiceControlDisabled', () => {it('requires explicit discard before a retained recording can be replaced', () => {expect(isVoiceControlDisabled(false, false, false, true)).toBe(true);diff --git a/ui/src/lib/voiceRecording.ts b/ui/src/lib/voiceRecording.tsindex c89b26abc..c9ec3ccce 100644--- a/ui/src/lib/voiceRecording.ts+++ b/ui/src/lib/voiceRecording.ts@@ -322,6 +322,43 @@ export const deleteMapValueIfCurrent = <Key, Value>(return map.delete(key);};+export type VoiceCaptureClaim = {+ isCurrent(): boolean;+ release(): void;+};++type ActiveVoiceCapture = {+ token: symbol;+ finish: () => void;+};++let activeVoiceCapture: ActiveVoiceCapture | null = null;++/**+ * Give the newest explicit voice action sole ownership of the browser mic.+ * Replacing an owner asks it to finish first, preserving captured speech while+ * preventing hidden Chat and Show Page recorders from running concurrently.+ */+export const claimVoiceCapture = (finish: () => void): VoiceCaptureClaim => {+ const token = Symbol('voice-capture');+ const previous = activeVoiceCapture;+ activeVoiceCapture = { token, finish };+ try {+ previous?.finish();+ } catch {+ // Ownership has already moved; a stale recorder cannot block the new one.+ }+ let released = false;+ return {+ isCurrent: () => !released && activeVoiceCapture?.token === token,+ release: () => {+ if (released) return;+ released = true;+ if (activeVoiceCapture?.token === token) activeVoiceCapture = null;+ },+ };+};+export const isVoiceControlDisabled = (disabled: boolean,recording: boolean,