π¬ A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots π
TypeScript browser-extensionchrome-extensiondocumentationfirefox-extensionguide-generatorlocal-firstmanifest-v3privacy-firstproductivityreactscreenshotstep-by-step-guidetutorialtypescriptworkflowwxt
fix(voice): settle narration when there is nothing left to transcribe
davbio8f0c09c539ac
diff --git a/src/entrypoints/background/__tests__/narration-settle.test.ts b/src/entrypoints/background/__tests__/narration-settle.test.tsnew file mode 100644index 0000000..63b55dc--- /dev/null+++ b/src/entrypoints/background/__tests__/narration-settle.test.ts@@ -0,0 +1,132 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const ensureVoiceHost = vi.fn();+const queryMicPermission = vi.fn();+const startVoiceCapture = vi.fn();+const stopVoiceCapture = vi.fn();+const hasVoiceHost = vi.fn();+const closeVoiceHostIfIdle = vi.fn();+const storageGet = vi.fn();++vi.mock('@/lib/offscreen', () => ({+ supportsVoice: () => true,+ ensureVoiceHost: (...args: unknown[]) => ensureVoiceHost(...args),+ queryMicPermission: (...args: unknown[]) => queryMicPermission(...args),+ startVoiceCapture: (...args: unknown[]) => startVoiceCapture(...args),+ stopVoiceCapture: (...args: unknown[]) => stopVoiceCapture(...args),+ hasVoiceHost: (...args: unknown[]) => hasVoiceHost(...args),+ closeVoiceHostIfIdle: (...args: unknown[]) => closeVoiceHostIfIdle(...args),+ closeVoiceHost: vi.fn(),+ flushVoiceCapture: vi.fn(),+ openMicPermissionPage: vi.fn(),+ registerVoicePanelRelay: vi.fn(),+}));++vi.mock('@/lib/browser-api', () => ({+ localStorage: { get: (...args: unknown[]) => storageGet(...args), set: vi.fn() },+ onMessage: vi.fn(),+}));++vi.mock('@/lib/port', () => ({ broadcastVoiceToPanel: vi.fn() }));++vi.mock('@/lib/voice-narration', () => ({+ readTranscriptionSettings: () => Promise.resolve({ provider: 'openai', apiKey: 'sk-test' }),+ narrateRecording: vi.fn(),+}));++vi.mock('@/core/guides/service', () => ({+ saveTranscript: vi.fn().mockResolvedValue(undefined),+ applyNarrationToSteps: vi.fn().mockResolvedValue(undefined),+ findExistingStepIds: vi.fn().mockResolvedValue([]),+ getStepsForGuide: vi.fn().mockResolvedValue([]),+}));++vi.mock('../deferred-descriptions', () => ({ discardDeferred: vi.fn() }));+vi.mock('../describe-unnarrated', () => ({ describeStepNow: vi.fn(), describeUnnarratedSteps: vi.fn() }));++import {+ applyNarration,+ getVoiceUpdate,+ startVoiceNarration,+ stopVoiceNarration,+ whenNarrationSettled,+} from '../voice';++const EMPTY_RESULT = {+ descriptions: [],+ transcript: { epochMs: 1_700_000_000_000, lines: [] },+ stats: {+ batches: 0,+ failedBatches: 0,+ droppedBatches: 0,+ forcedSplits: 0,+ verbatimSegments: 0,+ splitSegments: 0,+ rejectedSegments: 0,+ },+};++async function beginRecording(): Promise<void> {+ await startVoiceNarration(undefined);+ expect(getVoiceUpdate().phase).toBe('recording');+}++beforeEach(() => {+ storageGet.mockReset().mockResolvedValue({ voiceEnabled: true, voiceProvider: 'openai', voiceApiKey: 'sk-test' });+ ensureVoiceHost.mockReset().mockResolvedValue(true);+ queryMicPermission.mockReset().mockResolvedValue({ state: 'granted' });+ startVoiceCapture.mockReset().mockResolvedValue({ started: true });+ hasVoiceHost.mockReset().mockResolvedValue(true);+ closeVoiceHostIfIdle.mockReset().mockResolvedValue(undefined);+ stopVoiceCapture.mockReset();+});++describe('a narration that has nothing left to transcribe', () => {+ it('settles when the host delivers the result before the stop call resolves', async () => {+ const deliversResultBeforeResolving = async () => {+ await applyNarration('g1', EMPTY_RESULT, true);+ return { ok: true, audioEpochMs: 1_700_000_000_000, durationSeconds: 4 };+ };+ stopVoiceCapture.mockImplementation(deliversResultBeforeResolving);++ await beginRecording();+ await stopVoiceNarration('g1');++ expect(getVoiceUpdate().phase).toBe('idle');+ await expect(whenNarrationSettled()).resolves.toBeUndefined();+ });++ it('settles when the result arrives after the stop call resolves', async () => {+ stopVoiceCapture.mockResolvedValue({ ok: true, audioEpochMs: 1_700_000_000_000, durationSeconds: 4 });++ await beginRecording();+ await stopVoiceNarration('g1');+ expect(getVoiceUpdate().phase).toBe('transcribing');++ await applyNarration('g1', EMPTY_RESULT, true);++ expect(getVoiceUpdate().phase).toBe('idle');+ await expect(whenNarrationSettled()).resolves.toBeUndefined();+ });++ it('does not leave the panel transcribing when the host refuses the stop', async () => {+ stopVoiceCapture.mockResolvedValue({ ok: false, reason: 'no-audio', error: 'No microphone audio was captured' });++ await beginRecording();+ await stopVoiceNarration('g1');++ expect(getVoiceUpdate().phase).toBe('error');+ await expect(whenNarrationSettled()).resolves.toBeUndefined();+ });++ it('keeps a mid-recording flush from ending the transcription', async () => {+ stopVoiceCapture.mockResolvedValue({ ok: true, audioEpochMs: 1_700_000_000_000, durationSeconds: 4 });++ await beginRecording();+ await stopVoiceNarration('g1');++ await applyNarration('g1', EMPTY_RESULT, false);++ expect(getVoiceUpdate().phase).toBe('transcribing');+ });+});diff --git a/src/entrypoints/background/__tests__/narration-transcript.test.ts b/src/entrypoints/background/__tests__/narration-transcript.test.tsindex 1771998..d7d0c66 100644--- a/src/entrypoints/background/__tests__/narration-transcript.test.ts+++ b/src/entrypoints/background/__tests__/narration-transcript.test.ts@@ -43,7 +43,11 @@ beforeEach(() => {describe('applying a narration result', () => {it('stores the transcript, rejected lines and all', async () => {- await applyNarration('g1', { descriptions: [{ stepId: 's1', text: 'Open the billing tab' }], transcript, stats });+ await applyNarration(+ 'g1',+ { descriptions: [{ stepId: 's1', text: 'Open the billing tab' }], transcript, stats },+ false,+ );expect(saveTranscript).toHaveBeenCalledWith('g1', transcript);});@@ -51,7 +55,7 @@ describe('applying a narration result', () => {it('stores a slice that attributed nothing at all', async () => {const orphaned = { epochMs: transcript.epochMs, lines: [transcript.lines[1]] };- await applyNarration('g1', { descriptions: [], transcript: orphaned, stats });+ await applyNarration('g1', { descriptions: [], transcript: orphaned, stats }, false);expect(saveTranscript).toHaveBeenCalledWith('g1', orphaned);expect(applyNarrationToSteps).toHaveBeenCalledWith([]);@@ -60,8 +64,8 @@ describe('applying a narration result', () => {it('keeps each transcribed slice as its own stored row', async () => {const second = { epochMs: transcript.epochMs + 30_000, lines: transcript.lines };- await applyNarration('g1', { descriptions: [], transcript, stats });- await applyNarration('g1', { descriptions: [], transcript: second, stats });+ await applyNarration('g1', { descriptions: [], transcript, stats }, false);+ await applyNarration('g1', { descriptions: [], transcript: second, stats }, false);expect(saveTranscript).toHaveBeenCalledTimes(2);expect(saveTranscript.mock.calls.map((call) => call[1].epochMs)).toEqual([transcript.epochMs, second.epochMs]);@@ -70,7 +74,11 @@ describe('applying a narration result', () => {it('still applies the narration when the transcript cannot be stored', async () => {saveTranscript.mockRejectedValue(new Error('QuotaExceededError'));- await applyNarration('g1', { descriptions: [{ stepId: 's1', text: 'Open the billing tab' }], transcript, stats });+ await applyNarration(+ 'g1',+ { descriptions: [{ stepId: 's1', text: 'Open the billing tab' }], transcript, stats },+ false,+ );expect(applyNarrationToSteps).toHaveBeenCalledWith([{ stepId: 's1', description: 'Open the billing tab' }]);});diff --git a/src/entrypoints/background/voice.ts b/src/entrypoints/background/voice.tsindex 8412932..1767d9b 100644--- a/src/entrypoints/background/voice.ts+++ b/src/entrypoints/background/voice.ts@@ -9,6 +9,7 @@ import {closeVoiceHostIfIdle,ensureVoiceHost,flushVoiceCapture,+ getVoiceStatus,hasVoiceHost,openMicPermissionPage,queryMicPermission,@@ -31,7 +32,7 @@ import {type VoiceStepMark,} from '@/lib/voice-messages';import { narrateRecording, readTranscriptionSettings, type VoiceRecording } from '@/lib/voice-narration';-import { handedOffPcm, voiceStopAction } from '@/lib/voice-recovery';+import { handedOffPcm, isVoiceStatus, voiceStopAction } from '@/lib/voice-recovery';import { discardDeferred } from './deferred-descriptions';import { describeStepNow, describeUnnarratedSteps } from './describe-unnarrated';@@ -92,27 +93,40 @@ let orphanAudio: VoiceRecording | null = null;let transcribingGuideId: string | null = null;let settleNarration: (() => void) | null = null;let narrationSettled: Promise<void> | null = null;+let outstandingTranscriptions = 0;const NARRATION_SETTLE_TIMEOUT_MS = 30000;export function whenNarrationSettled(): Promise<void> {- if (!narrationSettled) return Promise.resolve();- return Promise.race([- narrationSettled,- new Promise<void>((resolve) => setTimeout(resolve, NARRATION_SETTLE_TIMEOUT_MS)),- ]);+ const pending = narrationSettled;+ if (!pending) return Promise.resolve();+ return new Promise<void>((resolve) => {+ const timer = setTimeout(resolve, NARRATION_SETTLE_TIMEOUT_MS);+ void pending.then(() => {+ clearTimeout(timer);+ resolve();+ });+ });}-function markNarrationPending(): void {+function claimTranscription(guideId: string): void {+ transcribingGuideId = guideId;+ outstandingTranscriptions += 1;+ if (narrationSettled) return;narrationSettled = new Promise<void>((resolve) => {settleNarration = resolve;});}-function markNarrationSettled(): void {+function releaseTranscription(guideId: string): boolean {+ if (transcribingGuideId !== guideId || outstandingTranscriptions === 0) return false;+ outstandingTranscriptions -= 1;+ if (outstandingTranscriptions > 0) return true;+ transcribingGuideId = null;settleNarration?.();settleNarration = null;narrationSettled = null;+ return true;}function requestMicPermission(tabId?: number): void {@@ -147,6 +161,25 @@ async function beginVoiceCapture(microphoneId: string | undefined, tabId: numberawait closeVoiceHost();}+export async function isNarrationLive(): Promise<boolean> {+ if (phase.phase === 'recording') return true;+ if (!supportsVoice() || !(await hasVoiceHost())) return false;+ const status = await getVoiceStatus().catch(() => null);+ return isVoiceStatus(status) && status.recording;+}++export function isNarrationSettling(): boolean {+ return phase.phase === 'transcribing';+}++export function reportNarrationLost(): void {+ report({+ phase: 'error',+ reason: 'stream-ended',+ error: 'Narration could not be restarted after the pause',+ });+}+export function canStartNarrationNow(captureState: string, voicePhase: VoicePhase): boolean {return captureState === CaptureState.RECORDING && voicePhase !== 'recording' && voicePhase !== 'transcribing';}@@ -197,11 +230,11 @@ async function recoverNarration(guideId: string): Promise<void> {}logger.warn('voice: transcribing narration captured before the microphone host went away');- transcribingGuideId = guideId;+ claimTranscription(guideId);report({ phase: 'transcribing' });const steps = await getStepsForGuide(guideId);const result = await narrateRecording(audio, stepMarks(steps), settings);- await applyNarration(guideId, result);+ await applyNarration(guideId, result, true);}export async function flushNarrationForStep(guideId: string, stepId: string, timestamp: number): Promise<void> {@@ -243,30 +276,33 @@ export async function stopVoiceNarration(guideId: string): Promise<void> {const steps = await getStepsForGuide(guideId);const settings = await readTranscriptionSettings();++ claimTranscription(guideId);+ if (phase.phase === 'recording') report({ phase: 'transcribing' });+const response = await stopVoiceCapture(guideId, stepMarks(steps), settings);if (response.ok) {logger.info('voice: transcribing narration', response);- transcribingGuideId = guideId;- markNarrationPending();- if (phase.phase === 'recording') report({ phase: 'transcribing' });return;}logger.warn('voice: no narration to apply', response);- report({ phase: 'error', reason: response.reason, error: response.error });+ if (releaseTranscription(guideId)) report({ phase: 'error', reason: response.reason, error: response.error });await closeVoiceHostIfIdle();} catch (error) {logger.error('voice: narration could not be stopped', error);- report({ phase: 'error', reason: 'unknown', error: String(error) });+ if (releaseTranscription(guideId)) report({ phase: 'error', reason: 'unknown', error: String(error) });await closeVoiceHostIfIdle();}}-export async function applyNarration(guideId: string, result: VoiceResultEvent['result']): Promise<void> {- const final = transcribingGuideId === guideId;+export async function applyNarration(+ guideId: string,+ result: VoiceResultEvent['result'],+ final: boolean,+): Promise<void> {try {- if (final) transcribingGuideId = null;await saveTranscript(guideId, result.transcript).catch((error: unknown) =>logger.warn('voice: the transcript could not be stored', error),);@@ -293,7 +329,7 @@ export async function applyNarration(guideId: string, result: VoiceResultEvent['if (final) report({ phase: 'error', reason: 'unknown', error: String(error) });} finally {if (final) {- markNarrationSettled();+ releaseTranscription(guideId);await closeVoiceHostIfIdle();}}@@ -348,7 +384,7 @@ export function registerVoiceListeners(onMicrophoneGranted?: () => Promise<unknoswitch (event.type) {case VoiceMessage.VOICE_RESULT:- void applyNarration(event.guideId, event.result);+ void applyNarration(event.guideId, event.result, event.final);return undefined;case VoiceMessage.VOICE_HANDOFF:handleVoiceHandoff(event);diff --git a/src/lib/__tests__/voice-host-final.test.ts b/src/lib/__tests__/voice-host-final.test.tsnew file mode 100644index 0000000..72d29fe--- /dev/null+++ b/src/lib/__tests__/voice-host-final.test.ts@@ -0,0 +1,113 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const sendMessage = vi.fn();+const narrateRecording = vi.fn();++vi.mock('../browser-api', () => ({+ getExtensionURL: (path: string) => path,+ onMessage: vi.fn(),+ sendMessage: (...args: unknown[]) => sendMessage(...args),+}));++vi.mock('../logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++const recorderState = {+ recording: false,+ audioEpochMs: 1_700_000_000_000 as number | null,+ sampleRate: 16000,+ sampleCount: 16000,+ durationSeconds: 1,+};++vi.mock('../mic-recorder', () => ({+ MicRecorder: class {+ get recording() {+ return recorderState.recording;+ }+ get audioEpochMs() {+ return recorderState.audioEpochMs;+ }+ get sampleRate() {+ return recorderState.sampleRate;+ }+ get sampleCount() {+ return recorderState.sampleCount;+ }+ get durationSeconds() {+ return recorderState.durationSeconds;+ }+ stop() {+ recorderState.recording = false;+ return {+ pcm: new Int16Array(recorderState.sampleCount),+ sampleRate: recorderState.sampleRate,+ audioEpochMs: recorderState.audioEpochMs,+ durationSeconds: recorderState.durationSeconds,+ };+ }+ snapshot() {+ return this.stop();+ }+ release() {}+ },+}));++vi.mock('../voice-narration', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../voice-narration')>();+ return { ...actual, narrateRecording: (...args: unknown[]) => narrateRecording(...args) };+});++import { createVoiceHost } from '../voice-host';+import { VOICE_BACKGROUND_TARGET, VoiceMessage } from '../voice-messages';++const SETTINGS = { provider: 'openai', apiKey: 'sk-test' };++function deliveredResults(): Array<{ final: boolean }> {+ return sendMessage.mock.calls+ .map(([event]) => event as { type: string; target: string; final: boolean })+ .filter((event) => event.type === VoiceMessage.VOICE_RESULT && event.target === VOICE_BACKGROUND_TARGET);+}++beforeEach(() => {+ sendMessage.mockReset().mockResolvedValue(undefined);+ narrateRecording.mockReset();+ recorderState.recording = true;+ recorderState.audioEpochMs = 1_700_000_000_000;+ recorderState.sampleCount = 160000;+ recorderState.durationSeconds = 10;+});++describe('the final flag on a delivered narration result', () => {+ it('is true when a stop has no steps to attribute to', async () => {+ const host = createVoiceHost();++ await host.handle({+ type: VoiceMessage.VOICE_STOP,+ target: 'voice-offscreen',+ guideId: 'g1',+ steps: [],+ settings: SETTINGS,+ } as never);++ expect(deliveredResults().map((event) => event.final)).toEqual([true]);+ });++ it('is false for a mid-recording flush', async () => {+ narrateRecording.mockResolvedValue({+ descriptions: [{ stepId: 's1', text: 'Open billing' }],+ transcript: { epochMs: 1_700_000_000_000, lines: [{ start: 0, end: 1, text: 'Open billing', stepId: 's1' }] },+ stats: {},+ });+ const host = createVoiceHost();++ await host.handle({+ type: VoiceMessage.VOICE_FLUSH,+ target: 'voice-offscreen',+ guideId: 'g1',+ step: { stepId: 's1', timestamp: 1_700_000_005_000 },+ settings: SETTINGS,+ } as never);++ expect(deliveredResults().map((event) => event.final)).toEqual([false]);+ });+});diff --git a/src/lib/voice-host.ts b/src/lib/voice-host.tsindex 8d52234..57d3f2e 100644--- a/src/lib/voice-host.ts+++ b/src/lib/voice-host.ts@@ -108,13 +108,14 @@ export function createVoiceHost(): VoiceHost {);}- function deliver(guideId: string, result: NarrationResult): void {+ function deliver(guideId: string, result: NarrationResult, final: boolean): void {emit(voiceMessage<VoiceResultEvent>({type: VoiceMessage.VOICE_RESULT,target: VOICE_BACKGROUND_TARGET,guideId,result,+ final,}),);}@@ -158,7 +159,7 @@ export function createVoiceHost(): VoiceHost {const result = await narrateRecording(audio, steps, settings);pending -= 1;retained = null;- deliver(guideId, result);+ deliver(guideId, result, true);}async function handleFlush(request: VoiceFlushRequest): Promise<VoiceFlushResponse> {@@ -181,7 +182,7 @@ export function createVoiceHost(): VoiceHost {try {const result = await narrateRecording(slice, [request.step], request.settings);const attributed = result.descriptions.length > 0;- if (attributed || result.transcript.lines.length > 0) deliver(request.guideId, result);+ if (attributed || result.transcript.lines.length > 0) deliver(request.guideId, result, false);return { ok: true, flushed: attributed };} finally {pending -= 1;@@ -200,7 +201,7 @@ export function createVoiceHost(): VoiceHost {const { audioEpochMs, durationSeconds } = audio;if (request.steps.length === 0) {- deliver(request.guideId, EMPTY_NARRATION);+ deliver(request.guideId, EMPTY_NARRATION, true);return { ok: true, audioEpochMs, durationSeconds };}@@ -211,7 +212,7 @@ export function createVoiceHost(): VoiceHost {const tail = flushedUpToSeconds > 0 ? partialRecording(audio, flushedUpToSeconds, audio.durationSeconds) : audio;if (!tail) {- deliver(request.guideId, EMPTY_NARRATION);+ deliver(request.guideId, EMPTY_NARRATION, true);return { ok: true, audioEpochMs, durationSeconds };}diff --git a/src/lib/voice-messages.ts b/src/lib/voice-messages.tsindex 511f0f8..d1b98e9 100644--- a/src/lib/voice-messages.ts+++ b/src/lib/voice-messages.ts@@ -148,6 +148,7 @@ export interface VoiceResultEvent extends VoiceEnvelope {target: typeof VOICE_BACKGROUND_TARGET;guideId: string;result: NarrationResult;+ final: boolean;}export interface VoiceHandoffEvent extends VoiceEnvelope {