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 📖

test: move shared tests into the packages they cover and unit test the desktop recorder rules

Luis Ortiz5ddb2bab5a3b
diff --git a/apps/desktop/scripts/check-pipeline.ts b/apps/desktop/scripts/check-pipeline.ts
index 9458b6e..0828579 100644
--- a/apps/desktop/scripts/check-pipeline.ts
+++ b/apps/desktop/scripts/check-pipeline.ts
@@ -9,15 +9,10 @@ import type { KeyAction } from '../src/main/capture/input-hook';
import {
type CaptureRequest,
typedTextFor,
- clickAction,
comboLabel,
DesktopRecorder,
- frameFor,
- isRepeatClick,
isRepeatKey,
- isTextKey,
isBoundShortcut,
- shouldCapture,
targetRect,
} from '../src/main/capture/recorder';
import { clampToDisplays } from '../src/main/capture/region';
@@ -25,8 +20,6 @@ import { registerScreenshotProtocol, SCREENSHOT_SCHEME, sweepScreenshots } from
import {
DEFAULT_CAPTURE_SETTINGS,
loadSettings,
- MAX_TYPING_DEBOUNCE_MS,
- MIN_TYPING_DEBOUNCE_MS,
normaliseSettings,
saveSettings,
} from '../src/main/capture/settings';
@@ -135,86 +128,8 @@ app.whenReady().then(async () => {
detail: `5000 ms clamped to ${clamped.screenshotDelayMs}, 750 ms reloaded as ${reloaded.screenshotDelayMs}`,
});
- const knobs = normaliseSettings({
- typingDebounceMs: 50,
- recordKeys: 'yes' as never,
- shortcuts: { startStop: ' ', pauseResume: null, capture: 'Alt+F2' } as never,
- });
- const legacy = normaliseSettings({
- captureOutsideClicks: true,
- captureKeys: false,
- captureTyping: false,
- });
- results.push({
- name: 'settings saved under the old names carry over',
- ok:
- legacy.keepClicksBeyondArea &&
- !legacy.recordKeys &&
- !legacy.recordTyping &&
- normaliseSettings({ recordTyping: true, captureTyping: false }).recordTyping &&
- normaliseSettings({ captureMode: 'region' as never }).captureMode === 'area',
- detail: 'each old key maps onto its new name, the new name wins when both are present, and region mode reads as area',
- });
-
- results.push({
- name: 'toggles, knobs and shortcuts normalise',
- ok:
- knobs.typingDebounceMs === MIN_TYPING_DEBOUNCE_MS &&
- normaliseSettings({ typingDebounceMs: 90_000 }).typingDebounceMs === MAX_TYPING_DEBOUNCE_MS &&
- knobs.recordKeys === DEFAULT_CAPTURE_SETTINGS.recordKeys &&
- knobs.shortcuts.startStop === null &&
- knobs.shortcuts.pauseResume === null &&
- knobs.shortcuts.capture === 'Alt+F2' &&
- normaliseSettings({}).shortcuts.startStop === DEFAULT_CAPTURE_SETTINGS.shortcuts.startStop,
- detail: `50 ms clamped to ${knobs.typingDebounceMs}, a blank accelerator cleared, a missing one kept its default`,
- });
-
- results.push({
- name: 'a right click is its own action',
- ok: clickAction(1) === 'click' && clickAction(2) === 'auxclick' && clickAction(3) === 'click',
- detail: 'the right button reads as auxclick, left and middle as click',
- });
saveSettings(userSettings);
- const outsidePoint = { x: region.x + region.width + 40, y: region.y + 20 };
- results.push({
- name: 'outside clicks are opt in',
- ok:
- !shouldCapture({ ...REGION_MODE, keepClicksBeyondArea: false }, region, outsidePoint) &&
- shouldCapture({ ...REGION_MODE, keepClicksBeyondArea: true }, region, outsidePoint) &&
- shouldCapture({ ...REGION_MODE, keepClicksBeyondArea: false }, region, {
- x: region.x + 10,
- y: region.y + 10,
- }) &&
- shouldCapture({ ...DEFAULT_CAPTURE_SETTINGS, keepClicksBeyondArea: false }, region, outsidePoint),
- detail: 'ignored when off, captured when on, inside always captured, never filtered outside region mode',
- });
-
- results.push({
- name: 'a double click is one step',
- ok:
- isRepeatClick(1_000, 1_120) &&
- isRepeatClick(1_000, 1_500) &&
- !isRepeatClick(1_000, 1_501) &&
- !isRepeatClick(null, 1_000),
- detail: 'a press within 500 ms of the last one is dropped, later is kept, the first always captures',
- });
-
- const insidePoint = { x: region.x + 10, y: region.y + 10 };
- const windowRect = { x: region.x + 5, y: region.y + 5, width: 300, height: 200 };
- const elsewhere = { x: region.x + 900, y: region.y + 900, width: 100, height: 100 };
- const sameRect = (a: Rect, b: Rect) => a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
- results.push({
- name: 'each mode frames its own rectangle',
- ok:
- sameRect(frameFor('screen', insidePoint, region, windowRect), display.bounds) &&
- sameRect(frameFor('window', insidePoint, region, windowRect), windowRect) &&
- sameRect(frameFor('window', insidePoint, region, elsewhere), display.bounds) &&
- sameRect(frameFor('window', insidePoint, region, null), display.bounds) &&
- sameRect(frameFor('area', insidePoint, region, windowRect), region) &&
- sameRect(frameFor('area', outsidePoint, region, windowRect), region),
- detail: 'screen takes the display, window takes the window and falls back twice, region always takes the region',
- });
let framedBy: CaptureRequest | null = null;
const clickedWindow = { x: region.x + 40, y: region.y + 30, width: 300, height: 200 };
@@ -401,21 +316,6 @@ app.whenReady().then(async () => {
detail: `wrote ${secret?.action ?? 'nothing'} with inputValue ${String(secret?.inputValue)} and no captured text`,
});
- const press = (keycode: number, held: Partial<KeyAction> = {}) =>
- isTextKey({ kind: 'keydown', keycode, shift: false, alt: false, ctrl: false, meta: false, at: 0, ...held });
- results.push({
- name: 'only typing keys open a session',
- ok:
- press(30) &&
- press(30, { shift: true }) &&
- !press(30, { ctrl: true }) &&
- !press(28) &&
- !press(15) &&
- !press(1) &&
- !press(42),
- detail: 'a letter types, shift still types, a shortcut does not, and Enter, Tab, Escape and Shift all close the session',
- });
-
const pressed = (keycode: number, held: Partial<KeyAction> = {}): KeyAction => ({
kind: 'keydown',
keycode,
diff --git a/apps/desktop/src/main/__tests__/recorder-rules.test.ts b/apps/desktop/src/main/__tests__/recorder-rules.test.ts
new file mode 100644
index 0000000..3aab309
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/recorder-rules.test.ts
@@ -0,0 +1,159 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const DISPLAY = { x: 0, y: 0, width: 1920, height: 1080 };
+
+vi.mock('electron', () => ({
+ app: { getPath: () => '/tmp' },
+ clipboard: { readText: () => '' },
+ net: {},
+ protocol: {},
+ screen: {
+ getDisplayNearestPoint: () => ({ bounds: DISPLAY, scaleFactor: 1 }),
+ getCursorScreenPoint: () => ({ x: 0, y: 0 }),
+ },
+}));
+vi.mock('node-screenshots', () => ({ Monitor: class {} }));
+vi.mock('../capture/native', () => ({ loadNative: () => null }));
+
+import type { ScreenElement } from '../capture/element';
+import type { KeyAction } from '../capture/input-hook';
+import {
+ clickAction,
+ comboLabel,
+ frameFor,
+ isBoundShortcut,
+ isRepeatClick,
+ isRepeatKey,
+ isTextKey,
+ shouldCapture,
+ typedTextFor,
+} from '../capture/recorder';
+import {
+ DEFAULT_CAPTURE_SETTINGS,
+ MAX_TYPING_DEBOUNCE_MS,
+ MIN_TYPING_DEBOUNCE_MS,
+ normaliseSettings,
+} from '../capture/settings';
+
+const region = { x: 100, y: 100, width: 800, height: 600 };
+const AREA = { ...DEFAULT_CAPTURE_SETTINGS, captureMode: 'area' as const };
+const inside = { x: region.x + 10, y: region.y + 10 };
+const outside = { x: region.x + region.width + 40, y: region.y + 20 };
+
+function key(keycode: number, held: Partial<KeyAction> = {}): KeyAction {
+ return { kind: 'keydown', keycode, shift: false, alt: false, ctrl: false, meta: false, at: 0, ...held };
+}
+
+function editor(value: string | null): ScreenElement {
+ return {
+ role: 'document',
+ name: null,
+ textContent: value,
+ ariaLabel: 'Document',
+ altText: null,
+ password: false,
+ ancestors: [],
+ children: [],
+ rect: { x: 0, y: 0, width: 400, height: 300 },
+ };
+}
+
+describe('capture settings', () => {
+ it('reads settings saved under the old names, letting a new name win and region mode read as area', () => {
+ const legacy = normaliseSettings({ captureOutsideClicks: true, captureKeys: false, captureTyping: false });
+ expect(legacy.keepClicksBeyondArea).toBe(true);
+ expect(legacy.recordKeys).toBe(false);
+ expect(legacy.recordTyping).toBe(false);
+ expect(normaliseSettings({ recordTyping: true, captureTyping: false }).recordTyping).toBe(true);
+ expect(normaliseSettings({ captureMode: 'region' as never }).captureMode).toBe('area');
+ });
+
+ it('clamps the knobs, drops a blank shortcut and keeps a missing one at its default', () => {
+ const knobs = normaliseSettings({
+ screenshotDelayMs: 5000,
+ typingDebounceMs: 50,
+ recordKeys: 'yes' as never,
+ captureMode: 'sideways' as never,
+ shortcuts: { startStop: ' ', pauseResume: null, capture: 'Alt+F2' } as never,
+ });
+ expect(knobs.screenshotDelayMs).toBe(2000);
+ expect(knobs.typingDebounceMs).toBe(MIN_TYPING_DEBOUNCE_MS);
+ expect(normaliseSettings({ typingDebounceMs: 90_000 }).typingDebounceMs).toBe(MAX_TYPING_DEBOUNCE_MS);
+ expect(knobs.recordKeys).toBe(DEFAULT_CAPTURE_SETTINGS.recordKeys);
+ expect(knobs.captureMode).toBe(DEFAULT_CAPTURE_SETTINGS.captureMode);
+ expect(knobs.shortcuts).toEqual({ startStop: null, pauseResume: null, capture: 'Alt+F2' });
+ expect(normaliseSettings({}).shortcuts.startStop).toBe(DEFAULT_CAPTURE_SETTINGS.shortcuts.startStop);
+ });
+});
+
+describe('clicks', () => {
+ it('reads the right button as its own action', () => {
+ expect([clickAction(1), clickAction(2), clickAction(3)]).toEqual(['click', 'auxclick', 'click']);
+ });
+
+ it('keeps clicks outside the area only when asked, and never filters outside area mode', () => {
+ expect(shouldCapture({ ...AREA, keepClicksBeyondArea: false }, region, outside)).toBe(false);
+ expect(shouldCapture({ ...AREA, keepClicksBeyondArea: true }, region, outside)).toBe(true);
+ expect(shouldCapture({ ...AREA, keepClicksBeyondArea: false }, region, inside)).toBe(true);
+ expect(shouldCapture({ ...DEFAULT_CAPTURE_SETTINGS, keepClicksBeyondArea: false }, region, outside)).toBe(true);
+ });
+
+ it('treats a second press within 500 ms as the same click', () => {
+ expect(isRepeatClick(1_000, 1_120)).toBe(true);
+ expect(isRepeatClick(1_000, 1_500)).toBe(true);
+ expect(isRepeatClick(1_000, 1_501)).toBe(false);
+ expect(isRepeatClick(null, 1_000)).toBe(false);
+ });
+
+ it('frames the display, the window under the click, or the area', () => {
+ const window = { x: region.x + 5, y: region.y + 5, width: 300, height: 200 };
+ const elsewhere = { x: 1500, y: 900, width: 100, height: 100 };
+ expect(frameFor('screen', inside, region, window)).toEqual(DISPLAY);
+ expect(frameFor('window', inside, region, window)).toEqual(window);
+ expect(frameFor('window', inside, region, elsewhere)).toEqual(DISPLAY);
+ expect(frameFor('window', inside, region, null)).toEqual(DISPLAY);
+ expect(frameFor('area', outside, region, window)).toEqual(region);
+ });
+});
+
+describe('keys', () => {
+ it('opens a typing session only for keys that type', () => {
+ expect(isTextKey(key(30))).toBe(true);
+ expect(isTextKey(key(30, { shift: true }))).toBe(true);
+ for (const closing of [key(30, { ctrl: true }), key(28), key(15), key(1), key(42)]) {
+ expect(isTextKey(closing)).toBe(false);
+ }
+ });
+
+ it('recognises our own hotkey whatever order it is written in, and nothing near it', () => {
+ const pressed = key(31, { alt: true, shift: true });
+ expect(isBoundShortcut('Alt+Shift+S', pressed, 'S')).toBe(true);
+ expect(isBoundShortcut('shift+ALT+s', pressed, 'S')).toBe(true);
+ expect(isBoundShortcut('Alt+Shift+S', key(31, { alt: true }), 'S')).toBe(false);
+ expect(isBoundShortcut('Alt+Shift+S', key(31, { alt: true, shift: true, ctrl: true }), 'S')).toBe(false);
+ expect(isBoundShortcut('Alt+Shift+S', pressed, 'R')).toBe(false);
+ expect(isBoundShortcut(null, pressed, 'S')).toBe(false);
+ });
+
+ it('names a shortcut the way each platform writes it, and collapses auto-repeat', () => {
+ expect(comboLabel(key(31, { ctrl: true, shift: true }), 'S', false)).toBe('Ctrl+Shift+S');
+ expect(comboLabel(key(31, { meta: true, shift: true, alt: true }), 'S', true)).toBe('⌥⇧⌘S');
+ expect(isRepeatKey({ keycode: 28, at: 1_000 }, 28, 1_400)).toBe(true);
+ expect(isRepeatKey({ keycode: 28, at: 1_000 }, 28, 1_600)).toBe(false);
+ expect(isRepeatKey({ keycode: 28, at: 1_000 }, 15, 1_100)).toBe(false);
+ });
+});
+
+describe('typed text', () => {
+ it("reads the field's text, and falls back to the keystrokes for long or multi-line fields", () => {
+ expect(typedTextFor(editor('a short note'), 'a sho', false)).toBe('a sho');
+ expect(typedTextFor(editor('a short note'), 'a sho')).toBe('a short note');
+ expect(typedTextFor(editor(null), 'typed')).toBe('typed');
+ expect(typedTextFor({ ...editor('hi​'), role: 'textbox' }, '')).toBe('hi');
+ expect(typedTextFor({ ...editor('Save'), role: 'button' }, 'typed')).toBeNull();
+ expect(typedTextFor(editor('x'.repeat(201)), 'ab')).toBe('ab');
+ expect(typedTextFor(editor('y'.repeat(200)), 'ab')).toBe('y'.repeat(200));
+ expect(typedTextFor(editor('Last login\n➜ ~ testing'), 'testing')).toBe('testing');
+ expect(typedTextFor(editor('line one\nline two'), '')).toBe('line one\nline two');
+ });
+});
diff --git a/packages/core/src/capture/ai/__tests__/finish-guide.test.ts b/packages/core/src/capture/ai/__tests__/finish-guide.test.ts
new file mode 100644
index 0000000..15c0bc5
--- /dev/null
+++ b/packages/core/src/capture/ai/__tests__/finish-guide.test.ts
@@ -0,0 +1,347 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const {
+ clearStepAiPendingMock,
+ generateGuideMetaMock,
+ getGuideDomainMock,
+ getStepsForGuideMock,
+ localStorageGetMock,
+ updateGuideDescriptionMock,
+ updateGuideTitleMock,
+ whenNarrationSettledMock,
+} = vi.hoisted(() => ({
+ clearStepAiPendingMock: vi.fn(),
+ generateGuideMetaMock: vi.fn(),
+ getGuideDomainMock: vi.fn(),
+ getStepsForGuideMock: vi.fn(),
+ localStorageGetMock: vi.fn(),
+ updateGuideDescriptionMock: vi.fn(),
+ updateGuideTitleMock: vi.fn(),
+ whenNarrationSettledMock: vi.fn(),
+}));
+
+vi.mock('../meta', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../meta')>()),
+ generateGuideMeta: generateGuideMetaMock,
+}));
+
+vi.mock('@/core/guides/service', () => ({
+ clearStepAiPending: clearStepAiPendingMock,
+ getGuideDomain: getGuideDomainMock,
+ getStepsForGuide: getStepsForGuideMock,
+ updateGuideDescription: updateGuideDescriptionMock,
+ updateGuideTitle: updateGuideTitleMock,
+}));
+
+vi.mock('@/core/env', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/core/env')>()),
+ localStorage: { get: localStorageGetMock },
+}));
+
+import { i18n } from '@/core/env';
+import { finishGuide } from '../finish-guide';
+import { generateDescriptionOnDemand } from '../guide-description';
+import { AI_PROVIDERS } from '../models';
+
+const GUIDE_ID = 'guide-1';
+
+async function fallbackTitle(guideId: string): Promise<string> {
+ const domain = await getGuideDomainMock(guideId);
+ return domain ? i18n.t('background.guideOnDomain', [domain]) : i18n.t('background.newGuide');
+}
+
+const finish = (guideId: string) =>
+ finishGuide(guideId, { fallbackTitle, settleNarration: () => whenNarrationSettledMock() });
+
+const entryPoints = [
+ ['finishGuide', finish],
+ ['generateDescriptionOnDemand', generateDescriptionOnDemand],
+] as const;
+
+function makeSteps(count: number) {
+ return Array.from({ length: count }, (_, i) => ({
+ description: `step ${i}`,
+ url: `https://example.com/${i}`,
+ }));
+}
+
+describe('guide meta', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ localStorageGetMock.mockResolvedValue({ aiApiKey: 'key', aiProvider: 'openai', aiModel: 'gpt-4o' });
+ getStepsForGuideMock.mockResolvedValue(makeSteps(3));
+ getGuideDomainMock.mockResolvedValue('example.com');
+ updateGuideTitleMock.mockResolvedValue(undefined);
+ updateGuideDescriptionMock.mockResolvedValue(undefined);
+ generateGuideMetaMock.mockResolvedValue({ title: 'Generated Title', description: 'Generated description.' });
+ whenNarrationSettledMock.mockResolvedValue(undefined);
+ });
+
+ describe('input resolution shared by both entry points', () => {
+ it.each(entryPoints)('%s sends the first ten and last five of more than fifteen steps', async (_name, run) => {
+ getStepsForGuideMock.mockResolvedValue(makeSteps(20));
+
+ await run(GUIDE_ID);
+
+ const sent = generateGuideMetaMock.mock.calls[0][0];
+ expect(sent).toHaveLength(15);
+ expect(sent[0].description).toBe('step 0');
+ expect(sent[9].description).toBe('step 9');
+ expect(sent[10].description).toBe('step 15');
+ expect(sent[14].description).toBe('step 19');
+ });
+
+ it.each(entryPoints)('%s sends every step when there are exactly fifteen', async (_name, run) => {
+ getStepsForGuideMock.mockResolvedValue(makeSteps(15));
+
+ await run(GUIDE_ID);
+
+ expect(generateGuideMetaMock.mock.calls[0][0]).toHaveLength(15);
+ });
+
+ it.each(entryPoints)('%s drops steps that have no description', async (_name, run) => {
+ getStepsForGuideMock.mockResolvedValue([
+ { description: 'kept', url: 'https://example.com/a' },
+ { description: '', url: 'https://example.com/b' },
+ ]);
+
+ await run(GUIDE_ID);
+
+ expect(generateGuideMetaMock.mock.calls[0][0]).toEqual([{ description: 'kept', place: 'https://example.com/a' }]);
+ });
+
+ it.each(entryPoints)("%s defaults the model to the provider's own default", async (_name, run) => {
+ localStorageGetMock.mockResolvedValue({ aiApiKey: 'key', aiProvider: 'anthropic' });
+
+ await run(GUIDE_ID);
+
+ expect(generateGuideMetaMock).toHaveBeenCalledWith(
+ expect.anything(),
+ 'anthropic',
+ AI_PROVIDERS.anthropic.defaultModel,
+ 'key',
+ undefined,
+ );
+ });
+
+ it.each(entryPoints)('%s defaults the provider to OpenAI when none is stored', async (_name, run) => {
+ localStorageGetMock.mockResolvedValue({ aiApiKey: 'key' });
+
+ await run(GUIDE_ID);
+
+ expect(generateGuideMetaMock).toHaveBeenCalledWith(
+ expect.anything(),
+ 'openai',
+ AI_PROVIDERS.openai.defaultModel,
+ 'key',
+ undefined,
+ );
+ });
+ });
+
+ describe('finishGuide', () => {
+ it('applies the domain fallback title without calling the model when AI is off for the guide', async () => {
+ localStorageGetMock.mockResolvedValue({
+ aiApiKey: 'key',
+ aiProvider: 'openai',
+ aiModel: 'gpt-4o',
+ aiForGuide: false,
+ });
+
+ await finish(GUIDE_ID);
+
+ expect(generateGuideMetaMock).not.toHaveBeenCalled();
+ expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'background.guideOnDomain[example.com]');
+ });
+
+ it('applies the domain fallback title without calling the model when no key is set', async () => {
+ localStorageGetMock.mockResolvedValue({});
+
+ await finish(GUIDE_ID);
+
+ expect(generateGuideMetaMock).not.toHaveBeenCalled();
+ expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'background.guideOnDomain[example.com]');
+ });
+
+ it('writes the fallback title before narration settles when no key is set', async () => {
+ localStorageGetMock.mockResolvedValue({});
+ let settle!: () => void;
+ whenNarrationSettledMock.mockReturnValue(
+ new Promise<void>((resolve) => {
+ settle = resolve;
+ }),
+ );
+ getStepsForGuideMock.mockResolvedValue([
+ { id: 'step-1', description: '', url: 'https://example.com', aiPending: true },
+ ]);
+
+ const run = finish(GUIDE_ID);
+ await vi.waitFor(() =>
+ expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'background.guideOnDomain[example.com]'),
+ );
+ expect(clearStepAiPendingMock).not.toHaveBeenCalled();
+
+ settle();
+ await run;
+ expect(clearStepAiPendingMock).toHaveBeenCalledWith('step-1');
+ });
+
+ it('waits for narration before generating a title when a key is set', async () => {
+ let settle!: () => void;
+ whenNarrationSettledMock.mockReturnValue(
+ new Promise<void>((resolve) => {
+ settle = resolve;
+ }),
+ );
+ getStepsForGuideMock.mockResolvedValue([
+ { id: 'step-1', description: 'step 1', url: 'https://example.com', aiPending: true },
+ ]);
+
+ const run = finish(GUIDE_ID);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(generateGuideMetaMock).not.toHaveBeenCalled();
+ expect(updateGuideTitleMock).not.toHaveBeenCalled();
+
+ settle();
+ await run;
+ expect(clearStepAiPendingMock).toHaveBeenCalledWith('step-1');
+ expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'Generated Title');
+ });
+
+ it('still clears aiPending when the fallback title write fails', async () => {
+ localStorageGetMock.mockResolvedValue({});
+ updateGuideTitleMock.mockRejectedValue(new Error('DatabaseClosedError'));
+ getStepsForGuideMock.mockResolvedValue([
+ { id: 'step-1', description: '', url: 'https://example.com', aiPending: true },
+ ]);
+
+ await expect(finish(GUIDE_ID)).resolves.toBeUndefined();
+
+ expect(clearStepAiPendingMock).toHaveBeenCalledWith('step-1');
+ });
+
+ it('writes the fallback title only once when settling fails, so a rename in the meantime survives', async () => {
+ localStorageGetMock.mockResolvedValue({});
+ getStepsForGuideMock.mockRejectedValue(new Error('DatabaseClosedError'));
+
+ await expect(finish(GUIDE_ID)).resolves.toBeUndefined();
+
+ expect(updateGuideTitleMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('applies the fallback title and settles when the key cannot be read', async () => {
+ localStorageGetMock.mockRejectedValue(new Error('DatabaseClosedError'));
+ getStepsForGuideMock.mockResolvedValue([
+ { id: 'step-1', description: '', url: 'https://example.com', aiPending: true },
+ ]);
+
+ await finish(GUIDE_ID);
+
+ expect(generateGuideMetaMock).not.toHaveBeenCalled();
+ expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'background.guideOnDomain[example.com]');
+ expect(clearStepAiPendingMock).toHaveBeenCalledWith('step-1');
+ });
+
+ it('falls back to the generic title when the guide has no domain', async () => {
+ localStorageGetMock.mockResolvedValue({});
+ getGuideDomainMock.mockResolvedValue('');
+
+ await finish(GUIDE_ID);
+
+ expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'background.newGuide');
+ });
+
+ it('names a guide with no described step by the fallback, without asking the model', async () => {
+ getStepsForGuideMock.mockResolvedValue([{ description: '', url: 'https://example.com' }]);
+
+ await finish(GUIDE_ID);
+
+ expect(generateGuideMetaMock).not.toHaveBeenCalled();
+ expect(updateGuideTitleMock).toHaveBeenCalledTimes(1);
+ expect(updateGuideDescriptionMock).not.toHaveBeenCalled();
+ });
+
+ it('applies the fallback title when the model yields nothing', async () => {
+ generateGuideMetaMock.mockResolvedValue(null);
+
+ await finish(GUIDE_ID);
+
+ expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'background.guideOnDomain[example.com]');
+ });
+
+ it('stores both the title and the description on success', async () => {
+ await finish(GUIDE_ID);
+
+ expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'Generated Title');
+ expect(updateGuideDescriptionMock).toHaveBeenCalledWith(GUIDE_ID, 'Generated description.');
+ });
+
+ it('keeps the generated title when the description write fails', async () => {
+ updateGuideDescriptionMock.mockRejectedValue(new Error('QuotaExceededError'));
+
+ await finish(GUIDE_ID);
+
+ expect(updateGuideTitleMock).toHaveBeenCalledTimes(1);
+ expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'Generated Title');
+ });
+
+ it('applies the fallback title when the title write itself fails', async () => {
+ updateGuideTitleMock.mockRejectedValueOnce(new Error('DatabaseClosedError'));
+
+ await finish(GUIDE_ID);
+
+ expect(updateGuideTitleMock).toHaveBeenNthCalledWith(2, GUIDE_ID, 'background.guideOnDomain[example.com]');
+ });
+ });
+
+ describe('generateDescriptionOnDemand', () => {
+ it('reports a missing key without touching the guide', async () => {
+ localStorageGetMock.mockResolvedValue({});
+
+ await expect(generateDescriptionOnDemand(GUIDE_ID)).resolves.toEqual({ error: 'no-api-key' });
+ expect(updateGuideTitleMock).not.toHaveBeenCalled();
+ expect(updateGuideDescriptionMock).not.toHaveBeenCalled();
+ });
+
+ it('reports a guide with no described steps', async () => {
+ getStepsForGuideMock.mockResolvedValue([]);
+
+ await expect(generateDescriptionOnDemand(GUIDE_ID)).resolves.toEqual({ error: 'no-steps' });
+ expect(generateGuideMetaMock).not.toHaveBeenCalled();
+ });
+
+ it('reports a failed generation', async () => {
+ generateGuideMetaMock.mockResolvedValue(null);
+
+ await expect(generateDescriptionOnDemand(GUIDE_ID)).resolves.toEqual({ error: 'generation-failed' });
+ expect(updateGuideDescriptionMock).not.toHaveBeenCalled();
+ });
+
+ it('reports a failed generation when the model returns a title but no description', async () => {
+ generateGuideMetaMock.mockResolvedValue({ title: 'Generated Title' });
+
+ await expect(generateDescriptionOnDemand(GUIDE_ID)).resolves.toEqual({ error: 'generation-failed' });
+ expect(updateGuideDescriptionMock).not.toHaveBeenCalled();
+ });
+
+ it('resolves to save-failed rather than rejecting when the write throws', async () => {
+ updateGuideDescriptionMock.mockRejectedValue(new Error('QuotaExceededError'));
+
+ await expect(generateDescriptionOnDemand(GUIDE_ID)).resolves.toEqual({ error: 'save-failed' });
+ });
+
+ it('resolves to save-failed rather than rejecting when reading the inputs throws', async () => {
+ localStorageGetMock.mockRejectedValue(new Error('DatabaseClosedError'));
+
+ await expect(generateDescriptionOnDemand(GUIDE_ID)).resolves.toEqual({ error: 'save-failed' });
+ });
+
+ it('stores and returns the description, leaving the title untouched', async () => {
+ await expect(generateDescriptionOnDemand(GUIDE_ID)).resolves.toEqual({
+ description: 'Generated description.',
+ });
+ expect(updateGuideDescriptionMock).toHaveBeenCalledWith(GUIDE_ID, 'Generated description.');
+ expect(updateGuideTitleMock).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/src/lib/__tests__/utils.test.ts b/packages/core/src/guides/__tests__/domain.test.ts
similarity index 65%
rename from src/lib/__tests__/utils.test.ts
rename to packages/core/src/guides/__tests__/domain.test.ts
index ef60c3c..528ba44 100644
--- a/src/lib/__tests__/utils.test.ts
+++ b/packages/core/src/guides/__tests__/domain.test.ts
@@ -1,6 +1,5 @@
-import { extractDomain, getMostCommonDomain } from '@mimik/core/guides/domain';
-import { getDomainInitial } from '@mimik/ui';
import { describe, expect, it } from 'vitest';
+import { extractDomain, getMostCommonDomain } from '../domain';
describe('extractDomain', () => {
it('extracts hostname from a full URL', () => {
@@ -46,23 +45,3 @@ describe('getMostCommonDomain', () => {
expect(getMostCommonDomain([{ url: 'https://example.com' }])).toBe('example.com');
});
});
-
-describe('getDomainInitial', () => {
- it('returns uppercase first letter', () => {
- const { letter } = getDomainInitial('github.com');
- expect(letter).toBe('G');
- });
-
- it('returns a gradient tuple', () => {
- const { gradient } = getDomainInitial('github.com');
- expect(gradient).toHaveLength(2);
- expect(gradient[0]).toMatch(/^#[0-9A-Fa-f]{6}$/);
- expect(gradient[1]).toMatch(/^#[0-9A-Fa-f]{6}$/);
- });
-
- it('returns consistent gradient for the same domain', () => {
- const a = getDomainInitial('example.com');
- const b = getDomainInitial('example.com');
- expect(a.gradient).toEqual(b.gradient);
- });
-});
diff --git a/packages/ui/src/common/lib/__tests__/domain-initial.test.ts b/packages/ui/src/common/lib/__tests__/domain-initial.test.ts
new file mode 100644
index 0000000..d32e50e
--- /dev/null
+++ b/packages/ui/src/common/lib/__tests__/domain-initial.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+import { getDomainInitial } from '../domain-initial';
+
+describe('getDomainInitial', () => {
+ it('returns uppercase first letter', () => {
+ const { letter } = getDomainInitial('github.com');
+ expect(letter).toBe('G');
+ });
+
+ it('returns a gradient tuple', () => {
+ const { gradient } = getDomainInitial('github.com');
+ expect(gradient).toHaveLength(2);
+ expect(gradient[0]).toMatch(/^#[0-9A-Fa-f]{6}$/);
+ expect(gradient[1]).toMatch(/^#[0-9A-Fa-f]{6}$/);
+ });
+
+ it('returns consistent gradient for the same domain', () => {
+ const a = getDomainInitial('example.com');
+ const b = getDomainInitial('example.com');
+ expect(a.gradient).toEqual(b.gradient);
+ });
+});
diff --git a/src/ui/fullview/__tests__/ExportPreviewModal.test.tsx b/packages/ui/src/export/components/__tests__/ExportPreviewModal.test.tsx
similarity index 93%
rename from src/ui/fullview/__tests__/ExportPreviewModal.test.tsx
rename to packages/ui/src/export/components/__tests__/ExportPreviewModal.test.tsx
index f0a91d0..ee9e5b6 100644
--- a/src/ui/fullview/__tests__/ExportPreviewModal.test.tsx
+++ b/packages/ui/src/export/components/__tests__/ExportPreviewModal.test.tsx
@@ -1,8 +1,9 @@
// @vitest-environment jsdom
+
+import { DEFAULT_EXPORT_OPTIONS } from '@mimik/core/export/options';
+import type { Guide, Screenshot, Step } from '@mimik/core/guides/types';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { DEFAULT_EXPORT_OPTIONS } from '@/core/export/options';
-import type { Guide, Screenshot, Step } from '@/core/guides/types';
const exportGuideAsVideo = vi.hoisted(() => vi.fn());
const exportGuideAsHTML = vi.hoisted(() => vi.fn());
@@ -10,32 +11,32 @@ const canExportVideo = vi.hoisted(() => vi.fn());
const stored = vi.hoisted(() => ({ value: {} as Record<string, unknown> }));
const downloadBlob = vi.hoisted(() => vi.fn());
-vi.mock('@/core/export/download', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/core/export/download')>()),
+vi.mock('@mimik/core/export/download', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@mimik/core/export/download')>()),
downloadBlob,
}));
-vi.mock('@/core/env', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/core/env')>()),
+vi.mock('@mimik/core/env', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@mimik/core/env')>()),
localStorage: { get: async () => stored.value, set: async () => {} },
}));
-vi.mock('@/core/export/video-export', () => ({ exportGuideAsVideo }));
-vi.mock('@mimik/ui/export/components/VideoStepPlayer', () => ({
+vi.mock('@mimik/core/export/video-export', () => ({ exportGuideAsVideo }));
+vi.mock('../VideoStepPlayer', () => ({
VideoStepPlayer: () => <div data-testid="video-player" />,
}));
-vi.mock('@/core/export/html-export', () => ({ exportGuideAsHTML }));
-vi.mock('@/core/export/video-support', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/core/export/video-support')>()),
+vi.mock('@mimik/core/export/html-export', () => ({ exportGuideAsHTML }));
+vi.mock('@mimik/core/export/video-support', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@mimik/core/export/video-support')>()),
canExportVideo,
}));
-vi.mock('@/core/export/options', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/core/export/options')>()),
+vi.mock('@mimik/core/export/options', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@mimik/core/export/options')>()),
loadExportOptions: async () => DEFAULT_EXPORT_OPTIONS,
saveExportOptions: async () => {},
}));
-import { ExportPreviewModal } from '@mimik/ui';
+import { ExportPreviewModal } from '../ExportPreviewModal';
const guide: Guide = {
id: 'guide-1',
diff --git a/src/ui/sidepanel/__tests__/step-card-drag.test.tsx b/packages/ui/src/guide/components/__tests__/step-card-drag.test.tsx
similarity index 81%
rename from src/ui/sidepanel/__tests__/step-card-drag.test.tsx
rename to packages/ui/src/guide/components/__tests__/step-card-drag.test.tsx
index d3efd38..31b3b91 100644
--- a/src/ui/sidepanel/__tests__/step-card-drag.test.tsx
+++ b/packages/ui/src/guide/components/__tests__/step-card-drag.test.tsx
@@ -1,12 +1,13 @@
// @vitest-environment jsdom
-import { StepCard, TooltipProvider } from '@mimik/ui';
+import type { Step } from '@mimik/core/guides/types';
import { fireEvent, render } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
-import type { Step } from '@/core/guides/types';
+import { TooltipProvider } from '../../../components/ui/tooltip';
+import { StepCard } from '../StepCard';
-vi.mock('@/core/guides/service', () => ({ replaceScreenshot: vi.fn() }));
-vi.mock('@/core/screenshot/render', () => ({ imageDimensions: vi.fn(), renderScreenshot: vi.fn() }));
+vi.mock('@mimik/core/guides/service', () => ({ replaceScreenshot: vi.fn() }));
+vi.mock('@mimik/core/screenshot/render', () => ({ imageDimensions: vi.fn(), renderScreenshot: vi.fn() }));
const step: Step = {
id: 's1',
diff --git a/src/ui/sidepanel/__tests__/step-card-upload.test.tsx b/packages/ui/src/guide/components/__tests__/step-card-upload.test.tsx
similarity index 75%
rename from src/ui/sidepanel/__tests__/step-card-upload.test.tsx
rename to packages/ui/src/guide/components/__tests__/step-card-upload.test.tsx
index 4a29101..4b272a9 100644
--- a/src/ui/sidepanel/__tests__/step-card-upload.test.tsx
+++ b/packages/ui/src/guide/components/__tests__/step-card-upload.test.tsx
@@ -1,12 +1,13 @@
// @vitest-environment jsdom
-import { StepCard, TooltipProvider } from '@mimik/ui';
+import type { Step } from '@mimik/core/guides/types';
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
-import type { Step } from '@/core/guides/types';
+import { TooltipProvider } from '../../../components/ui/tooltip';
+import { StepCard } from '../StepCard';
-vi.mock('@/core/guides/service', () => ({ replaceScreenshot: vi.fn() }));
-vi.mock('@/core/screenshot/render', () => ({ imageDimensions: vi.fn(), renderScreenshot: vi.fn() }));
+vi.mock('@mimik/core/guides/service', () => ({ replaceScreenshot: vi.fn() }));
+vi.mock('@mimik/core/screenshot/render', () => ({ imageDimensions: vi.fn(), renderScreenshot: vi.fn() }));
const step: Step = {
id: 's1',
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index 68a6b12..f5b061a 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -12,7 +12,6 @@ export { Segmented } from './common/components/Segmented';
export { SettingsCard } from './common/components/SettingsCard';
export { Switch } from './common/components/Switch';
export { useSavedFlash } from './common/hooks/use-saved-flash';
-export { getDomainInitial } from './common/lib/domain-initial';
export { formatRelativeTime } from './common/lib/format-relative-time';
export { Button } from './components/ui/button';
export {
@@ -26,7 +25,6 @@ export {
export { Input } from './components/ui/input';
export { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './components/ui/select';
export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './components/ui/tooltip';
-export { ExportPreviewModal } from './export/components/ExportPreviewModal';
export { VoiceoverSettings } from './export/components/VoiceoverSettings';
export { BlockCard } from './guide/components/BlockCard';
export { EmptyGuideState } from './guide/components/EmptyGuideState';
diff --git a/src/entrypoints/background/__tests__/guide-meta.test.ts b/src/entrypoints/background/__tests__/guide-meta.test.ts
index 85c26d1..a895e58 100644
--- a/src/entrypoints/background/__tests__/guide-meta.test.ts
+++ b/src/entrypoints/background/__tests__/guide-meta.test.ts
@@ -40,17 +40,10 @@ vi.mock('@/core/env', async (importOriginal) => ({
vi.mock('../voice', () => ({ whenNarrationSettled: whenNarrationSettledMock }));
-import { generateDescriptionOnDemand } from '@/core/capture/ai/guide-description';
-import { AI_PROVIDERS } from '@/core/capture/ai/models';
import { generateGuideMetaOnStop } from '../guide-meta';
const GUIDE_ID = 'guide-1';
-const entryPoints = [
- ['generateGuideMetaOnStop', generateGuideMetaOnStop],
- ['generateDescriptionOnDemand', generateDescriptionOnDemand],
-] as const;
-
function makeSteps(count: number) {
return Array.from({ length: count }, (_, i) => ({
description: `step ${i}`,
@@ -70,83 +63,7 @@ describe('background guide-meta', () => {
whenNarrationSettledMock.mockResolvedValue(undefined);
});
- describe('input resolution shared by both entry points', () => {
- it.each(entryPoints)('%s sends the first ten and last five of more than fifteen steps', async (_name, run) => {
- getStepsForGuideMock.mockResolvedValue(makeSteps(20));
-
- await run(GUIDE_ID);
-
- const sent = generateGuideMetaMock.mock.calls[0][0];
- expect(sent).toHaveLength(15);
- expect(sent[0].description).toBe('step 0');
- expect(sent[9].description).toBe('step 9');
- expect(sent[10].description).toBe('step 15');
- expect(sent[14].description).toBe('step 19');
- });
-
- it.each(entryPoints)('%s sends every step when there are exactly fifteen', async (_name, run) => {
- getStepsForGuideMock.mockResolvedValue(makeSteps(15));
-
- await run(GUIDE_ID);
-
- expect(generateGuideMetaMock.mock.calls[0][0]).toHaveLength(15);
- });
-
- it.each(entryPoints)('%s drops steps that have no description', async (_name, run) => {
- getStepsForGuideMock.mockResolvedValue([
- { description: 'kept', url: 'https://example.com/a' },
- { description: '', url: 'https://example.com/b' },
- ]);
-
- await run(GUIDE_ID);
-
- expect(generateGuideMetaMock.mock.calls[0][0]).toEqual([{ description: 'kept', place: 'https://example.com/a' }]);
- });
-
- it.each(entryPoints)("%s defaults the model to the provider's own default", async (_name, run) => {
- localStorageGetMock.mockResolvedValue({ aiApiKey: 'key', aiProvider: 'anthropic' });
-
- await run(GUIDE_ID);
-
- expect(generateGuideMetaMock).toHaveBeenCalledWith(
- expect.anything(),
- 'anthropic',
- AI_PROVIDERS.anthropic.defaultModel,
- 'key',
- undefined,
- );
- });
-
- it.each(entryPoints)('%s defaults the provider to OpenAI when none is stored', async (_name, run) => {
- localStorageGetMock.mockResolvedValue({ aiApiKey: 'key' });
-
- await run(GUIDE_ID);
-
- expect(generateGuideMetaMock).toHaveBeenCalledWith(
- expect.anything(),
- 'openai',
- AI_PROVIDERS.openai.defaultModel,
- 'key',
- undefined,
- );
- });
- });
-
describe('generateGuideMetaOnStop', () => {
- it('applies the domain fallback title without calling the model when AI is off for the guide', async () => {
- localStorageGetMock.mockResolvedValue({
- aiApiKey: 'key',
- aiProvider: 'openai',
- aiModel: 'gpt-4o',
- aiForGuide: false,
- });
-
- await generateGuideMetaOnStop(GUIDE_ID);
-
- expect(generateGuideMetaMock).not.toHaveBeenCalled();
- expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'background.guideOnDomain[example.com]');
- });
-
it('applies the domain fallback title without calling the model when no key is set', async () => {
localStorageGetMock.mockResolvedValue({});
@@ -156,29 +73,6 @@ describe('background guide-meta', () => {
expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'background.guideOnDomain[example.com]');
});
- it('writes the fallback title before narration settles when no key is set', async () => {
- localStorageGetMock.mockResolvedValue({});
- let settle!: () => void;
- whenNarrationSettledMock.mockReturnValue(
- new Promise<void>((resolve) => {
- settle = resolve;
- }),
- );
- getStepsForGuideMock.mockResolvedValue([
- { id: 'step-1', description: '', url: 'https://example.com', aiPending: true },
- ]);
-
- const run = generateGuideMetaOnStop(GUIDE_ID);
- await vi.waitFor(() =>
- expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'background.guideOnDomain[example.com]'),
- );
- expect(clearStepAiPendingMock).not.toHaveBeenCalled();
-
- settle();
- await run;
- expect(clearStepAiPendingMock).toHaveBeenCalledWith('step-1');
- });
-
it('waits for narration before generating a title when a key is set', async () => {
let settle!: () => void;
whenNarrationSettledMock.mockReturnValue(
@@ -200,141 +94,5 @@ describe('background guide-meta', () => {
expect(clearStepAiPendingMock).toHaveBeenCalledWith('step-1');
expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'Generated Title');
});
-
- it('still clears aiPending when the fallback title write fails', async () => {
- localStorageGetMock.mockResolvedValue({});
- updateGuideTitleMock.mockRejectedValue(new Error('DatabaseClosedError'));
- getStepsForGuideMock.mockResolvedValue([
- { id: 'step-1', description: '', url: 'https://example.com', aiPending: true },
- ]);
-
- await expect(generateGuideMetaOnStop(GUIDE_ID)).resolves.toBeUndefined();
-
- expect(clearStepAiPendingMock).toHaveBeenCalledWith('step-1');
- });
-
- it('writes the fallback title only once when settling fails, so a rename in the meantime survives', async () => {
- localStorageGetMock.mockResolvedValue({});
- getStepsForGuideMock.mockRejectedValue(new Error('DatabaseClosedError'));
-
- await expect(generateGuideMetaOnStop(GUIDE_ID)).resolves.toBeUndefined();
-
- expect(updateGuideTitleMock).toHaveBeenCalledTimes(1);
- });
-
- it('applies the fallback title and settles when the key cannot be read', async () => {
- localStorageGetMock.mockRejectedValue(new Error('DatabaseClosedError'));
- getStepsForGuideMock.mockResolvedValue([
- { id: 'step-1', description: '', url: 'https://example.com', aiPending: true },
- ]);
-
- await generateGuideMetaOnStop(GUIDE_ID);
-
- expect(generateGuideMetaMock).not.toHaveBeenCalled();
- expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'background.guideOnDomain[example.com]');
- expect(clearStepAiPendingMock).toHaveBeenCalledWith('step-1');
- });
-
- it('falls back to the generic title when the guide has no domain', async () => {
- localStorageGetMock.mockResolvedValue({});
- getGuideDomainMock.mockResolvedValue('');
-
- await generateGuideMetaOnStop(GUIDE_ID);
-
- expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'background.newGuide');
- });
-
- it('names a guide with no described step by the fallback, without asking the model', async () => {
- getStepsForGuideMock.mockResolvedValue([{ description: '', url: 'https://example.com' }]);
-
- await generateGuideMetaOnStop(GUIDE_ID);
-
- expect(generateGuideMetaMock).not.toHaveBeenCalled();
- expect(updateGuideTitleMock).toHaveBeenCalledTimes(1);
- expect(updateGuideDescriptionMock).not.toHaveBeenCalled();
- });
-
- it('applies the fallback title when the model yields nothing', async () => {
- generateGuideMetaMock.mockResolvedValue(null);
-
- await generateGuideMetaOnStop(GUIDE_ID);
-
- expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'background.guideOnDomain[example.com]');
- });
-
- it('stores both the title and the description on success', async () => {
- await generateGuideMetaOnStop(GUIDE_ID);
-
- expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'Generated Title');
- expect(updateGuideDescriptionMock).toHaveBeenCalledWith(GUIDE_ID, 'Generated description.');
- });
-
- it('keeps the generated title when the description write fails', async () => {
- updateGuideDescriptionMock.mockRejectedValue(new Error('QuotaExceededError'));
-
- await generateGuideMetaOnStop(GUIDE_ID);
-
- expect(updateGuideTitleMock).toHaveBeenCalledTimes(1);
- expect(updateGuideTitleMock).toHaveBeenCalledWith(GUIDE_ID, 'Generated Title');
- });
-
- it('applies the fallback title when the title write itself fails', async () => {
- updateGuideTitleMock.mockRejectedValueOnce(new Error('DatabaseClosedError'));
-
- await generateGuideMetaOnStop(GUIDE_ID);
-
- expect(updateGuideTitleMock).toHaveBeenNthCalledWith(2, GUIDE_ID, 'background.guideOnDomain[example.com]');
- });
- });
-
- describe('generateDescriptionOnDemand', () => {
- it('reports a missing key without touching the guide', async () => {
- localStorageGetMock.mockResolvedValue({});
-
- await expect(generateDescriptionOnDemand(GUIDE_ID)).resolves.toEqual({ error: 'no-api-key' });
- expect(updateGuideTitleMock).not.toHaveBeenCalled();
- expect(updateGuideDescriptionMock).not.toHaveBeenCalled();
- });
-
- it('reports a guide with no described steps', async () => {
- getStepsForGuideMock.mockResolvedValue([]);
-
- await expect(generateDescriptionOnDemand(GUIDE_ID)).resolves.toEqual({ error: 'no-steps' });
- expect(generateGuideMetaMock).not.toHaveBeenCalled();
- });
-
- it('reports a failed generation', async () => {
- generateGuideMetaMock.mockResolvedValue(null);
-
- await expect(generateDescriptionOnDemand(GUIDE_ID)).resolves.toEqual({ error: 'generation-failed' });
- expect(updateGuideDescriptionMock).not.toHaveBeenCalled();
- });
-
- it('reports a failed generation when the model returns a title but no description', async () => {
- generateGuideMetaMock.mockResolvedValue({ title: 'Generated Title' });
-
- await expect(generateDescriptionOnDemand(GUIDE_ID)).resolves.toEqual({ error: 'generation-failed' });
- expect(updateGuideDescriptionMock).not.toHaveBeenCalled();
- });
-
- it('resolves to save-failed rather than rejecting when the write throws', async () => {
- updateGuideDescriptionMock.mockRejectedValue(new Error('QuotaExceededError'));
-
- await expect(generateDescriptionOnDemand(GUIDE_ID)).resolves.toEqual({ error: 'save-failed' });
- });
-
- it('resolves to save-failed rather than rejecting when reading the inputs throws', async () => {
- localStorageGetMock.mockRejectedValue(new Error('DatabaseClosedError'));
-
- await expect(generateDescriptionOnDemand(GUIDE_ID)).resolves.toEqual({ error: 'save-failed' });
- });
-
- it('stores and returns the description, leaving the title untouched', async () => {
- await expect(generateDescriptionOnDemand(GUIDE_ID)).resolves.toEqual({
- description: 'Generated description.',
- });
- expect(updateGuideDescriptionMock).toHaveBeenCalledWith(GUIDE_ID, 'Generated description.');
- expect(updateGuideTitleMock).not.toHaveBeenCalled();
- });
});
});