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(guides): store the narration transcript and keep the spoken original

davbio2d8b4625846b
diff --git a/src/core/guides/__tests__/spoken-original.test.ts b/src/core/guides/__tests__/spoken-original.test.ts
new file mode 100644
index 0000000..ec17c1e
--- /dev/null
+++ b/src/core/guides/__tests__/spoken-original.test.ts
@@ -0,0 +1,337 @@
+import 'fake-indexeddb/auto';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.hoisted(() => {
+ globalThis.BroadcastChannel = class BroadcastChannel {
+ name = 'test';
+ postMessage() {}
+ addEventListener() {}
+ removeEventListener() {}
+ close() {}
+ onmessage = null;
+ onmessageerror = null;
+ dispatchEvent() {
+ return true;
+ }
+ } as unknown as typeof BroadcastChannel;
+});
+
+import { db } from '../db';
+import {
+ appendToStepDescription,
+ applyNarrationToSteps,
+ attachTranscriptLine,
+ createSnapshot,
+ deleteTranscripts,
+ getTranscripts,
+ hasTranscript,
+ mergeGuideInto,
+ permanentlyDeleteGuide,
+ restoreNarratedDescription,
+ revertToSnapshot,
+ saveTranscript,
+ updateStepDescription,
+} from '../service';
+import type { Step } from '../types';
+
+const SPOKEN = 'Open the billing tab on the left';
+
+function makeStep(id: string, extras?: Partial<Step>): Step {
+ return {
+ id,
+ guideId: 'g1',
+ index: 0,
+ description: 'Clicked Billing',
+ action: 'click',
+ url: 'https://example.com/settings',
+ timestamp: Date.now(),
+ ...extras,
+ };
+}
+
+beforeEach(async () => {
+ await db.guides.add({
+ id: 'g1',
+ title: 'Test Guide',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ stepIds: ['s1'],
+ starred: false,
+ deletedAt: null,
+ });
+ await db.steps.add(makeStep('s1'));
+});
+
+afterEach(async () => {
+ await db.guides.clear();
+ await db.steps.clear();
+ await db.transcripts.clear();
+ await db.screenshots.clear();
+ await db.snapshots.clear();
+});
+
+describe('the spoken original', () => {
+ it('is kept alongside the description narration wrote', async () => {
+ await applyNarrationToSteps([{ stepId: 's1', description: SPOKEN }]);
+
+ const step = await db.steps.get('s1');
+ expect(step?.description).toBe(SPOKEN);
+ expect(step?.narratedDescription).toBe(SPOKEN);
+ });
+
+ it('survives an edit that replaces the description', async () => {
+ await applyNarrationToSteps([{ stepId: 's1', description: SPOKEN }]);
+ await updateStepDescription('s1', 'Click Billing', 'manual');
+
+ const step = await db.steps.get('s1');
+ expect(step?.description).toBe('Click Billing');
+ expect(step?.descriptionSource).toBe('manual');
+ expect(step?.narratedDescription).toBe(SPOKEN);
+ });
+
+ it('can be put back after an edit, source and all', async () => {
+ await applyNarrationToSteps([{ stepId: 's1', description: SPOKEN }]);
+ await updateStepDescription('s1', 'Click Billing', 'manual');
+
+ expect(await restoreNarratedDescription('s1')).toBe(SPOKEN);
+
+ const step = await db.steps.get('s1');
+ expect(step?.description).toBe(SPOKEN);
+ expect(step?.descriptionSource).toBe('narration');
+ });
+
+ it('has nothing to put back on a step narration never touched', async () => {
+ expect(await restoreNarratedDescription('s1')).toBeNull();
+ expect((await db.steps.get('s1'))?.description).toBe('Clicked Billing');
+ });
+});
+
+describe('appendToStepDescription', () => {
+ it('adds a recovered line to what the step already says', async () => {
+ expect(await appendToStepDescription('s1', 'then confirm the change')).toBe(
+ 'Clicked Billing then confirm the change',
+ );
+ expect((await db.steps.get('s1'))?.descriptionSource).toBe('manual');
+ });
+
+ it('becomes the whole description when the step had none', async () => {
+ await db.steps.update('s1', { description: '' });
+ expect(await appendToStepDescription('s1', 'open the billing tab')).toBe('open the billing tab');
+ });
+
+ it('refuses blank text and a step that is gone', async () => {
+ expect(await appendToStepDescription('s1', ' ')).toBeNull();
+ expect(await appendToStepDescription('missing', 'anything')).toBeNull();
+ });
+});
+
+describe('stored transcripts', () => {
+ const transcript = {
+ epochMs: 1_700_000_000_000,
+ lines: [
+ { start: 1, end: 3, text: SPOKEN, stepId: 's1', rejectReason: null },
+ { start: 4, end: 5, text: 'you', stepId: null, rejectReason: 'solo-filler:you' },
+ ],
+ };
+
+ it('keeps every line, attributed or not', async () => {
+ await saveTranscript('g1', transcript);
+
+ const rows = await getTranscripts('g1');
+ expect(rows).toHaveLength(1);
+ expect(rows[0].lines).toHaveLength(2);
+ expect(await hasTranscript('g1')).toBe(true);
+ });
+
+ it('stores nothing when there was nothing to say', async () => {
+ await saveTranscript('g1', { epochMs: 0, lines: [] });
+ expect(await hasTranscript('g1')).toBe(false);
+ });
+
+ it('keeps each transcribed slice as its own row', async () => {
+ await saveTranscript('g1', transcript);
+ await saveTranscript('g1', { ...transcript, epochMs: transcript.epochMs + 30_000 });
+ expect(await getTranscripts('g1')).toHaveLength(2);
+ });
+
+ it('can be deleted on its own, leaving the guide alone', async () => {
+ await saveTranscript('g1', transcript);
+ await deleteTranscripts('g1');
+
+ expect(await hasTranscript('g1')).toBe(false);
+ expect(await db.steps.get('s1')).toBeDefined();
+ });
+
+ it('goes away with the guide', async () => {
+ await saveTranscript('g1', transcript);
+ await permanentlyDeleteGuide('g1');
+
+ expect(await db.transcripts.count()).toBe(0);
+ });
+});
+
+describe('a transcript whose guide is no longer there', () => {
+ const transcript = {
+ epochMs: 1_700_000_000_000,
+ lines: [{ start: 1, end: 3, text: SPOKEN, stepId: 's1', rejectReason: null }],
+ };
+
+ it('follows its steps when a staged recording is merged into another guide', async () => {
+ await db.guides.add({
+ id: 'target',
+ title: 'Target',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ stepIds: [],
+ starred: false,
+ deletedAt: null,
+ });
+ await saveTranscript('g1', transcript);
+
+ await mergeGuideInto('g1', 'target', 0);
+
+ expect(await hasTranscript('g1')).toBe(false);
+ expect(await hasTranscript('target')).toBe(true);
+ });
+
+ it('is filed against the guide the steps ended up on when it lands after the merge', async () => {
+ await db.guides.add({
+ id: 'target',
+ title: 'Target',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ stepIds: [],
+ starred: false,
+ deletedAt: null,
+ });
+ await mergeGuideInto('g1', 'target', 0);
+
+ await saveTranscript('g1', transcript);
+
+ expect(await hasTranscript('target')).toBe(true);
+ expect((await getTranscripts('target'))[0].guideId).toBe('target');
+ });
+
+ it('still finds the merged guide when nothing in the slice was attributed', async () => {
+ await db.guides.add({
+ id: 'target',
+ title: 'Target',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ stepIds: [],
+ starred: false,
+ deletedAt: null,
+ });
+ await mergeGuideInto('g1', 'target', 0);
+
+ await saveTranscript('g1', {
+ epochMs: 1_700_000_000_000,
+ lines: [{ start: 1, end: 3, text: 'thinking out loud', stepId: null, rejectReason: null }],
+ });
+
+ expect(await hasTranscript('target')).toBe(true);
+ });
+
+ it('is not written at all once the guide and its steps are gone', async () => {
+ await permanentlyDeleteGuide('g1');
+
+ await saveTranscript('g1', transcript);
+
+ expect(await db.transcripts.count()).toBe(0);
+ });
+});
+
+describe('deleting a transcript', () => {
+ const transcript = {
+ epochMs: 1_700_000_000_000,
+ lines: [{ start: 1, end: 3, text: SPOKEN, stepId: 's1', rejectReason: null }],
+ };
+
+ it('takes the spoken words off the steps too, so nothing can put them back', async () => {
+ await applyNarrationToSteps([{ stepId: 's1', description: SPOKEN }]);
+ await saveTranscript('g1', transcript);
+
+ await deleteTranscripts('g1');
+
+ expect((await db.steps.get('s1'))?.narratedDescription).toBeUndefined();
+ expect(await restoreNarratedDescription('s1')).toBeNull();
+ });
+
+ it('takes them out of the snapshots that copied them', async () => {
+ await applyNarrationToSteps([{ stepId: 's1', description: SPOKEN }]);
+ await createSnapshot('g1');
+ await saveTranscript('g1', transcript);
+
+ await deleteTranscripts('g1');
+
+ const snapshots = await db.snapshots.where('guideId').equals('g1').toArray();
+ expect(snapshots.flatMap((s) => s.steps).every((s) => s.narratedDescription === undefined)).toBe(true);
+ });
+});
+
+describe('a line pushed onto a step by hand', () => {
+ const transcript = {
+ epochMs: 1_700_000_000_000,
+ lines: [
+ { start: 1, end: 3, text: SPOKEN, stepId: 's1', rejectReason: null },
+ { start: 4, end: 6, text: 'and then confirm it', stepId: null, rejectReason: null },
+ ],
+ };
+
+ it('goes back to unused when the step is restored to what narration said', async () => {
+ await applyNarrationToSteps([{ stepId: 's1', description: SPOKEN }]);
+ await saveTranscript('g1', transcript);
+ const row = (await getTranscripts('g1'))[0];
+
+ await appendToStepDescription('s1', 'and then confirm it');
+ await attachTranscriptLine(row.id, 1, 's1');
+ expect((await getTranscripts('g1'))[0].lines[1]).toMatchObject({ stepId: 's1', addedByHand: true });
+
+ await restoreNarratedDescription('s1');
+
+ const after = (await getTranscripts('g1'))[0].lines[1];
+ expect(after.stepId).toBeNull();
+ expect(after.addedByHand).toBeUndefined();
+ });
+
+ it('leaves a line narration itself attributed alone', async () => {
+ await applyNarrationToSteps([{ stepId: 's1', description: SPOKEN }]);
+ await saveTranscript('g1', transcript);
+ await updateStepDescription('s1', 'Click Billing', 'manual');
+
+ await restoreNarratedDescription('s1');
+
+ expect((await getTranscripts('g1'))[0].lines[0].stepId).toBe('s1');
+ });
+});
+
+describe('the snapshot hash after the spoken text is stripped', () => {
+ it('is recomputed, so two identical saves still collapse into one version', async () => {
+ await applyNarrationToSteps([{ stepId: 's1', description: SPOKEN }]);
+ const before = await createSnapshot('g1');
+ await saveTranscript('g1', {
+ epochMs: 1_700_000_000_000,
+ lines: [{ start: 1, end: 3, text: SPOKEN, stepId: 's1', rejectReason: null }],
+ });
+
+ await deleteTranscripts('g1');
+ const after = await createSnapshot('g1');
+
+ expect(before).not.toBeNull();
+ expect(after).not.toBeNull();
+ const stored = await db.snapshots.get((before as { id: string }).id);
+ expect(stored?.contentHash).toBe((after as { contentHash: string }).contentHash);
+ });
+});
+
+describe('restoring an older version', () => {
+ it('keeps a spoken original the snapshot was taken too early to hold', async () => {
+ const snapshot = await createSnapshot('g1');
+ expect(snapshot).not.toBeNull();
+
+ await applyNarrationToSteps([{ stepId: 's1', description: SPOKEN }]);
+ await revertToSnapshot((snapshot as { id: string }).id);
+
+ expect((await db.steps.get('s1'))?.narratedDescription).toBe(SPOKEN);
+ });
+});
diff --git a/src/core/guides/__tests__/transcript.test.ts b/src/core/guides/__tests__/transcript.test.ts
new file mode 100644
index 0000000..1e17a23
--- /dev/null
+++ b/src/core/guides/__tests__/transcript.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from 'vitest';
+import { countUnused, formatOffset, mergeTranscripts, nearestStepId, transcriptToText } from '../transcript';
+import type { GuideTranscript } from '../types';
+
+const EPOCH = 1_700_000_000_000;
+
+function row(epochOffsetMs: number, lines: Array<[number, string, string | null]>): GuideTranscript {
+ return {
+ id: `t-${epochOffsetMs}`,
+ guideId: 'g1',
+ epochMs: EPOCH + epochOffsetMs,
+ createdAt: 0,
+ lines: lines.map(([start, text, stepId]) => ({ start, end: start + 1, text, stepId, rejectReason: null })),
+ };
+}
+
+describe('mergeTranscripts', () => {
+ it('orders lines from separate slices by when they were spoken', () => {
+ const lines = mergeTranscripts([
+ row(30_000, [[2, 'and then save', 's3']]),
+ row(0, [
+ [1, 'first open settings', 's1'],
+ [5, 'scroll down a bit', 's2'],
+ ]),
+ ]);
+
+ expect(lines.map((line) => line.text)).toEqual(['first open settings', 'scroll down a bit', 'and then save']);
+ });
+
+ it('measures the offset from the earliest slice, not from each slice', () => {
+ const lines = mergeTranscripts([row(0, [[1, 'first', 's1']]), row(30_000, [[2, 'later', 's2']])]);
+ expect(lines.map((line) => line.offsetSeconds)).toEqual([0, 31]);
+ });
+
+ it('has nothing to merge when no slice was stored', () => {
+ expect(mergeTranscripts([])).toEqual([]);
+ });
+});
+
+describe('nearestStepId', () => {
+ const lines = mergeTranscripts([
+ row(0, [
+ [1, 'thinking out loud', null],
+ [3, 'now I click save', 's2'],
+ [6, 'and now the dialog', 's3'],
+ ]),
+ ]);
+
+ it('looks forward first, because narration comes before the action it describes', () => {
+ expect(nearestStepId(lines, 0)).toBe('s2');
+ });
+
+ it('still looks forward when a step sits on either side of the stray line', () => {
+ const between = mergeTranscripts([
+ row(0, [
+ [1, 'click save', 's1'],
+ [3, 'stray thought', null],
+ [5, 'now the dialog', 's3'],
+ ]),
+ ]);
+ expect(nearestStepId(between, 1)).toBe('s3');
+ });
+
+ it('falls back to the step before when nothing follows', () => {
+ const trailing = mergeTranscripts([
+ row(0, [
+ [1, 'click save', 's1'],
+ [4, 'that is everything', null],
+ ]),
+ ]);
+ expect(nearestStepId(trailing, 1)).toBe('s1');
+ });
+
+ it('has nowhere to put a line when no line was attributed at all', () => {
+ const orphans = mergeTranscripts([row(0, [[1, 'hello?', null]])]);
+ expect(nearestStepId(orphans, 0)).toBeNull();
+ });
+});
+
+describe('countUnused', () => {
+ it('counts only the lines no step took', () => {
+ const lines = mergeTranscripts([
+ row(0, [
+ [1, 'kept', 's1'],
+ [3, 'dropped', null],
+ [5, 'also dropped', null],
+ ]),
+ ]);
+ expect(countUnused(lines)).toBe(2);
+ });
+});
+
+describe('transcriptToText', () => {
+ it('stamps each line with its time and the step that used it', () => {
+ const lines = mergeTranscripts([
+ row(0, [
+ [1, 'open settings', 's1'],
+ [65, 'stray thought', null],
+ ]),
+ ]);
+
+ expect(transcriptToText(lines, new Map([['s1', 4]]))).toBe('0:00 [4] open settings\n1:04 stray thought');
+ });
+});
+
+describe('formatOffset', () => {
+ it('pads seconds and rolls over into minutes', () => {
+ expect(formatOffset(0)).toBe('0:00');
+ expect(formatOffset(9.9)).toBe('0:09');
+ expect(formatOffset(61)).toBe('1:01');
+ expect(formatOffset(-5)).toBe('0:00');
+ });
+});
diff --git a/src/core/guides/service.ts b/src/core/guides/service.ts
index ea06964..56da9f2 100644
--- a/src/core/guides/service.ts
+++ b/src/core/guides/service.ts
@@ -1,10 +1,20 @@
import { i18n } from '#imports';
import type { NarrationUpdate } from '@/core/capture/voice/narration-updates';
+import type { NarrationTranscript } from '@/core/capture/voice/types';
import type { ScreenshotEdits } from '@/core/screenshot/types';
import type { ParsedBundle } from '@/core/transfer/parse';
import { db } from './db';
import { hashPayload } from './snapshot-hash';
-import type { BlockType, CalloutVariant, DescriptionSource, Guide, Screenshot, Snapshot, Step } from './types';
+import type {
+ BlockType,
+ CalloutVariant,
+ DescriptionSource,
+ Guide,
+ GuideTranscript,
+ Screenshot,
+ Snapshot,
+ Step,
+} from './types';
export type GuideChangeEvent = { type: 'starred'; id: string; starred: boolean } | { type: 'mutated' };
@@ -124,6 +134,7 @@ export async function permanentlyDeleteGuide(id: string): Promise<void> {
.anyOf([...stepIds])
.delete();
await db.snapshots.where('guideId').equals(id).delete();
+ await db.transcripts.where('guideId').equals(id).delete();
await db.steps.where('guideId').equals(id).delete();
await db.guides.delete(id);
notifyGuidesChanged({ type: 'mutated' });
@@ -198,7 +209,7 @@ export async function createStep(step: Step): Promise<void> {
}
export async function mergeGuideInto(sourceGuideId: string, targetGuideId: string, atIndex: number): Promise<number> {
- const moved = await db.transaction('rw', db.steps, db.guides, async () => {
+ const moved = await db.transaction('rw', db.steps, db.guides, db.transcripts, async () => {
const incoming = await db.steps.where('guideId').equals(sourceGuideId).sortBy('index');
const target = await db.steps.where('guideId').equals(targetGuideId).sortBy('index');
if (incoming.length > 0) {
@@ -213,6 +224,8 @@ export async function mergeGuideInto(sourceGuideId: string, targetGuideId: strin
updatedAt: Date.now(),
});
}
+ await db.transcripts.where('guideId').equals(sourceGuideId).modify({ guideId: targetGuideId });
+ mergedInto.set(sourceGuideId, targetGuideId);
await db.guides.delete(sourceGuideId);
return incoming.length;
});
@@ -263,12 +276,120 @@ export async function applyNarrationToSteps(updates: readonly NarrationUpdate[])
if (updates.length === 0) return;
await db.transaction('rw', db.steps, async () => {
for (const { stepId, description } of updates) {
- await db.steps.update(stepId, { description, descriptionSource: 'narration', aiPending: false });
+ await db.steps.update(stepId, {
+ description,
+ narratedDescription: description,
+ descriptionSource: 'narration',
+ aiPending: false,
+ });
}
});
notifyGuidesChanged({ type: 'mutated' });
}
+const mergedInto = new Map<string, string>();
+
+async function resolveTranscriptOwner(guideId: string, transcript: NarrationTranscript): Promise<string | null> {
+ if (await db.guides.get(guideId)) return guideId;
+ const spokenFor = transcript.lines.map((line) => line.stepId).filter((id): id is string => id !== null);
+ const steps = await db.steps.bulkGet(spokenFor);
+ const owner = steps.find((step) => step !== undefined)?.guideId ?? mergedInto.get(guideId);
+ return owner && (await db.guides.get(owner)) ? owner : null;
+}
+
+export async function saveTranscript(guideId: string, transcript: NarrationTranscript): Promise<void> {
+ if (transcript.lines.length === 0) return;
+ const owner = await resolveTranscriptOwner(guideId, transcript);
+ if (!owner) return;
+ await db.transcripts.add({
+ id: crypto.randomUUID(),
+ guideId: owner,
+ epochMs: transcript.epochMs,
+ createdAt: Date.now(),
+ lines: transcript.lines,
+ });
+ notifyGuidesChanged({ type: 'mutated' });
+}
+
+export async function getTranscripts(guideId: string): Promise<GuideTranscript[]> {
+ return db.transcripts.where('guideId').equals(guideId).toArray();
+}
+
+export async function hasTranscript(guideId: string): Promise<boolean> {
+ return (await db.transcripts.where('guideId').equals(guideId).count()) > 0;
+}
+
+export async function deleteTranscripts(guideId: string): Promise<void> {
+ await db.transaction('rw', db.transcripts, db.steps, db.snapshots, async () => {
+ await db.transcripts.where('guideId').equals(guideId).delete();
+ await db.steps
+ .where('guideId')
+ .equals(guideId)
+ .modify((step) => {
+ delete step.narratedDescription;
+ });
+ await db.snapshots
+ .where('guideId')
+ .equals(guideId)
+ .modify((snapshot) => {
+ for (const step of snapshot.steps) delete step.narratedDescription;
+ snapshot.contentHash = hashPayload({
+ title: snapshot.title,
+ stepIds: snapshot.stepIds,
+ steps: snapshot.steps,
+ screenshots: snapshot.screenshots,
+ });
+ });
+ });
+ notifyGuidesChanged({ type: 'mutated' });
+}
+
+async function releaseHandAddedLines(guideId: string, stepId: string): Promise<void> {
+ await db.transcripts
+ .where('guideId')
+ .equals(guideId)
+ .modify((row) => {
+ for (const line of row.lines) {
+ if (line.stepId !== stepId || !line.addedByHand) continue;
+ line.stepId = null;
+ delete line.addedByHand;
+ }
+ });
+}
+
+export async function restoreNarratedDescription(stepId: string): Promise<string | null> {
+ const step = await db.steps.get(stepId);
+ const spoken = step?.narratedDescription?.trim();
+ if (!step || !spoken) return null;
+ await db.steps.update(stepId, { description: spoken, descriptionSource: 'narration', aiPending: false });
+ await releaseHandAddedLines(step.guideId, stepId);
+ notifyGuidesChanged({ type: 'mutated' });
+ return spoken;
+}
+
+export async function attachTranscriptLine(rowId: string, lineIndex: number, stepId: string): Promise<void> {
+ await db.transcripts
+ .where('id')
+ .equals(rowId)
+ .modify((row) => {
+ const line = row.lines[lineIndex];
+ if (!line) return;
+ line.stepId = stepId;
+ line.addedByHand = true;
+ });
+}
+
+export async function appendToStepDescription(stepId: string, text: string): Promise<string | null> {
+ const addition = text.trim();
+ if (!addition) return null;
+ const step = await db.steps.get(stepId);
+ if (!step) return null;
+ const description = step.description.trim() ? `${step.description.trim()} ${addition}` : addition;
+ await db.steps.update(stepId, { description, descriptionSource: 'manual', aiPending: false });
+ notifyGuidesChanged({ type: 'mutated' });
+ return description;
+}
+
export async function applyAiDescription(stepId: string, description: string): Promise<void> {
const wrote = await db.transaction('rw', db.steps, async () => {
const step = await db.steps.get(stepId);
@@ -437,7 +558,14 @@ export async function revertToSnapshot(snapshotId: string): Promise<Snapshot | n
const existing = await db.steps.where('guideId').equals(snapshot.guideId).toArray();
const keep = new Set(snapshot.steps.map((s) => s.id));
await db.steps.bulkDelete(existing.filter((s) => !keep.has(s.id)).map((s) => s.id));
- await db.steps.bulkPut(snapshot.steps);
+ const spoken = new Map(existing.map((step) => [step.id, step.narratedDescription]));
+ await db.steps.bulkPut(
+ snapshot.steps.map((step) =>
+ step.narratedDescription === undefined && spoken.get(step.id) !== undefined
+ ? { ...step, narratedDescription: spoken.get(step.id) }
+ : step,
+ ),
+ );
const live = await db.screenshots.bulkGet(snapshot.screenshots.map((r) => r.id));
const merged = snapshot.screenshots
.map((row, i) => (live[i] ? { ...row, blob: live[i]!.blob } : null))
diff --git a/src/core/guides/transcript.ts b/src/core/guides/transcript.ts
new file mode 100644
index 0000000..20fce1f
--- /dev/null
+++ b/src/core/guides/transcript.ts
@@ -0,0 +1,61 @@
+import type { TranscriptLine } from '@/core/capture/voice/types';
+import type { GuideTranscript, Step } from './types';
+
+const MS_PER_S = 1000;
+
+export interface TimelineLine extends TranscriptLine {
+ atMs: number;
+ offsetSeconds: number;
+ rowId: string;
+ lineIndex: number;
+}
+
+export function mergeTranscripts(rows: readonly GuideTranscript[]): TimelineLine[] {
+ const lines = rows.flatMap((row) =>
+ row.lines.map((line, lineIndex) => ({
+ ...line,
+ atMs: row.epochMs + line.start * MS_PER_S,
+ rowId: row.id,
+ lineIndex,
+ })),
+ );
+ lines.sort((a, b) => a.atMs - b.atMs);
+ const first = lines[0]?.atMs ?? 0;
+ return lines.map((line) => ({ ...line, offsetSeconds: (line.atMs - first) / MS_PER_S }));
+}
+
+export function withLiveSteps(lines: readonly TimelineLine[], steps: readonly Step[]): TimelineLine[] {
+ const live = new Set(steps.map((step) => step.id));
+ return lines.map((line) => (line.stepId && live.has(line.stepId) ? line : { ...line, stepId: null }));
+}
+
+export function nearestStepId(lines: readonly TimelineLine[], index: number): string | null {
+ for (let i = index + 1; i < lines.length; i++) {
+ if (lines[i].stepId) return lines[i].stepId;
+ }
+ for (let i = index - 1; i >= 0; i--) {
+ if (lines[i].stepId) return lines[i].stepId;
+ }
+ return null;
+}
+
+export function formatOffset(seconds: number): string {
+ const total = Math.max(0, Math.floor(seconds));
+ const mins = Math.floor(total / 60);
+ const secs = total % 60;
+ return `${mins}:${String(secs).padStart(2, '0')}`;
+}
+
+export function transcriptToText(lines: readonly TimelineLine[], stepNumbers?: ReadonlyMap<string, number>): string {
+ return lines
+ .map((line) => {
+ const number = line.stepId ? stepNumbers?.get(line.stepId) : undefined;
+ const tag = number ? ` [${number}]` : '';
+ return `${formatOffset(line.offsetSeconds)}${tag} ${line.text}`;
+ })
+ .join('\n');
+}
+
+export function countUnused(lines: readonly TimelineLine[]): number {
+ return lines.filter((line) => !line.stepId).length;
+}
diff --git a/src/entrypoints/background/__tests__/narration-transcript.test.ts b/src/entrypoints/background/__tests__/narration-transcript.test.ts
new file mode 100644
index 0000000..1771998
--- /dev/null
+++ b/src/entrypoints/background/__tests__/narration-transcript.test.ts
@@ -0,0 +1,77 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const saveTranscript = vi.fn();
+const applyNarrationToSteps = vi.fn();
+const findExistingStepIds = vi.fn();
+
+vi.mock('@/core/guides/service', () => ({
+ saveTranscript: (...args: unknown[]) => saveTranscript(...args),
+ applyNarrationToSteps: (...args: unknown[]) => applyNarrationToSteps(...args),
+ findExistingStepIds: (...args: unknown[]) => findExistingStepIds(...args),
+ getStepsForGuide: vi.fn(),
+}));
+
+vi.mock('../deferred-descriptions', () => ({ discardDeferred: vi.fn() }));
+vi.mock('../describe-unnarrated', () => ({ describeStepNow: vi.fn(), describeUnnarratedSteps: vi.fn() }));
+
+import { applyNarration, takeNarrated } from '../voice';
+
+const transcript = {
+ epochMs: 1_700_000_000_000,
+ lines: [
+ { start: 1, end: 3, text: 'Open the billing tab', stepId: 's1', rejectReason: null },
+ { start: 4, end: 5, text: 'you', stepId: null, rejectReason: 'solo-filler:you' },
+ ],
+};
+
+const stats = {
+ batches: 1,
+ failedBatches: 0,
+ droppedBatches: 0,
+ forcedSplits: 0,
+ verbatimSegments: 1,
+ splitSegments: 0,
+ rejectedSegments: 1,
+};
+
+beforeEach(() => {
+ saveTranscript.mockReset().mockResolvedValue(undefined);
+ applyNarrationToSteps.mockReset().mockResolvedValue(undefined);
+ findExistingStepIds.mockReset().mockResolvedValue(['s1']);
+ takeNarrated('g1');
+});
+
+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 });
+
+ expect(saveTranscript).toHaveBeenCalledWith('g1', transcript);
+ });
+
+ 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 });
+
+ expect(saveTranscript).toHaveBeenCalledWith('g1', orphaned);
+ expect(applyNarrationToSteps).toHaveBeenCalledWith([]);
+ });
+
+ 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 });
+
+ expect(saveTranscript).toHaveBeenCalledTimes(2);
+ expect(saveTranscript.mock.calls.map((call) => call[1].epochMs)).toEqual([transcript.epochMs, second.epochMs]);
+ });
+
+ 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 });
+
+ expect(applyNarrationToSteps).toHaveBeenCalledWith([{ stepId: 's1', description: 'Open the billing tab' }]);
+ });
+});
diff --git a/src/entrypoints/background/voice.ts b/src/entrypoints/background/voice.ts
index 867d7ee..8412932 100644
--- a/src/entrypoints/background/voice.ts
+++ b/src/entrypoints/background/voice.ts
@@ -1,7 +1,7 @@
import { CaptureState } from '@/core/capture/machine';
import { hasVoiceApiKey, VOICE_KEY_SETTINGS } from '@/core/capture/voice/api-key';
import { narrationUpdates } from '@/core/capture/voice/narration-updates';
-import { applyNarrationToSteps, findExistingStepIds, getStepsForGuide } from '@/core/guides/service';
+import { applyNarrationToSteps, findExistingStepIds, getStepsForGuide, saveTranscript } from '@/core/guides/service';
import { localStorage, onMessage as onRuntimeMessage } from '@/lib/browser-api';
import { logger } from '@/lib/logger';
import {
@@ -263,10 +263,13 @@ export async function stopVoiceNarration(guideId: string): Promise<void> {
}
}
-async function applyNarration(guideId: string, result: VoiceResultEvent['result']): Promise<void> {
+export async function applyNarration(guideId: string, result: VoiceResultEvent['result']): Promise<void> {
const final = transcribingGuideId === guideId;
try {
if (final) transcribingGuideId = null;
+ await saveTranscript(guideId, result.transcript).catch((error: unknown) =>
+ logger.warn('voice: the transcript could not be stored', error),
+ );
const narrated = result.descriptions.map((entry) => entry.stepId);
const surviving = await findExistingStepIds(narrated);
const updates = narrationUpdates(result, surviving);