Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

feat(voice): host microphone narration in the Firefox sidebar

Luis Ortiza75d3f8c949d
diff --git a/src/entrypoints/background/voice.ts b/src/entrypoints/background/voice.ts
index 43b1664..1030cd3 100644
--- a/src/entrypoints/background/voice.ts
+++ b/src/entrypoints/background/voice.ts
@@ -3,15 +3,16 @@ import { applyNarrationToSteps, getStepsForGuide } from '@/core/guides/service';
import { localStorage, onMessage as onRuntimeMessage } from '@/lib/browser-api';
import { logger } from '@/lib/logger';
import {
- closeOffscreenDocument,
- ensureOffscreenDocument,
- getVoiceStatus,
- hasOffscreenDocument,
+ closeVoiceHost,
+ closeVoiceHostIfIdle,
+ ensureVoiceHost,
+ hasVoiceHost,
openMicPermissionPage,
queryMicPermission,
+ registerVoicePanelRelay,
startVoiceCapture,
stopVoiceCapture,
- supportsOffscreen,
+ supportsVoice,
} from '@/lib/offscreen';
import { broadcastVoiceToPanel, type PanelVoiceUpdate } from '@/lib/port';
import {
@@ -19,10 +20,14 @@ import {
VOICE_BACKGROUND_TARGET,
type VoiceErrorEvent,
type VoiceEvent,
+ type VoiceHandoffEvent,
VoiceMessage,
type VoicePermissionResultEvent,
type VoiceResultEvent,
+ type VoiceStepMark,
} from '@/lib/voice-messages';
+import { narrateRecording, readTranscriptionSettings, type VoiceRecording } from '@/lib/voice-narration';
+import { handedOffPcm, voiceStopAction } from '@/lib/voice-recovery';
const START_TIMEOUT_MS = 8000;
@@ -61,18 +66,15 @@ async function readVoiceSettings(): Promise<{ enabled: boolean; hasApiKey: boole
};
}
-async function closeVoiceHostIfIdle(): Promise<void> {
- const status = await getVoiceStatus().catch(() => null);
- if (status?.recording || status?.transcribing) return;
- await closeOffscreenDocument();
-}
+let orphanAudio: VoiceRecording | null = null;
+let transcribingGuideId: string | null = null;
function requestMicPermission(tabId?: number): void {
void openMicPermissionPage(tabId).catch((error) => logger.error('voice: mic permission page failed to open', error));
}
async function beginVoiceCapture(microphoneId: string | undefined, tabId: number | undefined): Promise<void> {
- if (!(await ensureOffscreenDocument())) {
+ if (!(await ensureVoiceHost())) {
report({ phase: 'error', reason: 'unsupported', error: 'The offscreen document could not be created' });
return;
}
@@ -96,11 +98,11 @@ async function beginVoiceCapture(microphoneId: string | undefined, tabId: number
logger.warn('voice: narration unavailable, recording without it', started);
report({ phase: 'error', reason: started.reason, error: started.error });
if (started.reason === 'permission-denied') requestMicPermission(tabId);
- await closeOffscreenDocument();
+ await closeVoiceHost();
}
export async function startVoiceNarration(tabId?: number): Promise<void> {
- if (!supportsOffscreen()) return;
+ if (!supportsVoice()) return;
try {
const { enabled, hasApiKey, microphoneId } = await readVoiceSettings();
if (!enabled) return;
@@ -116,19 +118,54 @@ export async function startVoiceNarration(tabId?: number): Promise<void> {
}
}
+function stepMarks(steps: Array<{ id: string; timestamp: number }>): VoiceStepMark[] {
+ return steps.map((step) => ({ stepId: step.id, timestamp: step.timestamp }));
+}
+
+async function recoverNarration(guideId: string): Promise<void> {
+ const audio = orphanAudio;
+ orphanAudio = null;
+ if (!audio || import.meta.env.BROWSER !== 'firefox') return;
+
+ const settings = await readTranscriptionSettings();
+ if (!settings.apiKey) {
+ report({ phase: 'error', reason: 'missing-api-key', error: 'No transcription API key is configured' });
+ return;
+ }
+
+ logger.warn('voice: transcribing narration captured before the microphone host went away');
+ transcribingGuideId = guideId;
+ report({ phase: 'transcribing' });
+ const steps = await getStepsForGuide(guideId);
+ const result = await narrateRecording(audio, stepMarks(steps), settings);
+ await applyNarration(guideId, result);
+}
+
export async function stopVoiceNarration(guideId: string): Promise<void> {
- if (!supportsOffscreen()) return;
+ if (!supportsVoice()) return;
try {
- if (!(await hasOffscreenDocument())) return;
+ const action = voiceStopAction({
+ hostAlive: await hasVoiceHost(),
+ hasOrphanAudio: orphanAudio !== null,
+ wasRecording: phase.phase === 'recording',
+ });
+
+ if (action === 'skip') return;
+ if (action === 'recover') {
+ await recoverNarration(guideId);
+ return;
+ }
+ if (action === 'report-lost') {
+ report({ phase: 'error', reason: 'stream-ended', error: 'The microphone stopped before recording ended' });
+ return;
+ }
const steps = await getStepsForGuide(guideId);
- const response = await stopVoiceCapture(
- guideId,
- steps.map((step) => ({ stepId: step.id, timestamp: step.timestamp })),
- );
+ const response = await stopVoiceCapture(guideId, stepMarks(steps));
if (response.ok) {
logger.info('voice: transcribing narration', response);
+ transcribingGuideId = guideId;
if (phase.phase === 'recording') report({ phase: 'transcribing' });
return;
}
@@ -143,15 +180,16 @@ export async function stopVoiceNarration(guideId: string): Promise<void> {
}
}
-async function persistNarration(event: VoiceResultEvent): Promise<void> {
+async function applyNarration(guideId: string, result: VoiceResultEvent['result']): Promise<void> {
try {
- const steps = await getStepsForGuide(event.guideId);
+ transcribingGuideId = null;
+ const steps = await getStepsForGuide(guideId);
const updates = narrationUpdates(
- event.result,
+ result,
steps.map((step) => step.id),
);
await applyNarrationToSteps(updates);
- logger.info('voice: narration applied', { narrated: updates.length, of: steps.length, stats: event.result.stats });
+ logger.info('voice: narration applied', { narrated: updates.length, of: steps.length, stats: result.stats });
report({ phase: 'idle', narrated: updates.length });
} catch (error) {
logger.error('voice: narration could not be applied', error);
@@ -166,13 +204,35 @@ function handleVoiceError(event: VoiceErrorEvent): void {
report({ phase: 'error', reason: event.reason, error: event.error });
}
+function handleVoiceHandoff(event: VoiceHandoffEvent): void {
+ const pcm = handedOffPcm(event.pcm);
+ if (!pcm) {
+ logger.error('voice: handed-off audio did not survive the message boundary', typeof event.pcm);
+ return;
+ }
+
+ orphanAudio = {
+ pcm,
+ sampleRate: event.sampleRate,
+ audioEpochMs: event.audioEpochMs,
+ durationSeconds: event.durationSeconds,
+ };
+ logger.warn('voice: microphone host handed off captured audio', {
+ samples: pcm.length,
+ durationSeconds: event.durationSeconds,
+ });
+ if (transcribingGuideId) void recoverNarration(transcribingGuideId);
+}
+
function handlePermissionResult(event: VoicePermissionResultEvent): void {
logger.info('voice: microphone permission', event.state);
if (event.state === 'granted' && phase.phase === 'error') report({ phase: 'idle' });
}
export function registerVoiceListeners(): void {
- if (!supportsOffscreen()) return;
+ if (!supportsVoice()) return;
+
+ registerVoicePanelRelay();
onRuntimeMessage((message) => {
if (!isVoiceMessageFor(VOICE_BACKGROUND_TARGET, message)) return undefined;
@@ -180,7 +240,10 @@ export function registerVoiceListeners(): void {
switch (event.type) {
case VoiceMessage.VOICE_RESULT:
- void persistNarration(event);
+ void applyNarration(event.guideId, event.result);
+ return undefined;
+ case VoiceMessage.VOICE_HANDOFF:
+ handleVoiceHandoff(event);
return undefined;
case VoiceMessage.VOICE_ERROR:
handleVoiceError(event);
diff --git a/src/entrypoints/offscreen/index.ts b/src/entrypoints/offscreen/index.ts
index 93e07d7..7130188 100644
--- a/src/entrypoints/offscreen/index.ts
+++ b/src/entrypoints/offscreen/index.ts
@@ -1,240 +1,3 @@
-import { detectSpeechByEnergy } from '@/core/capture/voice/energy-gate';
-import { runNarrationPipeline } from '@/core/capture/voice/pipeline';
-import { buildStepWindows } from '@/core/capture/voice/step-windows';
-import { createTranscriber, type VoiceProvider } from '@/core/capture/voice/transcribe';
-import type { NarrationResult } from '@/core/capture/voice/types';
-import { getExtensionURL, localStorage, onMessage, sendMessage } from '@/lib/browser-api';
-import { logger } from '@/lib/logger';
-import {
- isVoiceMessageFor,
- VOICE_BACKGROUND_TARGET,
- VOICE_OFFSCREEN_TARGET,
- VOICE_SIDEPANEL_TARGET,
- type VoiceEpochEvent,
- type VoiceErrorEvent,
- type VoiceErrorReason,
- type VoiceEvent,
- type VoiceLevelEvent,
- VoiceMessage,
- type VoicePermissionQueryResponse,
- type VoicePermissionState,
- type VoiceRequest,
- type VoiceResultEvent,
- type VoiceStartRequest,
- type VoiceStartResponse,
- type VoiceStatusResponse,
- type VoiceStopRequest,
- type VoiceStopResponse,
- voiceMessage,
-} from '@/lib/voice-messages';
-import { MicRecorder, type MicRecording } from './mic-recorder';
+import { startVoiceHost } from '@/lib/voice-host';
-const VOICE_PROVIDERS: VoiceProvider[] = ['openai', 'groq'];
-
-interface VoiceSettings {
- provider: VoiceProvider;
- apiKey: string;
- language?: string;
-}
-
-const EMPTY_RESULT: NarrationResult = {
- descriptions: [],
- stats: {
- batches: 0,
- failedBatches: 0,
- droppedBatches: 0,
- verbatimSegments: 0,
- splitSegments: 0,
- rejectedSegments: 0,
- },
-};
-
-function emit(event: VoiceEvent): void {
- void sendMessage(event as unknown as Record<string, unknown>).catch(() => undefined);
-}
-
-function describe(error: unknown): string {
- return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
-}
-
-function startFailureReason(error: unknown): VoiceErrorReason {
- if (!(error instanceof Error)) return 'unknown';
- if (error.name === 'NotAllowedError' || error.name === 'SecurityError') return 'permission-denied';
- if (error.name === 'NotFoundError' || error.name === 'OverconstrainedError') return 'no-device';
- if (error.name === 'NotSupportedError') return 'unsupported';
- return 'unknown';
-}
-
-const recorder = new MicRecorder(getExtensionURL('/pcm-processor.js'), {
- onEpoch: (audioEpochMs) =>
- emit(
- voiceMessage<VoiceEpochEvent>({
- type: VoiceMessage.VOICE_EPOCH,
- target: VOICE_BACKGROUND_TARGET,
- audioEpochMs,
- }),
- ),
- onLevel: (level, speaking) =>
- emit(
- voiceMessage<VoiceLevelEvent>({
- type: VoiceMessage.VOICE_LEVEL,
- target: VOICE_SIDEPANEL_TARGET,
- level,
- speaking,
- }),
- ),
- onStreamEnded: () =>
- emit(
- voiceMessage<VoiceErrorEvent>({
- type: VoiceMessage.VOICE_ERROR,
- target: VOICE_BACKGROUND_TARGET,
- reason: 'stream-ended',
- error: 'The microphone stream ended before recording stopped',
- }),
- ),
-});
-
-async function readVoiceSettings(): Promise<VoiceSettings> {
- const stored = await localStorage.get(['voiceProvider', 'voiceApiKey', 'voiceLanguage', 'aiLanguage']);
- const provider = stored.voiceProvider as VoiceProvider;
- const locale = (stored.voiceLanguage ?? stored.aiLanguage) as string | undefined;
- return {
- provider: VOICE_PROVIDERS.includes(provider) ? provider : 'openai',
- apiKey: typeof stored.voiceApiKey === 'string' ? stored.voiceApiKey.trim() : '',
- language: locale ? locale.split('-')[0] : undefined,
- };
-}
-
-async function handleStart(request: VoiceStartRequest): Promise<VoiceStartResponse> {
- if (recorder.recording) {
- return { started: false, reason: 'already-recording', error: 'Microphone capture is already running' };
- }
- try {
- const stream = await recorder.start(request.deviceId);
- logger.info('voice: microphone capture started', stream);
- return { started: true, ...stream };
- } catch (error) {
- recorder.release();
- logger.error('voice: microphone capture failed to start', error);
- return { started: false, reason: startFailureReason(error), error: describe(error) };
- }
-}
-
-let pending = 0;
-
-function deliver(guideId: string, result: NarrationResult): void {
- emit(
- voiceMessage<VoiceResultEvent>({
- type: VoiceMessage.VOICE_RESULT,
- target: VOICE_BACKGROUND_TARGET,
- guideId,
- result,
- }),
- );
-}
-
-async function narrate(
- request: VoiceStopRequest,
- recording: MicRecording,
- audioEpochMs: number,
- settings: VoiceSettings,
-): Promise<NarrationResult> {
- try {
- const result = await runNarrationPipeline({
- pcm: recording.pcm,
- sampleRate: recording.sampleRate,
- steps: buildStepWindows(request.steps, audioEpochMs, recording.durationSeconds),
- detectSpeech: detectSpeechByEnergy,
- transcribe: createTranscriber(settings),
- });
- logger.info('voice: narration pipeline finished', result.stats);
- return result;
- } catch (error) {
- logger.error('voice: narration pipeline failed', error);
- return EMPTY_RESULT;
- }
-}
-
-async function transcribeInBackground(
- request: VoiceStopRequest,
- recording: MicRecording,
- audioEpochMs: number,
- settings: VoiceSettings,
-): Promise<void> {
- pending += 1;
- const result = await narrate(request, recording, audioEpochMs, settings);
- pending -= 1;
- deliver(request.guideId, result);
-}
-
-async function handleStop(request: VoiceStopRequest): Promise<VoiceStopResponse> {
- if (!recorder.recording) {
- return { ok: false, reason: 'not-recording', error: 'Microphone capture is not running' };
- }
-
- const recording = recorder.stop();
- if (recording.audioEpochMs === null || recording.pcm.length === 0) {
- return { ok: false, reason: 'no-audio', error: 'No microphone audio was captured' };
- }
-
- const audioEpochMs = recording.audioEpochMs;
- const durationSeconds = recording.durationSeconds;
- if (request.steps.length === 0) {
- deliver(request.guideId, EMPTY_RESULT);
- return { ok: true, audioEpochMs, durationSeconds };
- }
-
- const settings = await readVoiceSettings();
- if (!settings.apiKey) {
- return { ok: false, reason: 'missing-api-key', error: 'No transcription API key is configured' };
- }
-
- void transcribeInBackground(request, recording, audioEpochMs, settings);
- return { ok: true, audioEpochMs, durationSeconds };
-}
-
-async function permissionState(): Promise<VoicePermissionQueryResponse> {
- try {
- const result = await navigator.permissions.query({ name: 'microphone' as PermissionName });
- return { state: result.state as VoicePermissionState };
- } catch {
- return { state: 'unknown' };
- }
-}
-
-function status(): VoiceStatusResponse {
- return {
- recording: recorder.recording,
- transcribing: pending > 0,
- audioEpochMs: recorder.audioEpochMs,
- sampleRate: recorder.sampleRate,
- samples: recorder.sampleCount,
- durationSeconds: recorder.durationSeconds,
- };
-}
-
-onMessage((message, _sender, sendResponse) => {
- if (!isVoiceMessageFor(VOICE_OFFSCREEN_TARGET, message)) return undefined;
- const request = message as VoiceRequest;
-
- switch (request.type) {
- case VoiceMessage.VOICE_START:
- void handleStart(request).then(sendResponse);
- return true;
- case VoiceMessage.VOICE_STOP:
- void handleStop(request).then(sendResponse);
- return true;
- case VoiceMessage.VOICE_ABORT:
- recorder.release();
- sendResponse({ ok: true });
- return undefined;
- case VoiceMessage.VOICE_STATUS:
- sendResponse(status());
- return undefined;
- case VoiceMessage.VOICE_PERMISSION_QUERY:
- void permissionState().then(sendResponse);
- return true;
- default:
- return undefined;
- }
-});
+startVoiceHost();
diff --git a/src/entrypoints/sidepanel/index.tsx b/src/entrypoints/sidepanel/index.tsx
index 05e5de4..a20a1cb 100644
--- a/src/entrypoints/sidepanel/index.tsx
+++ b/src/entrypoints/sidepanel/index.tsx
@@ -1,5 +1,8 @@
import ReactDOM from 'react-dom/client';
+import { startSidepanelVoiceHost } from '@/lib/sidepanel-voice-host';
import App from '@/ui/sidepanel/App';
import '@/ui/global.css';
+startSidepanelVoiceHost();
+
ReactDOM.createRoot(document.getElementById('root')!).render(<App />);
diff --git a/src/lib/__tests__/voice-recovery.test.ts b/src/lib/__tests__/voice-recovery.test.ts
new file mode 100644
index 0000000..8fe1965
--- /dev/null
+++ b/src/lib/__tests__/voice-recovery.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from 'vitest';
+import { handedOffPcm, isVoiceStatus, voiceStopAction } from '../voice-recovery';
+
+describe('isVoiceStatus', () => {
+ it('accepts a status response from a live microphone host', () => {
+ expect(
+ isVoiceStatus({
+ recording: true,
+ transcribing: false,
+ audioEpochMs: 1,
+ sampleRate: 16000,
+ samples: 4800,
+ durationSeconds: 0.3,
+ }),
+ ).toBe(true);
+ });
+
+ it('rejects the undefined a closed sidebar leaves behind', () => {
+ expect(isVoiceStatus(undefined)).toBe(false);
+ expect(isVoiceStatus(null)).toBe(false);
+ });
+
+ it('rejects a reply from another listener that answered first', () => {
+ expect(isVoiceStatus({ ok: true })).toBe(false);
+ expect(isVoiceStatus({ recording: 'yes', transcribing: false })).toBe(false);
+ expect(isVoiceStatus('recording')).toBe(false);
+ });
+});
+
+describe('handedOffPcm', () => {
+ it('keeps samples that crossed the message boundary intact', () => {
+ const pcm = Int16Array.of(1, -2, 3);
+ expect(handedOffPcm(pcm)).toBe(pcm);
+ });
+
+ it('rebuilds samples that arrived as a bare buffer', () => {
+ const recovered = handedOffPcm(Int16Array.of(7, 8).buffer);
+ expect(recovered).toEqual(Int16Array.of(7, 8));
+ });
+
+ it('rebuilds samples that arrived as another view of the same bytes', () => {
+ const recovered = handedOffPcm(new Uint8Array(Int16Array.of(-1, 300).buffer));
+ expect(recovered).toEqual(Int16Array.of(-1, 300));
+ });
+
+ it('refuses a payload that lost its type or carries no audio', () => {
+ expect(handedOffPcm({ 0: 1, 1: 2 })).toBeNull();
+ expect(handedOffPcm(undefined)).toBeNull();
+ expect(handedOffPcm(new Int16Array(0))).toBeNull();
+ expect(handedOffPcm(new ArrayBuffer(0))).toBeNull();
+ });
+});
+
+describe('voiceStopAction', () => {
+ it('stops the host that is still answering', () => {
+ expect(voiceStopAction({ hostAlive: true, hasOrphanAudio: false, wasRecording: true })).toBe('stop-host');
+ });
+
+ it('transcribes audio left behind by a host that died', () => {
+ expect(voiceStopAction({ hostAlive: false, hasOrphanAudio: true, wasRecording: true })).toBe('recover');
+ });
+
+ it('prefers the handed-off audio over a host that reopened after the loss', () => {
+ expect(voiceStopAction({ hostAlive: true, hasOrphanAudio: true, wasRecording: false })).toBe('recover');
+ });
+
+ it('reports the loss when a recording host vanished with nothing to salvage', () => {
+ expect(voiceStopAction({ hostAlive: false, hasOrphanAudio: false, wasRecording: true })).toBe('report-lost');
+ });
+
+ it('stays quiet when narration was never running', () => {
+ expect(voiceStopAction({ hostAlive: false, hasOrphanAudio: false, wasRecording: false })).toBe('skip');
+ });
+});
diff --git a/src/entrypoints/offscreen/mic-recorder.ts b/src/lib/mic-recorder.ts
similarity index 100%
rename from src/entrypoints/offscreen/mic-recorder.ts
rename to src/lib/mic-recorder.ts
diff --git a/src/lib/offscreen.ts b/src/lib/offscreen.ts
index c12d75c..5fa6074 100644
--- a/src/lib/offscreen.ts
+++ b/src/lib/offscreen.ts
@@ -1,12 +1,17 @@
-import { createTab, getExtensionURL, sendMessage } from './browser-api';
+import { createTab, getExtensionURL, onMessage, sendMessage } from './browser-api';
import { logger } from './logger';
+import { localVoiceHost } from './voice-local';
import {
+ isVoiceMessageFor,
+ VOICE_BACKGROUND_TARGET,
VOICE_OFFSCREEN_TARGET,
+ VOICE_SIDEPANEL_TARGET,
type VoiceAbortRequest,
type VoiceAbortResponse,
VoiceMessage,
type VoicePermissionQueryRequest,
type VoicePermissionQueryResponse,
+ type VoicePermissionResultEvent,
type VoiceRequest,
type VoiceStartRequest,
type VoiceStartResponse,
@@ -17,6 +22,9 @@ import {
type VoiceStopResponse,
voiceMessage,
} from './voice-messages';
+import { isVoiceStatus } from './voice-recovery';
+
+const IS_FIREFOX = import.meta.env.BROWSER === 'firefox';
const OFFSCREEN_PATH = '/offscreen.html';
const MIC_PERMISSION_PATH = '/mic-permission.html';
@@ -92,24 +100,95 @@ export async function closeOffscreenDocument(): Promise<void> {
}
}
+async function requestMicrophoneInPage(): Promise<boolean> {
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ for (const track of stream.getTracks()) track.stop();
+ return true;
+ } catch (error) {
+ logger.warn('voice: microphone access was not granted', error);
+ return false;
+ }
+}
+
+async function promptForMicrophone(): Promise<void> {
+ const granted = await requestMicrophoneInPage();
+ void sendMessage(
+ voiceMessage<VoicePermissionResultEvent>({
+ type: VoiceMessage.VOICE_PERMISSION_RESULT,
+ target: VOICE_BACKGROUND_TARGET,
+ state: granted ? 'granted' : 'denied',
+ }) as unknown as Record<string, unknown>,
+ ).catch(() => undefined);
+}
+
export function openMicPermissionPage(tabId?: number): Promise<unknown> {
+ if (IS_FIREFOX) {
+ if (localVoiceHost() === null) return Promise.resolve(undefined);
+ return promptForMicrophone();
+ }
const url = getExtensionURL(tabId === undefined ? MIC_PERMISSION_PATH : `${MIC_PERMISSION_PATH}?tabId=${tabId}`);
return createTab({ url, active: true });
}
function request<T>(message: VoiceRequest): Promise<T> {
+ const local = IS_FIREFOX ? localVoiceHost() : null;
+ if (local) return local.handle(message) as Promise<T>;
return sendMessage(message as unknown as Record<string, unknown>) as Promise<T>;
}
+export function supportsVoice(): boolean {
+ return IS_FIREFOX || supportsOffscreen();
+}
+
+export function ensureVoiceHost(): Promise<boolean> {
+ if (IS_FIREFOX) return Promise.resolve(true);
+ return ensureOffscreenDocument();
+}
+
+export async function hasVoiceHost(): Promise<boolean> {
+ if (!IS_FIREFOX) return hasOffscreenDocument();
+ return isVoiceStatus(await getVoiceStatus().catch(() => null));
+}
+
+export async function closeVoiceHost(): Promise<void> {
+ if (IS_FIREFOX) return;
+ await closeOffscreenDocument();
+}
+
+export async function closeVoiceHostIfIdle(): Promise<void> {
+ if (IS_FIREFOX) return;
+ const status = await getVoiceStatus().catch(() => null);
+ if (status?.recording || status?.transcribing) return;
+ await closeOffscreenDocument();
+}
+
+export function registerVoicePanelRelay(): void {
+ if (!IS_FIREFOX) return;
+ onMessage((message) => {
+ if (!isVoiceMessageFor(VOICE_SIDEPANEL_TARGET, message)) return undefined;
+ void sendMessage(message as unknown as Record<string, unknown>).catch(() => undefined);
+ return undefined;
+ });
+}
+
+async function answered<T>(message: VoiceRequest, missing: T): Promise<T> {
+ if (!IS_FIREFOX) return request<T>(message);
+ const response = await request<T | undefined>(message).catch(() => undefined);
+ return response ?? missing;
+}
+
export function startVoiceCapture(deviceId?: string): Promise<VoiceStartResponse> {
- return request(
+ return answered<VoiceStartResponse>(
voiceMessage<VoiceStartRequest>({ type: VoiceMessage.VOICE_START, target: VOICE_OFFSCREEN_TARGET, deviceId }),
+ { started: false, reason: 'unsupported', error: 'No microphone host is available' },
);
}
export function stopVoiceCapture(guideId: string, steps: VoiceStepMark[]): Promise<VoiceStopResponse> {
- return request(
+ return answered<VoiceStopResponse>(
voiceMessage<VoiceStopRequest>({ type: VoiceMessage.VOICE_STOP, target: VOICE_OFFSCREEN_TARGET, guideId, steps }),
+ { ok: false, reason: 'stream-ended', error: 'The microphone host is no longer available' },
);
}
diff --git a/src/lib/sidepanel-voice-host.ts b/src/lib/sidepanel-voice-host.ts
new file mode 100644
index 0000000..dcda4dc
--- /dev/null
+++ b/src/lib/sidepanel-voice-host.ts
@@ -0,0 +1,15 @@
+import { logger } from './logger';
+import { setLocalVoiceHost } from './voice-local';
+
+export function startSidepanelVoiceHost(): void {
+ if (import.meta.env.BROWSER !== 'firefox') return;
+
+ void import('./voice-host')
+ .then(({ startVoiceHost }) => {
+ const host = startVoiceHost();
+ setLocalVoiceHost(host);
+ window.addEventListener('pagehide', () => host.surrender());
+ logger.debug('voice: sidebar microphone host ready');
+ })
+ .catch((error) => logger.error('voice: sidebar microphone host failed to load', error));
+}
diff --git a/src/lib/voice-host.ts b/src/lib/voice-host.ts
new file mode 100644
index 0000000..3d7cf53
--- /dev/null
+++ b/src/lib/voice-host.ts
@@ -0,0 +1,244 @@
+import type { NarrationResult } from '@/core/capture/voice/types';
+import { getExtensionURL, onMessage, sendMessage } from './browser-api';
+import { logger } from './logger';
+import { MicRecorder, type MicRecording } from './mic-recorder';
+import {
+ isVoiceMessageFor,
+ VOICE_BACKGROUND_TARGET,
+ VOICE_OFFSCREEN_TARGET,
+ VOICE_SIDEPANEL_TARGET,
+ type VoiceEpochEvent,
+ type VoiceErrorEvent,
+ type VoiceErrorReason,
+ type VoiceEvent,
+ type VoiceHandoffEvent,
+ type VoiceLevelEvent,
+ VoiceMessage,
+ type VoicePermissionQueryResponse,
+ type VoicePermissionState,
+ type VoiceRequest,
+ type VoiceResultEvent,
+ type VoiceStartRequest,
+ type VoiceStartResponse,
+ type VoiceStatusResponse,
+ type VoiceStopRequest,
+ type VoiceStopResponse,
+ voiceMessage,
+} from './voice-messages';
+import {
+ EMPTY_NARRATION,
+ narrateRecording,
+ readTranscriptionSettings,
+ type TranscriptionSettings,
+ type VoiceRecording,
+} from './voice-narration';
+
+export interface VoiceHost {
+ handle(request: VoiceRequest): Promise<unknown>;
+ status(): VoiceStatusResponse;
+ surrender(): void;
+}
+
+function emit(event: VoiceEvent): void {
+ void sendMessage(event as unknown as Record<string, unknown>).catch(() => undefined);
+}
+
+function describe(error: unknown): string {
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
+}
+
+function startFailureReason(error: unknown): VoiceErrorReason {
+ if (!(error instanceof Error)) return 'unknown';
+ if (error.name === 'NotAllowedError' || error.name === 'SecurityError') return 'permission-denied';
+ if (error.name === 'NotFoundError' || error.name === 'OverconstrainedError') return 'no-device';
+ if (error.name === 'NotSupportedError') return 'unsupported';
+ return 'unknown';
+}
+
+function usableRecording(recording: MicRecording): VoiceRecording | null {
+ if (recording.audioEpochMs === null || recording.pcm.length === 0) return null;
+ return {
+ pcm: recording.pcm,
+ sampleRate: recording.sampleRate,
+ audioEpochMs: recording.audioEpochMs,
+ durationSeconds: recording.durationSeconds,
+ };
+}
+
+async function permissionState(): Promise<VoicePermissionQueryResponse> {
+ try {
+ const result = await navigator.permissions.query({ name: 'microphone' as PermissionName });
+ return { state: result.state as VoicePermissionState };
+ } catch {
+ return { state: 'unknown' };
+ }
+}
+
+export function createVoiceHost(): VoiceHost {
+ let pending = 0;
+ let retained: VoiceRecording | null = null;
+
+ const recorder = new MicRecorder(getExtensionURL('/pcm-processor.js'), {
+ onEpoch: (audioEpochMs) =>
+ emit(
+ voiceMessage<VoiceEpochEvent>({
+ type: VoiceMessage.VOICE_EPOCH,
+ target: VOICE_BACKGROUND_TARGET,
+ audioEpochMs,
+ }),
+ ),
+ onLevel: (level, speaking) =>
+ emit(
+ voiceMessage<VoiceLevelEvent>({
+ type: VoiceMessage.VOICE_LEVEL,
+ target: VOICE_SIDEPANEL_TARGET,
+ level,
+ speaking,
+ }),
+ ),
+ onStreamEnded: () => reportStreamEnded(),
+ });
+
+ function reportStreamEnded(): void {
+ emit(
+ voiceMessage<VoiceErrorEvent>({
+ type: VoiceMessage.VOICE_ERROR,
+ target: VOICE_BACKGROUND_TARGET,
+ reason: 'stream-ended',
+ error: 'The microphone stream ended before recording stopped',
+ }),
+ );
+ }
+
+ function deliver(guideId: string, result: NarrationResult): void {
+ emit(
+ voiceMessage<VoiceResultEvent>({
+ type: VoiceMessage.VOICE_RESULT,
+ target: VOICE_BACKGROUND_TARGET,
+ guideId,
+ result,
+ }),
+ );
+ }
+
+ function handOff(audio: VoiceRecording): void {
+ emit(
+ voiceMessage<VoiceHandoffEvent>({
+ type: VoiceMessage.VOICE_HANDOFF,
+ target: VOICE_BACKGROUND_TARGET,
+ pcm: audio.pcm,
+ sampleRate: audio.sampleRate,
+ audioEpochMs: audio.audioEpochMs,
+ durationSeconds: audio.durationSeconds,
+ }),
+ );
+ }
+
+ async function handleStart(request: VoiceStartRequest): Promise<VoiceStartResponse> {
+ if (recorder.recording) {
+ return { started: false, reason: 'already-recording', error: 'Microphone capture is already running' };
+ }
+ try {
+ const stream = await recorder.start(request.deviceId);
+ logger.info('voice: microphone capture started', stream);
+ return { started: true, ...stream };
+ } catch (error) {
+ recorder.release();
+ logger.error('voice: microphone capture failed to start', error);
+ return { started: false, reason: startFailureReason(error), error: describe(error) };
+ }
+ }
+
+ async function transcribeInBackground(
+ guideId: string,
+ audio: VoiceRecording,
+ steps: VoiceStopRequest['steps'],
+ settings: TranscriptionSettings,
+ ): Promise<void> {
+ pending += 1;
+ const result = await narrateRecording(audio, steps, settings);
+ pending -= 1;
+ retained = null;
+ deliver(guideId, result);
+ }
+
+ async function handleStop(request: VoiceStopRequest): Promise<VoiceStopResponse> {
+ if (!recorder.recording) {
+ return { ok: false, reason: 'not-recording', error: 'Microphone capture is not running' };
+ }
+
+ const audio = usableRecording(recorder.stop());
+ if (!audio) {
+ return { ok: false, reason: 'no-audio', error: 'No microphone audio was captured' };
+ }
+
+ const { audioEpochMs, durationSeconds } = audio;
+ if (request.steps.length === 0) {
+ deliver(request.guideId, EMPTY_NARRATION);
+ return { ok: true, audioEpochMs, durationSeconds };
+ }
+
+ const settings = await readTranscriptionSettings();
+ if (!settings.apiKey) {
+ return { ok: false, reason: 'missing-api-key', error: 'No transcription API key is configured' };
+ }
+
+ retained = audio;
+ void transcribeInBackground(request.guideId, audio, request.steps, settings);
+ return { ok: true, audioEpochMs, durationSeconds };
+ }
+
+ function status(): VoiceStatusResponse {
+ return {
+ recording: recorder.recording,
+ transcribing: pending > 0,
+ audioEpochMs: recorder.audioEpochMs,
+ sampleRate: recorder.sampleRate,
+ samples: recorder.sampleCount,
+ durationSeconds: recorder.durationSeconds,
+ };
+ }
+
+ function handle(request: VoiceRequest): Promise<unknown> {
+ switch (request.type) {
+ case VoiceMessage.VOICE_START:
+ return handleStart(request);
+ case VoiceMessage.VOICE_STOP:
+ return handleStop(request);
+ case VoiceMessage.VOICE_ABORT:
+ recorder.release();
+ retained = null;
+ return Promise.resolve({ ok: true });
+ case VoiceMessage.VOICE_STATUS:
+ return Promise.resolve(status());
+ case VoiceMessage.VOICE_PERMISSION_QUERY:
+ return permissionState();
+ default:
+ return Promise.resolve(undefined);
+ }
+ }
+
+ function surrender(): void {
+ if (recorder.recording) {
+ const audio = usableRecording(recorder.stop());
+ if (audio) handOff(audio);
+ reportStreamEnded();
+ return;
+ }
+ if (pending > 0 && retained) handOff(retained);
+ }
+
+ return { handle, status, surrender };
+}
+
+export function startVoiceHost(): VoiceHost {
+ const host = createVoiceHost();
+
+ onMessage((message, _sender, sendResponse) => {
+ if (!isVoiceMessageFor(VOICE_OFFSCREEN_TARGET, message)) return undefined;
+ void host.handle(message as VoiceRequest).then(sendResponse);
+ return true;
+ });
+
+ return host;
+}
diff --git a/src/lib/voice-local.ts b/src/lib/voice-local.ts
new file mode 100644
index 0000000..494f74e
--- /dev/null
+++ b/src/lib/voice-local.ts
@@ -0,0 +1,15 @@
+import type { VoiceRequest } from './voice-messages';
+
+export interface LocalVoiceHost {
+ handle(request: VoiceRequest): Promise<unknown>;
+}
+
+let host: LocalVoiceHost | null = null;
+
+export function setLocalVoiceHost(next: LocalVoiceHost | null): void {
+ host = next;
+}
+
+export function localVoiceHost(): LocalVoiceHost | null {
+ return host;
+}
diff --git a/src/lib/voice-messages.ts b/src/lib/voice-messages.ts
index df71ec6..bda26cc 100644
--- a/src/lib/voice-messages.ts
+++ b/src/lib/voice-messages.ts
@@ -19,6 +19,7 @@ export const VoiceMessage = {
VOICE_LEVEL: 'VOICE_LEVEL',
VOICE_ERROR: 'VOICE_ERROR',
VOICE_RESULT: 'VOICE_RESULT',
+ VOICE_HANDOFF: 'VOICE_HANDOFF',
VOICE_PERMISSION_RESULT: 'VOICE_PERMISSION_RESULT',
} as const;
@@ -128,6 +129,15 @@ export interface VoiceResultEvent extends VoiceEnvelope {
result: NarrationResult;
}
+export interface VoiceHandoffEvent extends VoiceEnvelope {
+ type: typeof VoiceMessage.VOICE_HANDOFF;
+ target: typeof VOICE_BACKGROUND_TARGET;
+ pcm: Int16Array;
+ sampleRate: number;
+ audioEpochMs: number;
+ durationSeconds: number;
+}
+
export interface VoicePermissionResultEvent extends VoiceEnvelope {
type: typeof VoiceMessage.VOICE_PERMISSION_RESULT;
target: typeof VOICE_BACKGROUND_TARGET;
@@ -146,6 +156,7 @@ export type VoiceEvent =
| VoiceLevelEvent
| VoiceErrorEvent
| VoiceResultEvent
+ | VoiceHandoffEvent
| VoicePermissionResultEvent;
export function voiceMessage<T extends VoiceEnvelope>(message: Omit<T, 'timestamp'>): T {
diff --git a/src/lib/voice-narration.ts b/src/lib/voice-narration.ts
new file mode 100644
index 0000000..4d55f85
--- /dev/null
+++ b/src/lib/voice-narration.ts
@@ -0,0 +1,67 @@
+import { detectSpeechByEnergy } from '@/core/capture/voice/energy-gate';
+import { runNarrationPipeline } from '@/core/capture/voice/pipeline';
+import { buildStepWindows } from '@/core/capture/voice/step-windows';
+import { createTranscriber, type VoiceProvider } from '@/core/capture/voice/transcribe';
+import type { NarrationResult } from '@/core/capture/voice/types';
+import { localStorage } from './browser-api';
+import { logger } from './logger';
+import type { VoiceStepMark } from './voice-messages';
+
+const VOICE_PROVIDERS: VoiceProvider[] = ['openai', 'groq'];
+
+export interface TranscriptionSettings {
+ provider: VoiceProvider;
+ apiKey: string;
+ language?: string;
+}
+
+export interface VoiceRecording {
+ pcm: Int16Array;
+ sampleRate: number;
+ audioEpochMs: number;
+ durationSeconds: number;
+}
+
+export const EMPTY_NARRATION: NarrationResult = {
+ descriptions: [],
+ stats: {
+ batches: 0,
+ failedBatches: 0,
+ droppedBatches: 0,
+ verbatimSegments: 0,
+ splitSegments: 0,
+ rejectedSegments: 0,
+ },
+};
+
+export async function readTranscriptionSettings(): Promise<TranscriptionSettings> {
+ const stored = await localStorage.get(['voiceProvider', 'voiceApiKey', 'voiceLanguage', 'aiLanguage']);
+ const provider = stored.voiceProvider as VoiceProvider;
+ const locale = (stored.voiceLanguage ?? stored.aiLanguage) as string | undefined;
+ return {
+ provider: VOICE_PROVIDERS.includes(provider) ? provider : 'openai',
+ apiKey: typeof stored.voiceApiKey === 'string' ? stored.voiceApiKey.trim() : '',
+ language: locale ? locale.split('-')[0] : undefined,
+ };
+}
+
+export async function narrateRecording(
+ recording: VoiceRecording,
+ steps: VoiceStepMark[],
+ settings: TranscriptionSettings,
+): Promise<NarrationResult> {
+ try {
+ const result = await runNarrationPipeline({
+ pcm: recording.pcm,
+ sampleRate: recording.sampleRate,
+ steps: buildStepWindows(steps, recording.audioEpochMs, recording.durationSeconds),
+ detectSpeech: detectSpeechByEnergy,
+ transcribe: createTranscriber(settings),
+ });
+ logger.info('voice: narration pipeline finished', result.stats);
+ return result;
+ } catch (error) {
+ logger.error('voice: narration pipeline failed', error);
+ return EMPTY_NARRATION;
+ }
+}
diff --git a/src/lib/voice-recovery.ts b/src/lib/voice-recovery.ts
new file mode 100644
index 0000000..46c4389
--- /dev/null
+++ b/src/lib/voice-recovery.ts
@@ -0,0 +1,28 @@
+import type { VoiceStatusResponse } from './voice-messages';
+
+export type VoiceStopAction = 'stop-host' | 'recover' | 'report-lost' | 'skip';
+
+export function isVoiceStatus(value: unknown): value is VoiceStatusResponse {
+ if (typeof value !== 'object' || value === null) return false;
+ const candidate = value as Partial<VoiceStatusResponse>;
+ return typeof candidate.recording === 'boolean' && typeof candidate.transcribing === 'boolean';
+}
+
+export function handedOffPcm(value: unknown): Int16Array | null {
+ if (value instanceof Int16Array) return value.length > 0 ? value : null;
+ if (value instanceof ArrayBuffer) return value.byteLength > 0 ? new Int16Array(value) : null;
+ if (ArrayBuffer.isView(value)) {
+ return value.byteLength > 0 ? new Int16Array(value.buffer, value.byteOffset, value.byteLength / 2) : null;
+ }
+ return null;
+}
+
+export function voiceStopAction(input: {
+ hostAlive: boolean;
+ hasOrphanAudio: boolean;
+ wasRecording: boolean;
+}): VoiceStopAction {
+ if (input.hasOrphanAudio) return 'recover';
+ if (input.hostAlive) return 'stop-host';
+ return input.wasRecording ? 'report-lost' : 'skip';
+}