🎬 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
refactor(desktop): run the recording lifecycle on the shared capture machine, with the extension's names
Luis Ortiz153ff70233a8
diff --git a/apps/desktop/scripts/check-overlay.ts b/apps/desktop/scripts/check-overlay.tsindex 74812d6..32f72c6 100644--- a/apps/desktop/scripts/check-overlay.ts+++ b/apps/desktop/scripts/check-overlay.ts@@ -1,9 +1,11 @@import { join } from 'node:path';+import { CaptureState, captureMachine } from '@mimik/core/capture/machine';import { app, BrowserWindow, globalShortcut, screen, webContents } from 'electron';import { clampToDisplays, defaultRegion, loadRegion, type Region, saveRegion } from '../src/main/capture/region';import type { CaptureMode } from '../src/main/capture/settings';import { CaptureOverlay } from '../src/main/overlay';import { bindShortcuts, sameShortcuts, shortcutMap, unbindShortcuts } from '../src/main/shortcuts';+import { createActor } from 'xstate';interface CheckResult {name: string;@@ -50,7 +52,16 @@ setTimeout(() => bail(new Error('check did not finish within 60s')), 60_000).unrapp.whenReady().then(async () => {const commands: string[] = [];let mode: CaptureMode = 'region';+ const capture = createActor(captureMachine).start();+ const record = () => {+ const state = capture.getSnapshot().value;+ if (state === CaptureState.IDLE) capture.send({ type: 'ARM' });+ if (capture.getSnapshot().value === CaptureState.ARMED) capture.send({ type: 'START_RECORDING' });+ if (state === CaptureState.PAUSED) capture.send({ type: 'RESUME_CAPTURE' });+ };+ const pause = () => capture.send({ type: 'PAUSE_CAPTURE', reason: 'manual' });const overlay: CaptureOverlay = new CaptureOverlay(+ capture,(command) => commands.push(command),() => mode,{@@ -137,14 +148,14 @@ app.whenReady().then(async () => {'Start plays the intro over the capture area before recording',intro !== null &&!commands.includes('start') &&- overlay.state === 'armed' &&+ overlay.state === CaptureState.ARMED &&startCard.label === 'Starting…' &&startCard.start === true &&introBounds?.width === overlay.region.width &&introBounds?.height === overlay.region.height,`intro ${introBounds ? `${introBounds.width} × ${introBounds.height}` : 'missing'}, card says ${startCard.label}, commands: ${commands.join(', ') || 'none'}`,);- const recorded = await until(() => overlay.state === 'recording', 7_000);+ const recorded = await until(() => overlay.state === CaptureState.RECORDING, 7_000);check('Start reaches the host and records once the intro ends',recorded && commands.includes('start') && overlay.introWindow === null,@@ -152,19 +163,19 @@ app.whenReady().then(async () => {);await windowWithHash('controls')?.webContents.executeJavaScript("document.querySelector('#secondary').click()");await settle();- const pausedInto = overlay.state;- overlay.run('cancel');+ const pausedInto = overlay.isEditing ? 'editor' : overlay.state;+ overlay.run('cancelEdit');await settle();check('Pause in Area mode pauses and opens the area editor, and Cancel leaves it paused',- commands.includes('pause') && pausedInto === 'editing' && overlay.state === 'paused',+ commands.includes('pause') && pausedInto === 'editor' && overlay.state === CaptureState.PAUSED,`commands: ${commands.join(', ')}; pause opened ${pausedInto}, cancel left ${overlay.state}`,);await windowWithHash('controls')?.webContents.executeJavaScript("document.querySelector('#primary').click()");await settle();check('finishing hides the area and the controls',- overlay.state === 'hidden' && overlayWindows().every((w) => !w.isVisible()),+ overlay.state === CaptureState.IDLE && overlayWindows().every((w) => !w.isVisible()),`state is ${overlay.state}; ${overlayWindows().filter((w) => w.isVisible()).length} window(s) still visible`,);overlay.arm();@@ -197,7 +208,7 @@ app.whenReady().then(async () => {const evaluate = (script: string) => windowWithHash('controls')?.webContents.executeJavaScript(script);const card = async (fields: string) => JSON.parse(String((await evaluate(`JSON.stringify({ ${fields} })`)) ?? '{}'));const src = 'mimik-screenshot://00000000-0000-4000-8000-000000000000';- overlay.record();+ record();await settle();const idle = await card("tip: document.querySelector('#tip').textContent, hint: document.querySelector('#keyHint').textContent");check(@@ -206,12 +217,12 @@ app.whenReady().then(async () => {`tip: ${idle.tip}, hint: ${idle.hint}`,);const badgeWhileRecording = await card("badge: !document.querySelector('#badge').hidden && document.querySelector('#badge').textContent");- overlay.pause();+ pause();await settle();const resting = await card("tip: document.querySelector('#tip').textContent, intro: !document.querySelector('#intro').hidden, resting: document.body.classList.contains('resting'), hint: document.querySelector('#keyHint').hidden",);- overlay.record();+ record();await settle();check('recording names its mode, and an empty pause is not a blank card',@@ -266,13 +277,13 @@ app.whenReady().then(async () => {await evaluate("document.querySelector('#remove').click()");await settle();- check('removing the step reaches the host', commands.includes('remove'), `commands: ${commands.join(', ')}`);+ check('removing the step reaches the host', commands.includes('deleteStep'), `commands: ${commands.join(', ')}`);- overlay.run('mic:on');+ overlay.run('narration:start');await settle();check('turning narration on reaches the host and keeps recording',- commands.includes('mic:on') && overlay.state === 'recording',+ commands.includes('narration:start') && overlay.state === CaptureState.RECORDING,`state ${overlay.state}, commands: ${commands.join(', ')}`,);@@ -406,11 +417,11 @@ app.whenReady().then(async () => {const inEditor = (script: string) => editorWindows()[0]?.executeJavaScript(script);const pickArea = () =>windowWithHash('controls')?.webContents.executeJavaScript("document.querySelector('button.mode[data-mode=\"area\"]').click()");- overlay.pause();+ pause();await settle();await pickArea();await settle();- const opened = { state: overlay.state, editors: editorWindows().length, sent: commands.at(-1) };+ const opened = { state: overlay.isEditing ? 'editor' : overlay.state, editors: editorWindows().length, sent: commands.at(-1) };const look = JSON.parse(String((await inEditor(@@ -420,21 +431,21 @@ app.whenReady().then(async () => {) as { buttons?: string[]; edge?: string; corner?: string };await inEditor("document.querySelector('#bar button.secondary').click()");await settle();- const cancelled = { state: overlay.state, editors: editorWindows().length, sent: commands.at(-1) };+ const cancelled = { state: overlay.isEditing ? 'editor' : overlay.state, editors: editorWindows().length, sent: commands.at(-1) };await pickArea();await settle();await inEditor("document.querySelector('#bar button.primary').click()");await settle();- const confirmed = { state: overlay.state, editors: editorWindows().length, sent: commands.at(-1) };+ const confirmed = { state: overlay.isEditing ? 'editor' : overlay.state, editors: editorWindows().length, sent: commands.at(-1) };check('picking Area while paused opens the editor, Done resumes and Cancel stays paused',- opened.state === 'editing' &&+ opened.state === 'editor' &&opened.editors === displays.length &&opened.sent === 'mode:region' &&- cancelled.state === 'paused' &&+ cancelled.state === CaptureState.PAUSED &&cancelled.editors === 0 &&cancelled.sent === 'mode:screen' &&- confirmed.state === 'recording' &&+ confirmed.state === CaptureState.RECORDING &&confirmed.editors === 0 &&confirmed.sent === 'resume',`opened ${JSON.stringify(opened)}, cancel ${JSON.stringify(cancelled)}, done ${JSON.stringify(confirmed)}`,@@ -494,7 +505,7 @@ app.whenReady().then(async () => {`refused ${clash.join(', ') || 'nothing'}`,);- overlay.hide();+ overlay.reset();overlay.destroy();saveRegion(defaultRegion());diff --git a/apps/desktop/scripts/check-pipeline.ts b/apps/desktop/scripts/check-pipeline.tsindex b5f6ad4..46aed03 100644--- a/apps/desktop/scripts/check-pipeline.ts+++ b/apps/desktop/scripts/check-pipeline.ts@@ -85,25 +85,25 @@ app.whenReady().then(async () => {const recorder = new DesktopRecorder(() => region,(fn) => fn(),- (request) => ask(win.webContents, 'mimik:capture:step', { ...request, guideId: activeGuide }),+ (request) => ask(win.webContents, 'mimik:capture:captureStep', { ...request, guideId: activeGuide }),{ grab: async () => syntheticDisplay, settings: () => settings, lookup: () => Promise.resolve(null) },);- activeGuide = await ask<string>(win.webContents, 'mimik:capture:startGuide');+ activeGuide = await ask<string>(win.webContents, 'mimik:capture:createGuide');const guideId = activeGuide;await recorder.capture({ x: region.x + 120, y: region.y + 90 });await recorder.capture({ x: region.x + 400, y: region.y + 300 });const results = await ask<CheckResult[]>(win.webContents, 'mimik:check:verify', guideId, 60_000);- const blindGuide = await ask<string>(win.webContents, 'mimik:capture:startGuide');+ const blindGuide = await ask<string>(win.webContents, 'mimik:capture:createGuide');let blindRequest: CaptureRequest | null = null;const blind = new DesktopRecorder(() => region,(fn) => fn(),(request) => {blindRequest = request;- return ask(win.webContents, 'mimik:capture:step', { ...request, guideId: blindGuide });+ return ask(win.webContents, 'mimik:capture:captureStep', { ...request, guideId: blindGuide });},{ grab: () => Promise.reject(new Error('display gone')), settings: () => settings, lookup: () => Promise.resolve(null) },);@@ -635,7 +635,7 @@ app.whenReady().then(async () => {detail: 'a real rectangle wins; no element, one covering the frame, or one overflowing it falls back to the click box',});- activeGuide = await ask<string>(win.webContents, 'mimik:capture:startGuide');+ activeGuide = await ask<string>(win.webContents, 'mimik:capture:createGuide');settings = { ...REGION_MODE, screenshotDelayMs: 400 };const before = Date.now();@@ -664,7 +664,7 @@ app.whenReady().then(async () => {await app_.loadFile(join(__dirname, '../renderer/index.html'));let wired = 'no reply';try {- const id = await ask<string>(app_.webContents, 'mimik:capture:startGuide', undefined, 20_000);+ const id = await ask<string>(app_.webContents, 'mimik:capture:createGuide', {}, 20_000);wired = typeof id === 'string' && id.length > 0 ? id : `unexpected reply ${JSON.stringify(id)}`;await ask(app_.webContents, 'mimik:check:cleanup', [id], 20_000).catch(() => undefined);} catch (error) {@@ -678,7 +678,7 @@ app.whenReady().then(async () => {let titled = 'no reply';try {- const id = await ask<string>(app_.webContents, 'mimik:capture:startGuide', undefined, 20_000);+ const id = await ask<string>(app_.webContents, 'mimik:capture:createGuide', {}, 20_000);await ask(app_.webContents, 'mimik:capture:finishGuide', id, 20_000);titled = (await ask<string | null>(win.webContents, 'mimik:check:title', id, 20_000)) ?? 'no guide';await ask(app_.webContents, 'mimik:check:cleanup', [id], 20_000).catch(() => undefined);@@ -688,7 +688,7 @@ app.whenReady().then(async () => {let merged = 'no reply';try {const labelled = (guide: string, ariaLabel: string) =>- ask(app_.webContents, 'mimik:capture:step', {+ ask(app_.webContents, 'mimik:capture:captureStep', {guideId: guide,action: 'click',elementMeta: {@@ -703,13 +703,13 @@ app.whenReady().then(async () => {devicePixelRatio: 1,},}, 20_000);- const target = await ask<string>(app_.webContents, 'mimik:capture:startGuide', false, 20_000);+ const target = await ask<string>(app_.webContents, 'mimik:capture:createGuide', { staging: false }, 20_000);await labelled(target, 'First');await labelled(target, 'Third');const before = await ask<string | null>(win.webContents, 'mimik:check:title', target, 20_000);- const staging = await ask<string>(app_.webContents, 'mimik:capture:startGuide', true, 20_000);+ const staging = await ask<string>(app_.webContents, 'mimik:capture:createGuide', { staging: true }, 20_000);await labelled(staging, 'Second');- await ask(app_.webContents, 'mimik:capture:insertGuide', { guideId: staging, targetGuideId: target, atIndex: 1 }, 20_000);+ await ask(app_.webContents, 'mimik:capture:mergeGuideInto', { guideId: staging, targetGuideId: target, atIndex: 1 }, 20_000);const order = (await ask<string[] | null>(win.webContents, 'mimik:check:steps', target, 20_000)) ?? [];const left = await ask<string[] | null>(win.webContents, 'mimik:check:steps', staging, 20_000);const after = await ask<string | null>(win.webContents, 'mimik:check:title', target, 20_000);@@ -749,7 +749,13 @@ app.whenReady().then(async () => {});const stopped = 'bc4e4a1e-0000-4000-8000-000000000001';- app_.webContents.send('mimik:capture:command', 'stop', 'idle', region, stopped);+ app_.webContents.send('mimik:capture:stateUpdate', {+ command: 'stop',+ state: 'IDLE',+ pauseReason: null,+ currentGuideId: stopped,+ stepCount: 0,+ });let shown = 'no navigation';for (let i = 0; i < 40 && !shown.startsWith('#guide/'); i++) {await new Promise((r) => setTimeout(r, 50));diff --git a/apps/desktop/src/main/__tests__/ask.test.ts b/apps/desktop/src/main/__tests__/ask.test.tsindex ef0de77..2d843f3 100644--- a/apps/desktop/src/main/__tests__/ask.test.ts+++ b/apps/desktop/src/main/__tests__/ask.test.ts@@ -21,12 +21,12 @@ function renderer(reply: unknown): WebContents {describe('ask', () => {it('resolves with what the renderer answered', async () => {- await expect(ask(renderer('guide-1'), 'mimik:capture:startGuide')).resolves.toBe('guide-1');+ await expect(ask(renderer('guide-1'), 'mimik:capture:createGuide')).resolves.toBe('guide-1');});it('rejects when the renderer answered with the error its handler threw', async () => {- await expect(ask(renderer({ error: 'QuotaExceededError' }), 'mimik:capture:startGuide')).rejects.toThrow(- 'mimik:capture:startGuide: QuotaExceededError',+ await expect(ask(renderer({ error: 'QuotaExceededError' }), 'mimik:capture:createGuide')).rejects.toThrow(+ 'mimik:capture:createGuide: QuotaExceededError',);});});diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 57fe76e..26c8585 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -1,6 +1,9 @@import { readFile } from 'node:fs/promises';import { basename, join } from 'node:path';+import { isLive } from '@mimik/core/capture/is-live';+import { CaptureState, captureMachine } from '@mimik/core/capture/machine';import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, protocol, screen, shell, Tray } from 'electron';+import { createActor } from 'xstate';import { shortcutLabel } from '../renderer/lib/shortcut-label';import { registerAiFetch } from './ai-fetch';import { APP_ICON_SCHEME, registerAppIconProtocol } from './app-icon';@@ -34,7 +37,8 @@ let mainWindow: BrowserWindow | null = null;let tray: Tray | null = null;let overlay: CaptureOverlay | null = null;let recorder: DesktopRecorder | null = null;-let guideId: string | null = null;+const capture = createActor(captureMachine).start();+let currentGuideId: string | null = null;let insert: CaptureInsert | null = null;let describing = true;let captureSettings: CaptureSettings | null = null;@@ -114,13 +118,9 @@ function trayIcon(recording: boolean): Electron.NativeImage {return process.platform === 'darwin' ? icon.resize({ width: 16, height: 16 }) : icon;}-function isCapturing(): boolean {- return overlay?.state === 'recording' || overlay?.state === 'paused';-}-function refreshTray(): void {if (!tray) return;- const recording = isCapturing();+ const recording = isLive(capture.getSnapshot().value);tray.setImage(trayIcon(recording));tray.setToolTip(recording ? mainI18n.t('desktop.trayRecording') : 'Mimik');}@@ -254,28 +254,42 @@ function createTray(): void {tray = new Tray(trayIcon(false));tray.setToolTip('Mimik');tray.on('click', () => {- if (isCapturing()) overlay?.run('stop');+ if (isLive(capture.getSnapshot().value)) overlay?.run('stop');else showWindow();});refreshTrayMenu();}-function broadcastOverlay(command: OverlayCommand, id: string | null): void {- mainWindow?.webContents.send('mimik:capture:command', command, overlay?.state, overlay?.region, id);+function captureStateUpdate(command: OverlayCommand | null, guideId: string | null) {+ const { value, context } = capture.getSnapshot();+ return {+ command,+ state: value,+ pauseReason: context.pauseReason,+ currentGuideId: guideId,+ stepCount: context.stepCount,+ };+}++function broadcastState(command: OverlayCommand, guideId: string | null): void {+ mainWindow?.webContents.send('mimik:capture:stateUpdate', captureStateUpdate(command, guideId));}function applyShortcuts(): void {setImmediate(() => {if (!overlay) return;- const recording = overlay.state === 'recording' || overlay.state === 'paused';- bindShortcuts(shortcutMap((captureSettings ?? loadSettings()).shortcuts, recording), onShortcut);+ bindShortcuts(+ shortcutMap((captureSettings ?? loadSettings()).shortcuts, isLive(capture.getSnapshot().value)),+ onShortcut,+ );});}function onShortcut(name: ShortcutName): void {if (!overlay) return;+ const state = capture.getSnapshot().value;if (name === 'startStop') {- if (overlay.state === 'hidden') {+ if (state === CaptureState.IDLE) {whenPermitted(() => {insert = null;enterCapture();@@ -283,12 +297,12 @@ function onShortcut(name: ShortcutName): void {});return;}- overlay.run(overlay.state === 'armed' ? 'start' : 'stop');+ overlay.run(state === CaptureState.ARMED ? 'start' : 'stop');return;}if (name === 'pauseResume') {- if (overlay.state === 'recording') overlay.run('pause');- else if (overlay.state === 'paused') overlay.run('resume');+ if (state === CaptureState.RECORDING) overlay.run('pause');+ else if (state === CaptureState.PAUSED) overlay.run('resume');return;}recorder?.captureNow(screen.getCursorScreenPoint());@@ -301,34 +315,41 @@ async function onOverlayCommand(command: OverlayCommand): Promise<void> {overlay?.refresh();return;}- if (command === 'mic:on' || command === 'mic:off') {- if (command === 'mic:off' || (await askMicrophone())) broadcastOverlay(command, guideId);+ if (command === 'narration:start' || command === 'narration:stop') {+ if (command === 'narration:stop' || (await askMicrophone())) broadcastState(command, currentGuideId);return;}- if (command === 'remove') {+ if (command === 'deleteStep') {const removed = steps.pop();- if (removed && guideId) {- await ask(mainWindow?.webContents ?? null, 'mimik:capture:removeStep', { guideId, stepId: removed.id }).catch(- () => undefined,- );+ if (removed && currentGuideId) {+ capture.send({ type: 'STEP_REMOVED' });+ await ask(mainWindow?.webContents ?? null, 'mimik:capture:deleteStep', {+ guideId: currentGuideId,+ stepId: removed.id,+ }).catch(() => undefined);}overlay?.showStep(steps.at(-1) ?? null);return;}- if (command === 'start' && !guideId) {+ if (command === 'start') {steps = [];overlay?.setAiFailure(null);+ currentGuideId = capture.getSnapshot().context.currentGuideId;try {- guideId = await ask<string>(mainWindow?.webContents ?? null, 'mimik:capture:startGuide', insert !== null);+ await ask(mainWindow?.webContents ?? null, 'mimik:capture:createGuide', {+ guideId: currentGuideId,+ staging: insert !== null,+ });} catch (error) {- overlay?.hide();+ currentGuideId = null;+ overlay?.reset();dialog.showErrorBox(mainI18n.t('desktop.cannotRecord'), error instanceof Error ? error.message : String(error));return;}const started = await recorder?.start();if (started && !started.ok) {- guideId = null;- overlay?.hide();+ currentGuideId = null;+ overlay?.reset();dialog.showErrorBox(mainI18n.t('desktop.cannotRecord'), started.detail);return;}@@ -336,31 +357,31 @@ async function onOverlayCommand(command: OverlayCommand): Promise<void> {recorder?.pause();} else if (command === 'resume') {recorder?.resume();- } else if (command === 'stop' || command === 'cancel') {+ } else if (command === 'stop') {recorder?.stop();await recorder?.drain();const target = insert;insert = null;- if (guideId && target) {+ if (currentGuideId && target) {await ask(mainWindow?.webContents ?? null,- 'mimik:capture:insertGuide',- { guideId, targetGuideId: target.guideId, atIndex: target.atIndex },+ 'mimik:capture:mergeGuideInto',+ { guideId: currentGuideId, targetGuideId: target.guideId, atIndex: target.atIndex },45_000,).catch(() => undefined);- if (command === 'stop' && steps.length > 0) finished = target.guideId;- } else {- if (command === 'stop') finished = guideId;- if (finished) {- void ask(mainWindow?.webContents ?? null, 'mimik:capture:finishGuide', finished, 45_000).catch(() => undefined);- }+ if (steps.length > 0) finished = target.guideId;+ } else if (currentGuideId) {+ finished = currentGuideId;+ void ask(mainWindow?.webContents ?? null, 'mimik:capture:finishGuide', finished, 45_000).catch(() => undefined);}- guideId = null;+ currentGuideId = null;+ } else if (command === 'disarm' || command === 'cancelEdit') {+ insert = null;}- broadcastOverlay(command, finished ?? guideId);+ broadcastState(command, finished ?? currentGuideId);applyShortcuts();refreshTray();- if (command === 'stop' || command === 'cancel') leaveCapture(Boolean(finished));+ if (command === 'stop' || command === 'disarm' || command === 'cancelEdit') leaveCapture(Boolean(finished));}let isQuitting = false;@@ -425,9 +446,11 @@ if (!app.requestSingleInstanceLock()) {const labelOf = (accelerator: string | null) =>accelerator ? shortcutLabel(accelerator, process.platform === 'darwin') : null;overlay = new CaptureOverlay(+ capture,(command) => void onOverlayCommand(command),() => (captureSettings ?? loadSettings()).captureMode,{+ insert: () => (insert ? { insertTargetGuideId: insert.guideId, insertAtIndex: insert.atIndex } : null),introFrame: async () => {const { captureMode } = captureSettings ?? loadSettings();const region = overlay?.region ?? { x: 0, y: 0, width: 0, height: 0 };@@ -448,8 +471,8 @@ if (!app.requestSingleInstanceLock()) {async (request) => {const reply = await ask<{ stepId?: string; title?: string; pending?: boolean }>(mainWindow?.webContents ?? null,- 'mimik:capture:step',- { ...request, guideId },+ 'mimik:capture:captureStep',+ { ...request, guideId: currentGuideId },).catch(() => undefined);if (reply?.stepId && reply.title) {const step: OverlayStep = {@@ -463,6 +486,7 @@ if (!app.requestSingleInstanceLock()) {app: request.elementMeta.app?.name ?? null,};steps.push(step);+ capture.send({ type: 'USER_ACTION' });describing = step.pending;overlay?.showStep(step);if (step.pending) overlay?.setProgress(95, 3500);@@ -513,6 +537,7 @@ if (!app.requestSingleInstanceLock()) {},);ipcMain.handle('mimik:capture:region', () => overlay?.region);+ ipcMain.handle('mimik:capture:getState', () => captureStateUpdate(null, currentGuideId));ipcMain.handle('mimik:capture:edit', (_event, target?: CaptureInsert) => {whenPermitted(() => {insert = target ?? null;diff --git a/apps/desktop/src/main/overlay/index.ts b/apps/desktop/src/main/overlay/index.tsindex b3382e1..0ddb8f8 100644--- a/apps/desktop/src/main/overlay/index.ts+++ b/apps/desktop/src/main/overlay/index.ts@@ -1,14 +1,21 @@import { join } from 'node:path';import type { AiFailureReason } from '@mimik/core/capture/ai/errors';+import {+ CaptureState,+ type CaptureStateValue,+ type captureMachine,+ type PauseReason,+} from '@mimik/core/capture/machine';import { app, BrowserWindow, ipcMain, screen } from 'electron';+import type { Actor } from 'xstate';import { clampToDisplays, loadRegion, type Region, saveRegion } from '../capture/region';import type { CaptureMode } from '../capture/settings';-export type OverlayState = 'hidden' | 'editing' | 'armed' | 'recording' | 'paused';+export type CaptureActor = Actor<typeof captureMachine>;export type OverlayCommand =- | 'edit'- | 'arm'- | 'cancel'+ | 'done'+ | 'cancelEdit'+ | 'disarm'| 'start'| 'pause'| 'resume'@@ -16,9 +23,9 @@ export type OverlayCommand =| 'mode:window'| 'mode:screen'| 'mode:region'- | 'remove'- | 'mic:on'- | 'mic:off'+ | 'deleteStep'+ | 'narration:start'+ | 'narration:stop'| 'intro:done';export interface OverlayStep {@@ -64,7 +71,8 @@ export interface OverlayPrint {}export interface OverlayView {- state: OverlayState;+ state: CaptureStateValue;+ pauseReason: PauseReason | null;region: Region;step: OverlayStep | null;mode: CaptureMode;@@ -79,6 +87,7 @@ export interface OverlayView {export interface OverlayOptions {introFrame?: () => Promise<Region>;+ insert?: () => { insertTargetGuideId: string; insertAtIndex: number } | null;shortcuts?: () => OverlayShortcuts;}@@ -144,7 +153,7 @@ export class CaptureOverlay {private anchor: { right: number; bottom: number } | null = null;private intro: BrowserWindow | null = null;private introDone: ((finished: boolean) => void) | null = null;- private current: OverlayState = 'hidden';+ private editing = false;private rect: Region;private step: OverlayStep | null = null;private size = { width: CONTROLS.width, height: CONTROLS.height };@@ -153,12 +162,12 @@ export class CaptureOverlay {private print: OverlayPrint = { src: null, aim: null };private aiFailure: OverlayAiFailure | null = null;private narration: OverlayNarration | null = null;- private editingFrom: OverlayState = 'hidden';private modeBeforeEdit: CaptureMode | null = null;private hiding: { shown: BrowserWindow[]; ready: Promise<unknown>; users: number } | null = null;private starting = false;constructor(+ private capture: CaptureActor,private onCommand: (command: OverlayCommand) => void,private mode: () => CaptureMode = () => 'region',private options: OverlayOptions = {},@@ -169,14 +178,19 @@ export class CaptureOverlay {ipcMain.on('mimik:overlay:setRegion', (_event, next: Region) => this.setRegion(next));ipcMain.on('mimik:overlay:command', (_event, command: OverlayCommand) => this.command(command));ipcMain.on('mimik:overlay:size', (_event, width: number, height: number) => this.resize(width, height));+ capture.subscribe(() => this.render());}get region(): Region {return this.rect;}- get state(): OverlayState {- return this.current;+ get state(): CaptureStateValue {+ return this.capture.getSnapshot().value;+ }++ get isEditing(): boolean {+ return this.editing;}private windows(): BrowserWindow[] {@@ -191,7 +205,8 @@ export class CaptureOverlay {private view(): OverlayView {return {- state: this.current,+ state: this.state,+ pauseReason: this.capture.getSnapshot().context.pauseReason,region: this.rect,step: this.step,mode: this.mode(),@@ -211,8 +226,7 @@ export class CaptureOverlay {}refresh(): void {- if (this.current !== 'hidden' && this.current !== 'editing') this.show(this.current);- else this.broadcast();+ this.render();}ignores(point: { x: number; y: number }): boolean {@@ -337,8 +351,7 @@ export class CaptureOverlay {}edit(): void {- if (this.current !== 'editing') this.editingFrom = this.current;- this.current = 'editing';+ this.editing = true;if (this.boundary && !this.boundary.isDestroyed()) this.boundary.hide();if (this.controls && !this.controls.isDestroyed()) this.controls.hide();this.closeEditors();@@ -354,9 +367,22 @@ export class CaptureOverlay {});}- private show(state: Exclude<OverlayState, 'hidden' | 'editing'>): void {+ private stopEditing(): void {+ this.editing = false;+ this.modeBeforeEdit = null;this.closeEditors();- this.current = state;+ }++ private render(): void {+ if (this.editing) {+ this.broadcast();+ return;+ }+ if (this.state === CaptureState.IDLE) {+ for (const win of this.windows()) win.hide();+ this.broadcast();+ return;+ }this.ensureBoundary();this.ensureControls();for (const win of this.windows()) {@@ -367,28 +393,22 @@ export class CaptureOverlay {}arm(): void {- this.show('armed');- }-- record(): void {- this.show('recording');- }-- pause(): void {- this.show('paused');+ this.stopEditing();+ if (this.state === CaptureState.IDLE) this.capture.send({ type: 'ARM' });+ else this.render();}private async begin(): Promise<void> {if (this.starting) return;this.starting = true;- this.show('armed');+ this.arm();const frame = await (this.options.introFrame?.() ?? Promise.resolve(this.displayUnderCursor())).catch(() =>this.displayUnderCursor(),);const finished = await this.playIntro(frame);this.starting = false;- if (!finished) return;- this.record();+ if (!finished || this.state !== CaptureState.ARMED) return;+ this.capture.send({ type: 'START_RECORDING', ...(this.options.insert?.() ?? {}) });this.onCommand('start');}@@ -420,13 +440,15 @@ export class CaptureOverlay {});}- hide(): void {+ reset(): void {this.introDone?.(false);this.starting = false;this.narration = null;- this.current = 'hidden';- this.closeEditors();- for (const win of this.windows()) win.hide();+ this.step = null;+ this.stopEditing();+ if (this.state === CaptureState.ARMED) this.capture.send({ type: 'DISARM' });+ else if (this.state !== CaptureState.IDLE) this.capture.send({ type: 'STOP_RECORDING' });+ this.render();}run(command: OverlayCommand): void {@@ -434,25 +456,31 @@ export class CaptureOverlay {}private command(command: OverlayCommand): void {+ const state = this.state;if (command.startsWith('mode:')) {const before = this.mode();this.onCommand(command);- if (command === 'mode:region' && this.current === 'paused') {- this.modeBeforeEdit = before;+ if (command === 'mode:region' && state === CaptureState.PAUSED && !this.editing) {this.edit();+ this.modeBeforeEdit = before;}return;}- const recording = this.editingFrom === 'recording' || this.editingFrom === 'paused';- if (this.current === 'editing' && recording && (command === 'arm' || command === 'cancel')) {- if (command === 'cancel' && this.modeBeforeEdit) this.onCommand(`mode:${this.modeBeforeEdit}`);- this.modeBeforeEdit = null;- if (this.editingFrom === 'recording') this.record();- else if (command === 'cancel') this.pause();- else {- this.record();- this.onCommand('resume');+ if (command === 'done') {+ if (state === CaptureState.PAUSED) this.command('resume');+ else this.arm();+ return;+ }+ if (command === 'cancelEdit') {+ const restore = this.modeBeforeEdit;+ this.stopEditing();+ if (state === CaptureState.PAUSED) {+ if (restore) this.onCommand(`mode:${restore}`);+ this.render();+ return;}+ this.reset();+ this.onCommand(command);return;}if (command === 'intro:done') {@@ -463,25 +491,33 @@ export class CaptureOverlay {void this.begin();return;}- if (command === 'remove') {+ if (command === 'deleteStep') {if (!this.busy) this.onCommand(command);return;}- if (command === 'mic:on' || command === 'mic:off') {+ if (command === 'narration:start' || command === 'narration:stop') {this.onCommand(command);return;}- if (this.starting && command !== 'cancel' && command !== 'stop') return;- if (command === 'edit') this.edit();- else if (command === 'arm') this.arm();- else if (command === 'resume') this.record();- else if (command === 'pause') this.pause();- else {- this.step = null;- this.hide();+ if (command === 'disarm' || (command === 'stop' && state === CaptureState.ARMED)) {+ this.reset();+ this.onCommand('disarm');+ return;+ }+ if (this.starting) return;+ if (command === 'pause' && state === CaptureState.RECORDING) {+ const area = this.mode() === 'region';+ this.capture.send({ type: 'PAUSE_CAPTURE', reason: area ? 'area' : 'manual' });+ this.onCommand(command);+ if (area) this.edit();+ } else if (command === 'resume' && state === CaptureState.PAUSED) {+ this.stopEditing();+ this.capture.send({ type: 'RESUME_CAPTURE' });+ this.onCommand(command);+ } else if (command === 'stop' && state !== CaptureState.IDLE) {+ this.reset();+ this.onCommand(command);}- this.onCommand(command);- if (command === 'pause' && this.mode() === 'region') this.edit();}async withHidden<T>(fn: () => Promise<T>): Promise<T> {@@ -516,7 +552,7 @@ export class CaptureOverlay {for (const win of [this.boundary, this.controls]) if (win && !win.isDestroyed()) win.destroy();this.boundary = null;this.controls = null;- this.current = 'hidden';+ this.editing = false;for (const channel of ['mimik:overlay:region', 'mimik:overlay:view']) ipcMain.removeHandler(channel);ipcMain.removeAllListeners('mimik:overlay:setRegion');ipcMain.removeAllListeners('mimik:overlay:command');diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex e5e7dcb..8685b9a 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -1,9 +1,17 @@import { contextBridge, ipcRenderer } from 'electron';import type { CaptureInsert } from '../main/capture/insert';import type { CaptureSettings } from '../main/capture/settings';-import type { OverlayAiFailure, OverlayNarration } from '../main/overlay';+import type { OverlayAiFailure, OverlayCommand, OverlayNarration } from '../main/overlay';import type { CapturePermissions, MicrophoneAccess, PermissionKind } from '../main/permissions';+export interface CaptureStateUpdate {+ command: OverlayCommand | null;+ state: string;+ pauseReason: string | null;+ currentGuideId: string | null;+ stepCount: number;+}+interface Region {x: number;y: number;@@ -32,12 +40,9 @@ const api = {onOpenSheet: (handler: () => void): void => {ipcRenderer.on('mimik:capture:openSheet', () => handler());},- onCommand: (handler: (command: string, state: string, region: Region, guideId: string | null) => void): void => {- ipcRenderer.on(- 'mimik:capture:command',- (_event, command: string, state: string, region: Region, guideId: string | null) =>- handler(command, state, region, guideId),- );+ getState: (): Promise<CaptureStateUpdate> => ipcRenderer.invoke('mimik:capture:getState'),+ onStateUpdate: (handler: (update: CaptureStateUpdate) => void): void => {+ ipcRenderer.on('mimik:capture:stateUpdate', (_event, update: CaptureStateUpdate) => handler(update));},},microphone: {diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsxindex 76a44d1..eec8ef1 100644--- a/apps/desktop/src/renderer/App.tsx+++ b/apps/desktop/src/renderer/App.tsx@@ -64,7 +64,7 @@ export function App() {}, []);useEffect(() => {- window.mimik.capture.onCommand((command, _state, _region, id) => {+ window.mimik.capture.onStateUpdate(({ command, currentGuideId: id }) => {if (command !== 'stop' || !id) return;setSettingsOpen(false);setSheet(null);diff --git a/apps/desktop/src/renderer/capture-host.ts b/apps/desktop/src/renderer/capture-host.tsindex a0fb653..d6dd5d2 100644--- a/apps/desktop/src/renderer/capture-host.ts+++ b/apps/desktop/src/renderer/capture-host.ts@@ -1,5 +1,6 @@import { resolveGuideMetaInputs } from '@mimik/core/capture/ai/guide-description';import { settleDescriptions } from '@mimik/core/capture/ai/settle-descriptions';+import { CaptureState } from '@mimik/core/capture/machine';import type { CaptureStepData } from '@mimik/core/capture/sink';import { i18n, localStorage } from '@mimik/core/env';import { getMostCommonApp } from '@mimik/core/guides/most-common-app';@@ -22,19 +23,23 @@ const sink = new DesktopCaptureSink(narration);allScreenshotIds().then((ids) => window.mimik.screenshots.sweep(ids));-window.mimik.onRequest('mimik:capture:startGuide', (payload) => sink.startGuide(payload === true));-window.mimik.onRequest('mimik:capture:step', (payload) => sink.captureStep(payload as CaptureStepData));+window.mimik.onRequest('mimik:capture:createGuide', (payload) =>+ sink.createGuide(payload as { guideId?: string; staging?: boolean }),+);+window.mimik.onRequest('mimik:capture:captureStep', (payload) => sink.captureStep(payload as CaptureStepData));-window.mimik.capture.onCommand(async (command, state, _region, id) => {- if (command === 'mic:on' || command === 'mic:off') await localStorage.set({ voiceEnabled: command === 'mic:on' });- if (!id) return;- if (command === 'start' || command === 'resume' || (command === 'mic:on' && state === 'recording')) {- narration.listen(id);- } else if (command === 'pause' || command === 'mic:off') narration.cut();- else if (command === 'cancel') narration.abort();+window.mimik.capture.onStateUpdate(async ({ command, state, currentGuideId }) => {+ if (command === 'narration:start' || command === 'narration:stop') {+ await localStorage.set({ voiceEnabled: command === 'narration:start' });+ }+ if (!currentGuideId) return;+ const recording = state === CaptureState.RECORDING;+ if (command === 'start' || command === 'resume' || (command === 'narration:start' && recording)) {+ narration.listen(currentGuideId);+ } else if (command === 'pause' || command === 'narration:stop') narration.cut();});-window.mimik.onRequest('mimik:capture:removeStep', async (payload) => {+window.mimik.onRequest('mimik:capture:deleteStep', async (payload) => {const { guideId, stepId } = payload as { guideId: string; stepId: string };await deleteStep(guideId, stepId);return true;@@ -59,7 +64,7 @@ window.mimik.onRequest('mimik:capture:finishGuide', async (payload) => {return true;});-window.mimik.onRequest('mimik:capture:insertGuide', async (payload) => {+window.mimik.onRequest('mimik:capture:mergeGuideInto', async (payload) => {const { guideId, targetGuideId, atIndex } = payload as { guideId: string; targetGuideId: string; atIndex: number };await narration.finish();await settleDescriptions(guideId);diff --git a/apps/desktop/src/renderer/capture-sink.ts b/apps/desktop/src/renderer/capture-sink.tsindex 5034b29..bd4fb45 100644--- a/apps/desktop/src/renderer/capture-sink.ts+++ b/apps/desktop/src/renderer/capture-sink.ts@@ -33,8 +33,14 @@ export type DesktopCaptureStepData = CaptureStepData & {export class DesktopCaptureSink implements CaptureSink {constructor(private readonly narration?: DesktopNarration) {}- async startGuide(staging = false): Promise<string> {- const guide = await createGuide(crypto.randomUUID(), staging);+ async createGuide({+ guideId,+ staging = false,+ }: {+ guideId?: string | null;+ staging?: boolean;+ } = {}): Promise<string> {+ const guide = await createGuide(guideId ?? crypto.randomUUID(), staging);return guide.id;}diff --git a/apps/desktop/src/renderer/check-pipeline.ts b/apps/desktop/src/renderer/check-pipeline.tsindex 0d667de..b595fd1 100644--- a/apps/desktop/src/renderer/check-pipeline.ts+++ b/apps/desktop/src/renderer/check-pipeline.ts@@ -20,8 +20,8 @@ interface CheckResult {const sink = new DesktopCaptureSink();-window.mimik.onRequest('mimik:capture:startGuide', () => sink.startGuide());-window.mimik.onRequest('mimik:capture:step', (payload) => sink.captureStep(payload as CaptureStepData));+window.mimik.onRequest('mimik:capture:createGuide', () => sink.createGuide());+window.mimik.onRequest('mimik:capture:captureStep', (payload) => sink.captureStep(payload as CaptureStepData));window.mimik.onRequest('mimik:check:screenshotSrc', async (payload) => {const found = await getGuide(payload as string);diff --git a/apps/desktop/src/renderer/overlay.css b/apps/desktop/src/renderer/overlay.cssindex fce3ccf..bdf242b 100644--- a/apps/desktop/src/renderer/overlay.css+++ b/apps/desktop/src/renderer/overlay.css@@ -217,12 +217,12 @@ body.boundary #frame {border-radius: 2px;}-body.boundary[data-state='paused'] #frame {+body.boundary[data-state='PAUSED'] #frame {border-style: dashed;border-color: var(--muted);}-body.boundary[data-state='armed'] #frame {+body.boundary[data-state='ARMED'] #frame {border-style: dashed;}@@ -277,13 +277,13 @@ body.controls #dot {background: #9ca3af;}-body.controls[data-state='recording'] #dot {+body.controls[data-state='RECORDING'] #dot {background: #dc2626;box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.18);animation: blink 1.6s ease-in-out infinite;}-body.controls.collapsed[data-state='recording'] #dot {+body.controls.collapsed[data-state='RECORDING'] #dot {background: #f87171;}@@ -377,7 +377,7 @@ body.controls #veil {background: rgba(238, 242, 255, 0.72);}-body.controls[data-state='paused'] #veil {+body.controls[data-state='PAUSED'] #veil {background: rgba(255, 255, 255, 0.55);}diff --git a/apps/desktop/src/renderer/overlay/controls.ts b/apps/desktop/src/renderer/overlay/controls.tsindex cc930c3..b99e80e 100644--- a/apps/desktop/src/renderer/overlay/controls.ts+++ b/apps/desktop/src/renderer/overlay/controls.ts@@ -165,9 +165,9 @@ export function controls(): void {const render = (view: OverlayView) => {const { state, step, busy, progress, print, starting, mode, shortcuts, aiFailure, narration } = view;- const armed = state === 'armed';- const recording = state === 'recording';- const paused = state === 'paused';+ const armed = state === 'ARMED';+ const recording = state === 'RECORDING';+ const paused = state === 'PAUSED';const waiting = recording && !step && !busy;const resting = paused && !step && !busy;@@ -311,7 +311,7 @@ export function controls(): void {primary.replaceChildren(icon(armed ? 'video' : 'check'));primary.append(i18n.t(armed ? 'desktop_startButton' : 'desktop_finish'));}- secondary.dataset.command = armed ? 'cancel' : recording ? 'pause' : 'resume';+ secondary.dataset.command = armed ? 'disarm' : recording ? 'pause' : 'resume';primary.dataset.command = armed ? 'start' : 'stop';primary.disabled = starting || (busy && !armed);foot.hidden = collapsed;@@ -362,10 +362,10 @@ export function controls(): void {}primary.addEventListener('click', () => window.mimikOverlay.command(primary.dataset.command ?? 'start'));- secondary.addEventListener('click', () => window.mimikOverlay.command(secondary.dataset.command ?? 'cancel'));- remove.addEventListener('click', () => window.mimikOverlay.command('remove'));+ secondary.addEventListener('click', () => window.mimikOverlay.command(secondary.dataset.command ?? 'disarm'));+ remove.addEventListener('click', () => window.mimikOverlay.command('deleteStep'));mic.addEventListener('click', () => {- if (shownMic !== 'locked') window.mimikOverlay.command(micOn ? 'mic:off' : 'mic:on');+ if (shownMic !== 'locked') window.mimikOverlay.command(micOn ? 'narration:stop' : 'narration:start');});const readMic = () =>localStorage.get([...VOICE_KEY_SETTINGS, 'voiceEnabled']).then((stored) => {diff --git a/apps/desktop/src/renderer/overlay/editor.ts b/apps/desktop/src/renderer/overlay/editor.tsindex c149c3f..4c6f744 100644--- a/apps/desktop/src/renderer/overlay/editor.ts+++ b/apps/desktop/src/renderer/overlay/editor.ts@@ -42,8 +42,8 @@ export function editor(origin: { x: number; y: number }): void {i18n.t('annotationEditor_done'),el('kbd', {}, 'Enter'),);- cancel.addEventListener('click', () => window.mimikOverlay.command('cancel'));- done.addEventListener('click', () => window.mimikOverlay.command('arm'));+ cancel.addEventListener('click', () => window.mimikOverlay.command('cancelEdit'));+ done.addEventListener('click', () => window.mimikOverlay.command('done'));const bar = el('div',{ id: 'bar' },@@ -115,8 +115,8 @@ export function editor(origin: { x: number; y: number }): void {});window.addEventListener('keydown', (event) => {- if (event.key === 'Enter') window.mimikOverlay.command('arm');- if (event.key === 'Escape') window.mimikOverlay.command('cancel');+ if (event.key === 'Enter') window.mimikOverlay.command('done');+ if (event.key === 'Escape') window.mimikOverlay.command('cancelEdit');});window.mimikOverlay.region().then((current) => {