π¬ 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
test(capture): cover the paused state and the blur mask contract
davbio7bcad214ff81
diff --git a/src/core/blur/__tests__/manager.test.ts b/src/core/blur/__tests__/manager.test.tsnew file mode 100644index 0000000..5bbeed3--- /dev/null+++ b/src/core/blur/__tests__/manager.test.ts@@ -0,0 +1,149 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from 'vitest';++let resolvePresets: ((v: unknown) => void) | null = null;++vi.mock('#imports', () => ({+ browser: {+ storage: {+ local: {+ get: () =>+ new Promise((resolve) => {+ resolvePresets = resolve;+ }),+ set: vi.fn(),+ },+ },+ },+}));++vi.mock('@/lib/messaging', () => ({ sendMessage: vi.fn().mockResolvedValue(undefined) }));++import { BlurManager } from '../manager';++/** The panel mounts a host on <html>, so its presence is the visible overlay. */+function overlayHosts(): number {+ return document.documentElement.querySelectorAll(':scope > [data-mimik-ignore]').length;+}++/** Drains the microtask queue regardless of how deep start()'s chain gets. */+async function settle() {+ resolvePresets?.({ blurPresets: { email: true } });+ await new Promise((resolve) => setTimeout(resolve, 0));+}++afterEach(() => {+ for (const el of document.documentElement.querySelectorAll(':scope > [data-mimik-ignore]')) {+ el.remove();+ }+ document.body.innerHTML = '';+ resolvePresets = null;+});++describe('BlurManager start/stop races', () => {+ it('mounts the overlay once the presets load', async () => {+ const manager = new BlurManager();+ manager.start();+ await settle();++ expect(overlayHosts()).toBe(1);+ });++ // Discarding a recording right after entering blur mode used to leave the+ // panel on the page forever: teardown ran before the panel existed, then the+ // pending start() mounted it with active already false.+ it('does not mount the overlay when stop lands while the presets load', async () => {+ const manager = new BlurManager();+ manager.start();+ manager.stop();+ await settle();++ expect(overlayHosts()).toBe(0);+ });++ it('does not mount the overlay when dismiss lands while the presets load', async () => {+ const manager = new BlurManager();+ manager.start();+ manager.dismiss();+ await settle();++ expect(overlayHosts()).toBe(0);+ });++ it('can be started again after a stop that interrupted a start', async () => {+ const manager = new BlurManager();+ manager.start();+ manager.stop();+ await settle();++ manager.start();+ await settle();++ expect(overlayHosts()).toBe(1);+ });++ // The whole point of having both: Done keeps the masks so later screenshots+ // stay redacted, and only the end of a recording takes them away. Mutating+ // dismiss() into stop() used to pass the entire suite.+ it('dismiss closes the overlay but leaves the masks and styles in place', async () => {+ document.body.innerHTML = '<p>[email protected]</p>';+ const manager = new BlurManager();+ manager.start();+ await settle();+ expect(document.querySelectorAll('[data-mimik-blur]')).toHaveLength(1);++ manager.dismiss();++ expect(overlayHosts()).toBe(0);+ expect(document.querySelectorAll('[data-mimik-blur]')).toHaveLength(1);+ expect(document.getElementById('mimik-blur-style')).not.toBeNull();+ });++ it('stop removes the masks and the styles as well as the overlay', async () => {+ document.body.innerHTML = '<p>[email protected]</p>';+ const manager = new BlurManager();+ manager.start();+ await settle();+ expect(document.querySelectorAll('[data-mimik-blur]')).toHaveLength(1);++ manager.stop();++ expect(overlayHosts()).toBe(0);+ expect(document.querySelectorAll('[data-mimik-blur]')).toHaveLength(0);+ expect(document.getElementById('mimik-blur-style')).toBeNull();+ });++ // The CLEAR_BLUR path: Done already tore the panel down, so a stop() gated on+ // `active` would leave the page blurred until the user reloaded it.+ it('stop still clears the masks after a dismiss has already run', async () => {+ document.body.innerHTML = '<p>[email protected]</p>';+ const manager = new BlurManager();+ manager.start();+ await settle();+ manager.dismiss();++ manager.stop();++ expect(document.querySelectorAll('[data-mimik-blur]')).toHaveLength(0);+ expect(document.getElementById('mimik-blur-style')).toBeNull();+ });++ it('does not mount two panels when a dismiss and a restart share one await', async () => {+ const manager = new BlurManager();+ manager.start();+ manager.dismiss();+ manager.start();+ await settle();++ expect(overlayHosts()).toBe(1);+ });++ it('removes the overlay on a stop after a completed start', async () => {+ const manager = new BlurManager();+ manager.start();+ await settle();+ manager.stop();++ expect(overlayHosts()).toBe(0);+ });+});diff --git a/src/core/blur/__tests__/restore.test.ts b/src/core/blur/__tests__/restore.test.tsnew file mode 100644index 0000000..2ceeab9--- /dev/null+++ b/src/core/blur/__tests__/restore.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';+import { CaptureState } from '@/core/capture/machine';+import type { GetStateResponse } from '@/lib/messaging';+import { shouldReopenBlur } from '../restore';++const state = (over: Partial<GetStateResponse> = {}): GetStateResponse => ({+ state: CaptureState.PAUSED,+ stepCount: 1,+ currentGuideId: 'guide-1',+ pauseReason: 'blur',+ ...over,+});++describe('shouldReopenBlur', () => {+ it('re-opens in the top frame of a recording paused for blur', () => {+ expect(shouldReopenBlur(state(), true)).toBe(true);+ });++ // The overlay is a top-frame singleton; without this every iframe on the+ // page would mount its own panel.+ it('never re-opens in a subframe', () => {+ expect(shouldReopenBlur(state(), false)).toBe(false);+ });++ it('does not re-open for a manual pause, which has no overlay', () => {+ expect(shouldReopenBlur(state({ pauseReason: 'manual' }), true)).toBe(false);+ });++ it('does not re-open over a live recording', () => {+ expect(shouldReopenBlur(state({ state: CaptureState.RECORDING, pauseReason: null }), true)).toBe(false);+ });++ it('does not re-open when nothing is being recorded', () => {+ expect(shouldReopenBlur(state({ state: CaptureState.IDLE, currentGuideId: null, pauseReason: null }), true)).toBe(+ false,+ );+ });++ // A snapshot persisted before PAUSED existed restores with no reason at all.+ it('does not re-open when the reason is missing', () => {+ expect(shouldReopenBlur(state({ pauseReason: null }), true)).toBe(false);+ });+});diff --git a/src/core/capture/__tests__/machine.test.ts b/src/core/capture/__tests__/machine.test.tsindex a024c6c..3058311 100644--- a/src/core/capture/__tests__/machine.test.ts+++ b/src/core/capture/__tests__/machine.test.ts@@ -116,4 +116,102 @@ describe('captureMachine', () => {expect(firstId).not.toBe(secondId);});++ it('transitions RECORDING β PAUSED on PAUSE_CAPTURE and records the reason', () => {+ const actor = startActor();+ actor.send({ type: 'START_RECORDING', url: 'https://example.com' });+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'blur' });++ const snap = actor.getSnapshot();+ expect(snap.value).toBe(CaptureState.PAUSED);+ expect(snap.context.pauseReason).toBe('blur');+ expect(snap.context.currentGuideId).toBeTypeOf('string');+ });++ it('transitions PAUSED β RECORDING on RESUME_CAPTURE and keeps the guide', () => {+ const actor = startActor();+ actor.send({ type: 'START_RECORDING', url: 'https://example.com' });+ const guideId = actor.getSnapshot().context.currentGuideId;+ actor.send({ type: 'USER_ACTION' });+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'manual' });+ actor.send({ type: 'RESUME_CAPTURE' });++ const snap = actor.getSnapshot();+ expect(snap.value).toBe(CaptureState.RECORDING);+ expect(snap.context.pauseReason).toBeNull();+ expect(snap.context.currentGuideId).toBe(guideId);+ expect(snap.context.stepCount).toBe(1);+ });++ it('ignores USER_ACTION while PAUSED', () => {+ const actor = startActor();+ actor.send({ type: 'START_RECORDING', url: 'https://example.com' });+ actor.send({ type: 'USER_ACTION' });+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'blur' });++ actor.send({ type: 'USER_ACTION' });+ actor.send({ type: 'USER_ACTION' });++ expect(actor.getSnapshot().context.stepCount).toBe(1);+ expect(actor.getSnapshot().value).toBe(CaptureState.PAUSED);+ });++ it('transitions PAUSED β IDLE on STOP_RECORDING and resets context', () => {+ const actor = startActor();+ actor.send({ type: 'START_RECORDING', url: 'https://example.com' });+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'blur' });+ actor.send({ type: 'STOP_RECORDING' });++ const snap = actor.getSnapshot();+ expect(snap.value).toBe(CaptureState.IDLE);+ expect(snap.context.currentGuideId).toBeNull();+ expect(snap.context.pauseReason).toBeNull();+ expect(snap.context.currentUrl).toBe('');+ });++ it('tracks URL_CHANGED while PAUSED so navigation is not lost', () => {+ const actor = startActor();+ actor.send({ type: 'START_RECORDING', url: 'https://example.com/a' });+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'blur' });+ actor.send({ type: 'URL_CHANGED', url: 'https://example.com/b' });++ expect(actor.getSnapshot().context.currentUrl).toBe('https://example.com/b');+ expect(actor.getSnapshot().value).toBe(CaptureState.PAUSED);+ });++ it('ignores PAUSE_CAPTURE in IDLE', () => {+ const actor = startActor();+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'manual' });++ expect(actor.getSnapshot().value).toBe(CaptureState.IDLE);+ expect(actor.getSnapshot().context.pauseReason).toBeNull();+ });++ it('ignores START_RECORDING while PAUSED', () => {+ const actor = startActor();+ actor.send({ type: 'START_RECORDING', url: 'https://first.com' });+ const guideId = actor.getSnapshot().context.currentGuideId;+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'blur' });++ actor.send({ type: 'START_RECORDING', url: 'https://second.com' });++ const snap = actor.getSnapshot();+ expect(snap.value).toBe(CaptureState.PAUSED);+ expect(snap.context.currentGuideId).toBe(guideId);+ });++ it('survives a persisted snapshot round trip while PAUSED', () => {+ const actor = startActor();+ actor.send({ type: 'START_RECORDING', url: 'https://example.com' });+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'blur' });+ const guideId = actor.getSnapshot().context.currentGuideId;++ const restored = createActor(captureMachine, { snapshot: actor.getPersistedSnapshot() });+ restored.start();++ const snap = restored.getSnapshot();+ expect(snap.value).toBe(CaptureState.PAUSED);+ expect(snap.context.pauseReason).toBe('blur');+ expect(snap.context.currentGuideId).toBe(guideId);+ });});diff --git a/src/core/capture/__tests__/session-sync.test.ts b/src/core/capture/__tests__/session-sync.test.tsnew file mode 100644index 0000000..02d3277--- /dev/null+++ b/src/core/capture/__tests__/session-sync.test.ts@@ -0,0 +1,77 @@+// @vitest-environment jsdom+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { GetStateResponse } from '@/lib/messaging';+import { CaptureState } from '../machine';++const sendMessage = vi.fn();+const startCapture = vi.fn((_guideId: string, _isTopFrame: boolean) => ({ stop: vi.fn() }));++vi.mock('@/lib/messaging', () => ({ sendMessage: (...args: unknown[]) => sendMessage(...args) }));+vi.mock('../events/handlers', () => ({+ startCapture: (guideId: string, isTopFrame: boolean) => startCapture(guideId, isTopFrame),+}));+vi.mock('@/lib/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++async function bootFrame(state: GetStateResponse, onSynced?: (s: GetStateResponse) => void) {+ sendMessage.mockResolvedValue(state);+ const { CaptureSession } = await import('../session');+ const session = new CaptureSession(onSynced);+ await vi.waitFor(() => expect(sendMessage).toHaveBeenCalled());+ await Promise.resolve();+ return session;+}++const recording: GetStateResponse = {+ state: CaptureState.RECORDING,+ stepCount: 2,+ currentGuideId: 'guide-1',+ pauseReason: null,+};++const pausedForBlur: GetStateResponse = {+ state: CaptureState.PAUSED,+ stepCount: 2,+ currentGuideId: 'guide-1',+ pauseReason: 'blur',+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe('CaptureSession boot sync', () => {+ it('starts capturing when the background is RECORDING', async () => {+ const session = await bootFrame(recording);++ expect(startCapture).toHaveBeenCalledWith('guide-1', true);+ expect(session.isActive).toBe(true);+ });++ // The bug in issue 58: a frame that loads during blur mode used to hear+ // RECORDING and start capturing behind a "capture paused" label.+ it('does not start capturing when the background is PAUSED', async () => {+ const session = await bootFrame(pausedForBlur);++ expect(startCapture).not.toHaveBeenCalled();+ expect(session.isActive).toBe(false);+ });++ it('hands the paused state to the caller so the blur overlay can re-open', async () => {+ const onSynced = vi.fn();+ await bootFrame(pausedForBlur, onSynced);++ expect(onSynced).toHaveBeenCalledWith(pausedForBlur);+ });++ it('stays idle when the background is IDLE', async () => {+ const session = await bootFrame({+ state: CaptureState.IDLE,+ stepCount: 0,+ currentGuideId: null,+ pauseReason: null,+ });++ expect(startCapture).not.toHaveBeenCalled();+ expect(session.isActive).toBe(false);+ });+});diff --git a/src/entrypoints/background/__tests__/navigation.test.ts b/src/entrypoints/background/__tests__/navigation.test.tsnew file mode 100644index 0000000..f7644b3--- /dev/null+++ b/src/entrypoints/background/__tests__/navigation.test.ts@@ -0,0 +1,117 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createActor } from 'xstate';+import { captureMachine } from '@/core/capture/machine';++let actor: ReturnType<typeof createActor<typeof captureMachine>>;++const { listeners, capture } = vi.hoisted(() => {+ const map = new Map<string, (...args: unknown[]) => unknown>();+ return {+ listeners: map,+ capture: (name: string) => (fn: (...args: unknown[]) => unknown) => map.set(name, fn),+ };+});++const injectContentScript = vi.fn();+const sendMessageToTab = vi.fn();++vi.mock('@/lib/browser-api', () => ({+ onNavigationCompleted: capture('navigated'),+ onHistoryStateUpdated: capture('pushState'),+ onTabActivated: capture('tabActivated'),+ onTabUpdated: capture('tabUpdated'),+ getTab: (id: number) => Promise.resolve({ id, url: 'https://app.test' }),+ sendMessageToTab: (...args: unknown[]) => sendMessageToTab(...args),+}));++vi.mock('../actor', () => ({ getActor: () => actor, waitUntilReady: () => Promise.resolve() }));+vi.mock('../tab-manager', () => ({+ injectContentScript: (id: number) => injectContentScript(id),+ isInjectableTab: () => true,+}));+vi.mock('@/lib/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++import { registerNavigationListeners } from '../navigation';++beforeEach(() => {+ vi.clearAllMocks();+ listeners.clear();+ actor = createActor(captureMachine);+ actor.start();+ actor.send({ type: 'START_RECORDING', url: 'https://app.test/a' });+ registerNavigationListeners();+});++function url() {+ return actor.getSnapshot().context.currentUrl;+}++describe('URL tracking', () => {+ it('follows a navigation while recording', async () => {+ await listeners.get('navigated')?.({ frameId: 0, url: 'https://app.test/b' });+ expect(url()).toBe('https://app.test/b');+ });++ // A paused recording is still a recording. Without this the first step after+ // the resume is stamped with the page the user was on before pausing, which+ // Guide Me then replays to.+ it('follows a navigation while paused', async () => {+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'blur' });++ await listeners.get('navigated')?.({ frameId: 0, url: 'https://app.test/b' });++ expect(url()).toBe('https://app.test/b');+ });++ it('follows an SPA route change while paused', async () => {+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'manual' });++ await listeners.get('pushState')?.({ frameId: 0, url: 'https://app.test/c' });++ expect(url()).toBe('https://app.test/c');+ });++ it('ignores a subframe navigation', async () => {+ await listeners.get('navigated')?.({ frameId: 3, url: 'https://ads.test' });+ expect(url()).toBe('https://app.test/a');+ });++ it('ignores navigation once the recording has ended', async () => {+ actor.send({ type: 'STOP_RECORDING' });++ await listeners.get('navigated')?.({ frameId: 0, url: 'https://app.test/b' });++ expect(url()).toBe('');+ });+});++describe('content script injection', () => {+ // A tab activated or loaded mid-pause would otherwise have no content script+ // to answer the resume broadcast, so its clicks are never captured.+ it('injects into a tab activated while paused', async () => {+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'manual' });+ sendMessageToTab.mockRejectedValue(new Error('no receiving end'));++ await listeners.get('tabActivated')?.({ tabId: 4 });++ expect(injectContentScript).toHaveBeenCalledWith(4);+ });++ it('injects into a tab that finishes loading while paused', async () => {+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'blur' });+ sendMessageToTab.mockRejectedValue(new Error('no receiving end'));++ await listeners.get('tabUpdated')?.(5, { status: 'complete' }, { id: 5, url: 'https://app.test' });++ expect(injectContentScript).toHaveBeenCalledWith(5);+ });++ it('does not inject once the recording has ended', async () => {+ actor.send({ type: 'STOP_RECORDING' });+ sendMessageToTab.mockRejectedValue(new Error('no receiving end'));++ await listeners.get('tabActivated')?.({ tabId: 4 });++ expect(injectContentScript).not.toHaveBeenCalled();+ });+});diff --git a/src/entrypoints/background/__tests__/pause.test.ts b/src/entrypoints/background/__tests__/pause.test.tsnew file mode 100644index 0000000..1f150a0--- /dev/null+++ b/src/entrypoints/background/__tests__/pause.test.ts@@ -0,0 +1,210 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createActor } from 'xstate';+import { CaptureState, captureMachine } from '@/core/capture/machine';++let actor: ReturnType<typeof createActor<typeof captureMachine>>;+let voicePhase = 'idle';+let activeTab: { id?: number; url?: string } | undefined;++/** Ordering matters more than call counts here, so record a sequence. */+const { calls, record } = vi.hoisted(() => {+ const seq: string[] = [];+ return {+ calls: seq,+ record: (name: string) => () => {+ seq.push(name);+ return Promise.resolve();+ },+ };+});++vi.mock('../actor', () => ({ getActor: () => actor }));++vi.mock('../tab-manager', () => ({+ broadcastDismissBlur: record('dismissBlur'),+ broadcastClearBlur: record('clearBlur'),+ broadcastStopCaptureAndFlush: record('flush'),+ broadcastStartCapture: record('startCapture'),+ injectContentScript: record('inject'),+ isInjectableTab: (tab: { url?: string }) => !!tab.url?.startsWith('https://'),+}));++vi.mock('../voice', () => ({+ getVoiceUpdate: () => ({ type: 'VOICE_UPDATE', phase: voicePhase }),+ stopVoiceNarration: record('stopNarration'),+}));++vi.mock('@/lib/browser-api', () => ({ getActiveTab: () => Promise.resolve(activeTab) }));++import { pauseCapture, resumeCapture, resumeFromPause } from '../pause';++beforeEach(() => {+ calls.length = 0;+ voicePhase = 'idle';+ activeTab = { id: 7, url: 'https://app.test' };+ actor = createActor(captureMachine);+ actor.start();+ actor.send({ type: 'START_RECORDING', url: 'https://app.test' });+});++describe('pauseCapture', () => {+ it('pauses the machine with its reason and flushes the frames', async () => {+ await expect(pauseCapture('manual')).resolves.toBe(true);++ expect(actor.getSnapshot().value).toBe(CaptureState.PAUSED);+ expect(actor.getSnapshot().context.pauseReason).toBe('manual');+ expect(calls).toContain('flush');+ });++ it('refuses when nothing is recording, without touching the frames', async () => {+ actor.send({ type: 'STOP_RECORDING' });++ await expect(pauseCapture('manual')).resolves.toBe(false);+ expect(calls).toEqual([]);+ });++ it('refuses a second pause', async () => {+ await pauseCapture('manual');+ calls.length = 0;++ await expect(pauseCapture('blur')).resolves.toBe(false);+ expect(actor.getSnapshot().context.pauseReason).toBe('manual');+ expect(calls).toEqual([]);+ });++ // Speech during a pause would otherwise be transcribed and attributed to the+ // step captured after the resume.+ it('stops narration when it was live', async () => {+ voicePhase = 'recording';++ await pauseCapture('blur');++ expect(calls).toContain('stopNarration');+ });++ it('leaves narration alone when it was not running', async () => {+ await pauseCapture('manual');++ expect(calls).not.toContain('stopNarration');+ });++ // The flush is what lets a typing session's final screenshot land, so it must+ // finish before the caller opens the blur overlay over the page.+ it('flushes before returning', async () => {+ await pauseCapture('blur');++ expect(calls).toContain('flush');+ expect(calls.indexOf('flush')).toBeGreaterThanOrEqual(0);+ });+});++describe('resumeCapture', () => {+ it('returns to RECORDING and clears the reason', async () => {+ await pauseCapture('manual');++ await expect(resumeCapture()).resolves.toBe(true);++ expect(actor.getSnapshot().value).toBe(CaptureState.RECORDING);+ expect(actor.getSnapshot().context.pauseReason).toBeNull();+ });++ it('refuses when the recording is not paused', async () => {+ await expect(resumeCapture()).resolves.toBe(false);+ expect(calls).toEqual([]);+ });++ it('keeps the same guide, so steps continue in one recording', async () => {+ const guideId = actor.getSnapshot().context.currentGuideId;+ await pauseCapture('manual');++ await resumeCapture();++ expect(actor.getSnapshot().context.currentGuideId).toBe(guideId);+ });++ // A tab opened during the pause was skipped by the navigation listeners, so+ // it has no content script to answer START_CAPTURE.+ it('injects the active tab before restarting capture', async () => {+ await pauseCapture('manual');+ calls.length = 0;++ await resumeCapture();++ expect(calls).toEqual(['inject', 'startCapture']);+ });++ it('skips injection on a tab that cannot take a content script', async () => {+ await pauseCapture('manual');+ activeTab = { id: 9, url: 'chrome://extensions' };+ calls.length = 0;++ await resumeCapture();++ expect(calls).toEqual(['startCapture']);+ });++ it('restarts narration only when the pause stopped it', async () => {+ voicePhase = 'recording';+ await pauseCapture('manual');+ const onResume = vi.fn();++ await resumeCapture(onResume);++ expect(onResume).toHaveBeenCalledOnce();+ });++ it('does not restart narration the user never had on', async () => {+ await pauseCapture('manual');+ const onResume = vi.fn();++ await resumeCapture(onResume);++ expect(onResume).not.toHaveBeenCalled();+ });++ it('does not restart narration twice across two pause cycles', async () => {+ voicePhase = 'recording';+ await pauseCapture('manual');+ const first = vi.fn();+ await resumeCapture(first);+ expect(first).toHaveBeenCalledOnce();++ voicePhase = 'idle';+ await pauseCapture('manual');+ const second = vi.fn();+ await resumeCapture(second);++ expect(second).not.toHaveBeenCalled();+ });+});++describe('resumeFromPause', () => {+ // Clearing here instead of dismissing would wipe the masks the user just+ // picked, leaving every screenshot after the resume unredacted.+ it('dismisses the overlay and never clears the masks', async () => {+ await pauseCapture('blur');+ calls.length = 0;++ await expect(resumeFromPause()).resolves.toBe(true);++ expect(calls).toContain('dismissBlur');+ expect(calls).not.toContain('clearBlur');+ });++ it('dismisses before unpausing, so no frame captures with the panel up', async () => {+ await pauseCapture('manual');+ calls.length = 0;++ await resumeFromPause();++ expect(calls.indexOf('dismissBlur')).toBeLessThan(calls.indexOf('startCapture'));+ });++ it('still dismisses when there is nothing to resume', async () => {+ calls.length = 0;++ await expect(resumeFromPause()).resolves.toBe(false);++ expect(calls).toEqual(['dismissBlur']);+ });+});diff --git a/src/entrypoints/background/__tests__/paused-steps.test.ts b/src/entrypoints/background/__tests__/paused-steps.test.tsnew file mode 100644index 0000000..5b50cc9--- /dev/null+++ b/src/entrypoints/background/__tests__/paused-steps.test.ts@@ -0,0 +1,104 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { CaptureState } from '@/core/capture/machine';+import type { ElementMeta } from '@/core/guides/types';++let state: string = CaptureState.RECORDING;++const send = vi.fn();+const updateStepDescription = vi.fn();+const stepsUpdate = vi.fn();+const captureVisibleTab = vi.fn();++vi.mock('../actor', () => ({+ getActor: () => ({+ getSnapshot: () => ({ value: state, context: { stepCount: 0, currentGuideId: 'guide-1', currentUrl: '/' } }),+ send,+ }),+}));++vi.mock('@/core/guides/service', () => ({+ addStepToGuide: vi.fn(),+ clearStepAiPending: vi.fn(),+ createStep: vi.fn(),+ saveScreenshot: vi.fn(),+ updateStepDescription: (...args: unknown[]) => updateStepDescription(...args),+}));++vi.mock('@/core/guides/db', () => ({+ db: { steps: { update: (...args: unknown[]) => stepsUpdate(...args), get: vi.fn() } },+}));++vi.mock('@/lib/browser-api', () => ({+ captureVisibleTab: (...args: unknown[]) => captureVisibleTab(...args),+ localStorage: { get: vi.fn().mockResolvedValue({}) },+}));++vi.mock('@/lib/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));+vi.mock('../voice', () => ({ getVoiceUpdate: () => ({ phase: 'idle' }), flushNarrationForStep: vi.fn() }));+vi.mock('../ai-description', () => ({ generateAiDescription: vi.fn() }));+vi.mock('../description-queue', () => ({ queueDescription: vi.fn() }));+vi.mock('../deferred-descriptions', () => ({ deferDescription: vi.fn(), shouldQueueAiDescription: () => false }));+vi.mock('@/core/capture/ai/keys', () => ({ AI_KEY_SETTINGS: [], resolveAiKey: () => ({ apiKey: undefined }) }));++const meta = { rect: { x: 0, y: 0, width: 10, height: 10 }, devicePixelRatio: 1 } as ElementMeta;++beforeEach(() => {+ vi.clearAllMocks();+ state = CaptureState.RECORDING;+});++describe('step writes while PAUSED', () => {+ it('ignores a captureStep', async () => {+ const { handleCaptureStep } = await import('../step-pipeline');+ state = CaptureState.PAUSED;++ const res = await handleCaptureStep({ guideId: 'guide-1', action: 'click', elementMeta: meta });++ expect(res).toEqual({ ignored: true });+ expect(send).not.toHaveBeenCalled();+ expect(captureVisibleTab).not.toHaveBeenCalled();+ });++ // A typing session that began before the pause must not land a keystroke+ // afterwards, which is the one write that used to bypass the state check.+ it('ignores an input step update', async () => {+ const { handleUpdateInputStep } = await import('../step-pipeline');+ state = CaptureState.PAUSED;++ await handleUpdateInputStep('step-1', 'Type secret');++ expect(updateStepDescription).not.toHaveBeenCalled();+ });++ // A finalize is the opposite case: it only completes a step the user finished+ // *before* pausing, so dropping it would leave that step holding the+ // screenshot taken while the field was still empty.+ it('still finalizes an input step, so the typed text is not lost', async () => {+ captureVisibleTab.mockRejectedValue(new Error('no tab in this harness'));+ const { handleFinalizeInputStep } = await import('../step-pipeline');+ state = CaptureState.PAUSED;++ await handleFinalizeInputStep('step-1', meta, undefined);++ expect(captureVisibleTab).toHaveBeenCalled();+ expect(stepsUpdate).toHaveBeenCalledWith('step-1', { elementMeta: meta });+ });++ it('refuses a finalize once the recording has ended', async () => {+ const { handleFinalizeInputStep } = await import('../step-pipeline');+ state = CaptureState.IDLE;++ await handleFinalizeInputStep('step-1', meta, undefined);++ expect(captureVisibleTab).not.toHaveBeenCalled();+ expect(stepsUpdate).not.toHaveBeenCalled();+ });++ it('still writes an input step update while RECORDING', async () => {+ const { handleUpdateInputStep } = await import('../step-pipeline');++ await handleUpdateInputStep('step-1', 'Type hello');++ expect(updateStepDescription).toHaveBeenCalledWith('step-1', 'Type hello');+ });+});diff --git a/src/entrypoints/background/__tests__/state-update.test.ts b/src/entrypoints/background/__tests__/state-update.test.tsnew file mode 100644index 0000000..85592ab--- /dev/null+++ b/src/entrypoints/background/__tests__/state-update.test.ts@@ -0,0 +1,79 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createActor } from 'xstate';+import { CaptureState, captureMachine } from '@/core/capture/machine';++const sessionGet = vi.fn();++vi.mock('@/lib/browser-api', () => ({+ sessionStorage: {+ get: (key: string) => sessionGet(key),+ set: vi.fn(),+ remove: vi.fn(),+ },+}));++vi.mock('@/lib/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++/** A snapshot as the previous build would have persisted it: no pauseReason. */+function legacyRecordingSnapshot() {+ const actor = createActor(captureMachine);+ actor.start();+ actor.send({ type: 'START_RECORDING', url: 'https://example.com' });+ const persisted = JSON.parse(JSON.stringify(actor.getPersistedSnapshot()));+ delete persisted.context.pauseReason;+ return persisted;+}++function pausedSnapshot() {+ const actor = createActor(captureMachine);+ actor.start();+ actor.send({ type: 'START_RECORDING', url: 'https://example.com' });+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'manual' });+ return JSON.parse(JSON.stringify(actor.getPersistedSnapshot()));+}++async function loadActor(snapshot: unknown) {+ vi.resetModules();+ sessionGet.mockResolvedValue({ machineSnapshot: snapshot });+ const mod = await import('../actor');+ await mod.initActor();+ return mod;+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe('getStateUpdate', () => {+ // Reloading the extension mid-session restores a snapshot written by the+ // build before PAUSED existed. Its context has no pauseReason at all, and an+ // `undefined` reaching the panel read as paused β the pill said "capture+ // paused" and the button offered Resume while the machine was RECORDING.+ it('reports a legacy RECORDING snapshot as recording, not paused', async () => {+ const { getStateUpdate } = await loadActor(legacyRecordingSnapshot());++ const update = getStateUpdate();++ expect(update.state).toBe(CaptureState.RECORDING);+ expect(update.pauseReason).toBeNull();+ });++ it('carries the pause reason when the machine really is paused', async () => {+ const { getStateUpdate } = await loadActor(pausedSnapshot());++ const update = getStateUpdate();++ expect(update.state).toBe(CaptureState.PAUSED);+ expect(update.pauseReason).toBe('manual');+ });++ it('starts idle when there is no snapshot to restore', async () => {+ const { getStateUpdate } = await loadActor(undefined);++ const update = getStateUpdate();++ expect(update.state).toBe(CaptureState.IDLE);+ expect(update.pauseReason).toBeNull();+ expect(update.currentGuideId).toBeNull();+ });+});diff --git a/src/entrypoints/background/__tests__/tab-manager.test.ts b/src/entrypoints/background/__tests__/tab-manager.test.tsnew file mode 100644index 0000000..7d65add--- /dev/null+++ b/src/entrypoints/background/__tests__/tab-manager.test.ts@@ -0,0 +1,91 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const queryTabs = vi.fn();+const sendMessageToTab = vi.fn();++vi.mock('@/lib/browser-api', () => ({+ executeScript: vi.fn(),+ queryTabs: (...args: unknown[]) => queryTabs(...args),+ sendMessageToTab: (tabId: number, msg: unknown) => sendMessageToTab(tabId, msg),+}));++vi.mock('@/lib/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++import {+ broadcastClearBlur,+ broadcastDismissBlur,+ broadcastStopCaptureAndFlush,+ isInjectableTab,+} from '../tab-manager';++function typesSent(): string[] {+ return sendMessageToTab.mock.calls.map(([, msg]) => (msg as { type: string }).type);+}++beforeEach(() => {+ vi.clearAllMocks();+ queryTabs.mockResolvedValue([+ { id: 1, url: 'https://a.test' },+ { id: 2, url: 'https://b.test' },+ ]);+ sendMessageToTab.mockResolvedValue(undefined);+});++describe('blur broadcasts', () => {+ // Swapping these two silently destroys the masks the user just picked, so the+ // message each one sends is worth pinning by name.+ it('dismiss asks every tab to close the overlay and keep the masks', async () => {+ await broadcastDismissBlur();+ expect(typesSent()).toEqual(['DISMISS_BLUR', 'DISMISS_BLUR']);+ });++ it('clear asks every tab to remove the masks', async () => {+ await broadcastClearBlur();+ expect(typesSent()).toEqual(['CLEAR_BLUR', 'CLEAR_BLUR']);+ });+});++describe('broadcastStopCaptureAndFlush', () => {+ it('waits for every tab to answer before resolving', async () => {+ let answered = 0;+ sendMessageToTab.mockImplementation(+ () =>+ new Promise((resolve) => {+ setTimeout(() => {+ answered++;+ resolve(undefined);+ }, 5);+ }),+ );++ await broadcastStopCaptureAndFlush();++ expect(answered).toBe(2);+ expect(typesSent()).toEqual(['STOP_CAPTURE', 'STOP_CAPTURE']);+ });++ // A tab with no content script rejects, and a frozen one never answers at+ // all β neither may hold the pause open.+ it('resolves even when a tab never answers', async () => {+ sendMessageToTab.mockImplementation(() => new Promise(() => {}));+ await expect(broadcastStopCaptureAndFlush()).resolves.toBeUndefined();+ });++ it('resolves when a tab rejects', async () => {+ sendMessageToTab.mockRejectedValue(new Error('no receiving end'));+ await expect(broadcastStopCaptureAndFlush()).resolves.toBeUndefined();+ });+});++describe('isInjectableTab', () => {+ it.each([+ ['https://example.com', true],+ ['http://localhost:3000', true],+ ['chrome://extensions', false],+ ['chrome-extension://abc/fullview.html', false],+ ['about:blank', false],+ ['', false],+ ])('%s β %s', (url, expected) => {+ expect(isInjectableTab({ url })).toBe(expected);+ });+});diff --git a/src/lib/__tests__/port.test.ts b/src/lib/__tests__/port.test.tsindex e17518e..ec4a906 100644--- a/src/lib/__tests__/port.test.ts+++ b/src/lib/__tests__/port.test.ts@@ -28,7 +28,13 @@ class FakePort {}}-const STATE: PanelStateUpdate = { type: 'STATE_UPDATE', state: 'IDLE', stepCount: 0, currentGuideId: null };+const STATE: PanelStateUpdate = {+ type: 'STATE_UPDATE',+ state: 'IDLE',+ stepCount: 0,+ currentGuideId: null,+ pauseReason: null,+};const TRANSCRIBING: PanelVoiceUpdate = { type: 'VOICE_UPDATE', phase: 'transcribing' };const DONE: PanelVoiceUpdate = { type: 'VOICE_UPDATE', phase: 'idle', narrated: 3 };diff --git a/src/locales/__tests__/coverage.test.ts b/src/locales/__tests__/coverage.test.tsindex 2e2f000..f3c280a 100644--- a/src/locales/__tests__/coverage.test.ts+++ b/src/locales/__tests__/coverage.test.ts@@ -20,8 +20,14 @@ function localeKeys(path: string): string[] {return keys.sort();}-describe('zh-CN locale coverage', () => {- it('matches the English message keys', () => {- expect(localeKeys('src/locales/zh-CN.yml')).toEqual(localeKeys('src/locales/en.yml'));- });+// Every locale, not just zh-CN: a key missing from one of the others used to+// ship silently and render as the raw key in the UI.+const LOCALES = ['zh-CN', 'es', 'fr', 'de', 'pt-BR'] as const;++describe('locale coverage', () => {+ for (const locale of LOCALES) {+ it(`${locale} matches the English message keys`, () => {+ expect(localeKeys(`src/locales/${locale}.yml`)).toEqual(localeKeys('src/locales/en.yml'));+ });+ }});