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 πŸ“–

refactor: restructure project with hybrid architecture

Luis Ortiz6dbda8b6a400
diff --git a/.gitignore b/.gitignore
index 0469ec4..a48174c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,3 +3,5 @@ node_modules/
.wxt/
dist/
.planning/
+docs/
+.source/
diff --git a/entrypoints/background.ts b/entrypoints/background.ts
deleted file mode 100644
index 676b434..0000000
--- a/entrypoints/background.ts
+++ /dev/null
@@ -1,345 +0,0 @@
-import { defineBackground } from 'wxt/utils/define-background';
-import { createActor } from 'xstate';
-import { captureMachine } from '../src/background/machine';
-import { captureAnnotated } from '../src/background/screenshot';
-import { buildFallbackDescription } from '../src/background/step-description';
-import { getAIDescription } from '../src/background/ai-description';
-import { db } from '../src/shared/db-schema';
-
-export default defineBackground(() => {
- chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
-
- let actorReadyResolve!: () => void;
- const actorReady = new Promise<void>(resolve => {
- actorReadyResolve = resolve;
- });
-
- let actor: ReturnType<typeof createActor<typeof captureMachine>>;
-
- async function startActor() {
- try {
- const result = await chrome.storage.session.get('machineSnapshot');
- const snapshot = result.machineSnapshot ?? undefined;
- actor = createActor(captureMachine, { snapshot });
- actor.start();
- } catch (err) {
- console.warn('[Mimik] Failed to restore snapshot, starting fresh', err);
- await chrome.storage.session.remove('machineSnapshot');
- actor = createActor(captureMachine);
- actor.start();
- }
-
- actor.subscribe(() => {
- const persisted = actor.getPersistedSnapshot();
- chrome.storage.session.set({ machineSnapshot: persisted });
- });
-
- actorReadyResolve();
- }
-
- startActor().catch((err) => {
- console.error('[Mimik] startActor failed', err);
- actor = createActor(captureMachine);
- actor.start();
- actorReadyResolve();
- });
-
- let captureQueue: Promise<void> = Promise.resolve();
-
- function enqueueCaptureStep(fn: () => Promise<void>): void {
- captureQueue = captureQueue.then(fn).catch(err =>
- console.error('[Mimik] Capture error', err)
- );
- }
-
- function isInjectableTab(tab: chrome.tabs.Tab): boolean {
- const url = tab.url || tab.pendingUrl || '';
- if (!url || url.startsWith('chrome://') || url.startsWith('chrome-extension://') ||
- url.startsWith('chrome.google.com/webstore') || url.startsWith('about:')) return false;
- return /^https?:/.test(url);
- }
-
- async function injectContentScript(tabId: number): Promise<void> {
- try {
- await chrome.tabs.sendMessage(tabId, { type: 'PING' });
- } catch {
- try {
- await chrome.scripting.executeScript({
- target: { tabId, allFrames: true },
- files: ['content-scripts/content.js'],
- });
- } catch (err) {
- }
- }
- }
-
- async function injectAllTabs(): Promise<void> {
- try {
- const windows = await chrome.windows.getAll({ populate: true });
- for (const win of windows) {
- for (const tab of win.tabs || []) {
- if (tab.id && isInjectableTab(tab)) {
- injectContentScript(tab.id);
- }
- }
- }
- } catch (err) {
- console.warn('[Mimik] injectAllTabs failed', err);
- }
- }
-
- async function broadcastStartCapture(guideId: string): Promise<void> {
- try {
- const tabs = await chrome.tabs.query({});
- for (const tab of tabs) {
- if (tab.id && isInjectableTab(tab)) {
- chrome.tabs.sendMessage(tab.id, { type: 'START_CAPTURE', guideId }).catch(() => {});
- }
- }
- } catch (err) {
- console.warn('[Mimik] broadcastStartCapture failed', err);
- }
- }
-
- async function broadcastStopCapture(): Promise<void> {
- try {
- const tabs = await chrome.tabs.query({});
- for (const tab of tabs) {
- if (tab.id) {
- chrome.tabs.sendMessage(tab.id, { type: 'STOP_CAPTURE' }).catch(() => {});
- }
- }
- } catch (err) {
- console.warn('[Mimik] broadcastStopCapture failed', err);
- }
- }
-
- injectAllTabs();
-
- chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
- if (msg.type === 'PING') {
- sendResponse({ alive: true });
- return true;
- }
-
- if (msg.type === 'GET_STATE') {
- (async () => {
- try {
- await actorReady;
- const snap = actor.getSnapshot();
- sendResponse({
- state: snap.value ?? 'unknown',
- stepCount: snap.context.stepCount,
- currentGuideId: snap.context.currentGuideId,
- });
- } catch (err) {
- console.error('[Mimik] GET_STATE failed', err);
- sendResponse({ state: 'unknown' });
- }
- })();
- return true;
- }
-
- if (msg.type === 'START_RECORDING') {
- (async () => {
- try {
- await actorReady;
- actor.send({ type: 'START_RECORDING', url: msg.url });
-
- const guideId = actor.getSnapshot().context.currentGuideId!;
-
- await db.guides.add({
- id: guideId,
- title: 'Untitled Guide',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- stepIds: [],
- starred: false,
- deletedAt: null,
- });
-
- await broadcastStartCapture(guideId);
-
- sendResponse({ guideId });
- } catch (err) {
- console.error('[Mimik] START_RECORDING failed', err);
- sendResponse({ error: String(err) });
- }
- })();
- return true;
- }
-
- if (msg.type === 'STOP_RECORDING') {
- (async () => {
- try {
- await actorReady;
-
- const guideId = actor.getSnapshot().context.currentGuideId;
-
- await broadcastStopCapture();
-
- actor.send({ type: 'STOP_RECORDING' });
- sendResponse({ success: true, guideId });
- } catch (err) {
- console.error('[Mimik] STOP_RECORDING failed', err);
- sendResponse({ error: String(err) });
- }
- })();
- return true;
- }
-
- if (msg.type === 'USER_ACTION') {
- (async () => {
- await actorReady;
-
- const snap = actor.getSnapshot();
- if (snap.value !== 'recording') {
- sendResponse({ ignored: true });
- return;
- }
-
- const stepIndex = actor.getSnapshot().context.stepCount;
- actor.send({ type: 'USER_ACTION' });
- const guideId = snap.context.currentGuideId!;
- const stepId = crypto.randomUUID();
- const tabId = sender.tab?.id;
-
- if (!tabId) {
- sendResponse({ error: 'no tabId' });
- return;
- }
-
- sendResponse({ stepId });
-
- enqueueCaptureStep(async () => {
- const fallbackDescription = buildFallbackDescription(msg.action, msg.elementMeta);
- const currentUrl = snap.context.currentUrl;
-
- let screenshotId: string | undefined;
- let screenshotBlob: Blob | undefined;
- try {
- const screenshot = await captureAnnotated(tabId, stepId, msg.elementMeta);
- screenshotId = screenshot.id;
- screenshotBlob = screenshot.blob;
- } catch (err) {
- console.warn('[Mimik] Screenshot capture failed, storing step without screenshot', err);
- }
-
- await db.steps.add({
- id: stepId,
- guideId,
- index: stepIndex,
- description: fallbackDescription,
- action: msg.action,
- url: currentUrl,
- timestamp: Date.now(),
- screenshotId,
- });
-
- const guide = await db.guides.get(guideId);
- if (guide) {
- await db.guides.update(guideId, {
- stepIds: [...guide.stepIds, stepId],
- updatedAt: Date.now(),
- });
- }
-
- if (screenshotBlob) {
- (async () => {
- try {
- const settings = await chrome.storage.local.get(['aiApiKey', 'aiProvider']);
- if (settings.aiApiKey) {
- const provider = (settings.aiProvider as 'openai' | 'anthropic') || 'openai';
- const aiDescription = await getAIDescription(
- screenshotBlob,
- msg.action,
- msg.elementMeta,
- provider,
- settings.aiApiKey
- );
- if (aiDescription) {
- await db.steps.update(stepId, { description: aiDescription });
- }
- }
- } catch (err) {
- console.error('[Mimik] AI description update failed', err);
- }
- })();
- }
- });
- })();
- return true;
- }
-
- if (msg.type === 'RRWEB_CHUNK') {
- (async () => {
- await db.rrwebEvents.add({
- id: crypto.randomUUID(),
- guideId: msg.guideId,
- events: msg.events,
- timestamp: msg.timestamp,
- });
- sendResponse({ stored: true });
- })();
- return true;
- }
-
- return false;
- });
-
- chrome.webNavigation.onCompleted.addListener(async (details) => {
- if (details.frameId !== 0) return;
- await actorReady;
- const state = actor.getSnapshot();
- if (state.value === 'recording') {
- actor.send({ type: 'SPA_NAVIGATE', url: details.url });
- }
- });
-
- chrome.webNavigation.onHistoryStateUpdated.addListener(async (details) => {
- if (details.frameId !== 0) return;
- await actorReady;
- const state = actor.getSnapshot();
- if (state.value === 'recording') {
- actor.send({ type: 'SPA_NAVIGATE', url: details.url });
- }
- });
-
- chrome.tabs.onActivated.addListener(async (activeInfo) => {
- await actorReady;
- const state = actor.getSnapshot();
- if (state.value !== 'recording') return;
-
- const guideId = state.context.currentGuideId;
- if (!guideId) return;
-
- try {
- await chrome.tabs.sendMessage(activeInfo.tabId, { type: 'PING' });
- } catch {
- try {
- const tab = await chrome.tabs.get(activeInfo.tabId);
- if (isInjectableTab(tab)) {
- await injectContentScript(activeInfo.tabId);
- }
- } catch {
- }
- }
- });
-
- chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
- if (changeInfo.status !== 'complete') return;
- await actorReady;
- const state = actor.getSnapshot();
- if (state.value !== 'recording') return;
- if (!isInjectableTab(tab)) return;
-
- try {
- await chrome.tabs.sendMessage(tabId, { type: 'PING' });
- } catch {
- try {
- await injectContentScript(tabId);
- } catch {
- }
- }
- });
-});
diff --git a/src/background/ai-description.ts b/src/capture/ai-description.ts
similarity index 97%
rename from src/background/ai-description.ts
rename to src/capture/ai-description.ts
index 61e2f5a..7971942 100644
--- a/src/background/ai-description.ts
+++ b/src/capture/ai-description.ts
@@ -1,5 +1,5 @@
import OpenAI from 'openai';
-import type { ElementMeta } from '../shared/types';
+import type { ElementMeta } from '@/guides/types';
export async function getAIDescription(
blob: Blob,
diff --git a/src/content/element-meta.ts b/src/capture/element-meta.ts
similarity index 95%
rename from src/content/element-meta.ts
rename to src/capture/element-meta.ts
index c4ca16e..817c0ca 100644
--- a/src/content/element-meta.ts
+++ b/src/capture/element-meta.ts
@@ -1,5 +1,5 @@
import { getCssSelector } from 'css-selector-generator';
-import type { ElementMeta } from '../shared/types';
+import type { ElementMeta } from '@/guides/types';
export function extractElementMeta(el: HTMLElement): ElementMeta {
const rect = el.getBoundingClientRect();
diff --git a/src/content/events.ts b/src/capture/events.ts
similarity index 98%
rename from src/content/events.ts
rename to src/capture/events.ts
index 158dadb..b2aa250 100644
--- a/src/content/events.ts
+++ b/src/capture/events.ts
@@ -1,3 +1,4 @@
+import { sendMessage } from '@/lib/messaging';
import { extractElementMeta } from './element-meta';
const FOCUSABLE_SELECTOR = 'a[href], button, input, select, textarea, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="checkbox"], [role="radio"], [tabindex], [contenteditable="true"]';
@@ -144,16 +145,8 @@ export function startCapture(guideId: string): () => void {
}
function sendAction(action: string, meta: ReturnType<typeof extractElementMeta>) {
- try {
- chrome.runtime.sendMessage({
- type: 'USER_ACTION',
- guideId,
- action,
- elementMeta: meta,
- });
- } catch (err) {
- console.warn('[Mimik] Failed to send action', err);
- }
+ sendMessage('userAction', { guideId, action, elementMeta: meta })
+ .catch(err => console.warn('[Mimik] Failed to send action', err));
}
function resetWindow() {
diff --git a/src/background/machine.ts b/src/capture/machine.ts
similarity index 100%
rename from src/background/machine.ts
rename to src/capture/machine.ts
diff --git a/src/content/rrweb-recorder.ts b/src/capture/rrweb-recorder.ts
similarity index 84%
rename from src/content/rrweb-recorder.ts
rename to src/capture/rrweb-recorder.ts
index 236f826..7317b68 100644
--- a/src/content/rrweb-recorder.ts
+++ b/src/capture/rrweb-recorder.ts
@@ -1,3 +1,4 @@
+import { sendMessage } from '@/lib/messaging';
// @ts-expect-error rrweb 1.1.3 type resolution
import { record } from 'rrweb';
@@ -10,12 +11,8 @@ export function startRrwebRecording(guideId: string): () => void {
function flushChunk() {
if (eventBuffer.length === 0) return;
const chunk = eventBuffer.splice(0);
- chrome.runtime.sendMessage({
- type: 'RRWEB_CHUNK',
- guideId,
- events: chunk,
- timestamp: Date.now(),
- });
+ sendMessage('rrwebChunk', { guideId, events: chunk, timestamp: Date.now() })
+ .catch(() => {});
}
const stopRecord = record({
diff --git a/src/background/screenshot.ts b/src/capture/screenshot.ts
similarity index 78%
rename from src/background/screenshot.ts
rename to src/capture/screenshot.ts
index 5f31886..5af311a 100644
--- a/src/background/screenshot.ts
+++ b/src/capture/screenshot.ts
@@ -1,8 +1,9 @@
-import { db } from '../shared/db-schema';
-import type { Screenshot, ElementMeta } from '../shared/types';
+import { captureVisibleTab } from '@/lib/browser-api';
+import { db } from '@/guides/db';
+import type { Screenshot, ElementMeta } from '@/guides/types';
export async function captureAndStore(tabId: number, stepId: string): Promise<Screenshot> {
- const dataUrl = await chrome.tabs.captureVisibleTab(null, { format: 'jpeg', quality: 90 });
+ const dataUrl = await captureVisibleTab('jpeg', 90);
const blob = await fetch(dataUrl).then(r => r.blob());
const screenshot: Screenshot = {
id: crypto.randomUUID(), stepId, blob, mimeType: 'image/jpeg', width: 0, height: 0,
@@ -20,10 +21,7 @@ export async function captureAnnotated(
stepId: string,
elementMeta: ElementMeta
): Promise<Screenshot> {
- const dataUrl = await chrome.tabs.captureVisibleTab(null, {
- format: 'jpeg',
- quality: 90,
- });
+ const dataUrl = await captureVisibleTab('jpeg', 90);
const blob = await fetch(dataUrl).then(r => r.blob());
const img = await createImageBitmap(blob);
diff --git a/src/content/spa-nav.ts b/src/capture/spa-nav.ts
similarity index 100%
rename from src/content/spa-nav.ts
rename to src/capture/spa-nav.ts
diff --git a/src/background/step-description.ts b/src/capture/step-description.ts
similarity index 95%
rename from src/background/step-description.ts
rename to src/capture/step-description.ts
index 7864ccc..2b687cb 100644
--- a/src/background/step-description.ts
+++ b/src/capture/step-description.ts
@@ -1,4 +1,4 @@
-import type { ElementMeta } from '../shared/types';
+import type { ElementMeta } from '@/guides/types';
export function buildFallbackDescription(action: string, meta: ElementMeta): string {
const target = meta.ariaLabel
diff --git a/src/entrypoints/background/actor.ts b/src/entrypoints/background/actor.ts
new file mode 100644
index 0000000..f2fa982
--- /dev/null
+++ b/src/entrypoints/background/actor.ts
@@ -0,0 +1,45 @@
+import { sessionStorage } from '@/lib/browser-api';
+import { createActor } from 'xstate';
+import { captureMachine } from '@/capture/machine';
+import type { ActorRef } from './types';
+
+const STORAGE_KEY = 'machineSnapshot';
+
+let actor: ActorRef;
+let readyResolve!: () => void;
+
+export const ready = new Promise<void>((resolve) => {
+ readyResolve = resolve;
+});
+
+export function getActor(): ActorRef {
+ return actor;
+}
+
+export async function initActor(): Promise<void> {
+ try {
+ const result = await sessionStorage.get(STORAGE_KEY);
+ const snapshot = result[STORAGE_KEY] ?? undefined;
+ actor = createActor(captureMachine, { snapshot });
+ actor.start();
+ } catch (err) {
+ console.warn('[Mimik] Failed to restore snapshot, starting fresh', err);
+ await sessionStorage.remove(STORAGE_KEY);
+ actor = createActor(captureMachine);
+ actor.start();
+ }
+
+ actor.subscribe(() => {
+ const persisted = actor.getPersistedSnapshot();
+ sessionStorage.set({ [STORAGE_KEY]: persisted });
+ });
+
+ readyResolve();
+}
+
+export function initActorFallback(): void {
+ console.error('[Mimik] initActor failed, starting fresh');
+ actor = createActor(captureMachine);
+ actor.start();
+ readyResolve();
+}
diff --git a/src/entrypoints/background/index.ts b/src/entrypoints/background/index.ts
new file mode 100644
index 0000000..8efd05e
--- /dev/null
+++ b/src/entrypoints/background/index.ts
@@ -0,0 +1,74 @@
+import { defineBackground } from '#imports';
+import { setSidePanelBehavior } from '@/lib/browser-api';
+import { onMessage } from '@/lib/messaging';
+import { db } from '@/guides/db';
+import { initActor, initActorFallback, getActor, ready } from './actor';
+import { injectAllTabs, broadcastStartCapture, broadcastStopCapture } from './tab-manager';
+import { handleUserAction } from './step-pipeline';
+import { registerNavigationListeners } from './navigation';
+
+export default defineBackground(() => {
+ setSidePanelBehavior(true);
+
+ initActor().catch(initActorFallback);
+ injectAllTabs();
+ registerNavigationListeners();
+
+ onMessage('ping', () => {
+ return { alive: true };
+ });
+
+ onMessage('getState', async () => {
+ await ready;
+ const snap = getActor().getSnapshot();
+ return {
+ state: (snap.value as string) ?? 'unknown',
+ stepCount: snap.context.stepCount,
+ currentGuideId: snap.context.currentGuideId,
+ };
+ });
+
+ onMessage('startRecording', async ({ data }) => {
+ await ready;
+ const actor = getActor();
+ actor.send({ type: 'START_RECORDING', url: data.url });
+ const guideId = actor.getSnapshot().context.currentGuideId!;
+
+ await db.guides.add({
+ id: guideId,
+ title: 'Untitled Guide',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ stepIds: [],
+ starred: false,
+ deletedAt: null,
+ });
+
+ await broadcastStartCapture(guideId);
+ return { guideId };
+ });
+
+ onMessage('stopRecording', async () => {
+ await ready;
+ const actor = getActor();
+ const guideId = actor.getSnapshot().context.currentGuideId;
+ await broadcastStopCapture();
+ actor.send({ type: 'STOP_RECORDING' });
+ return { success: true, guideId: guideId ?? undefined };
+ });
+
+ onMessage('userAction', async (message) => {
+ await ready;
+ return handleUserAction(message.data, message.sender);
+ });
+
+ onMessage('rrwebChunk', async ({ data }) => {
+ await db.rrwebEvents.add({
+ id: crypto.randomUUID(),
+ guideId: data.guideId,
+ events: data.events,
+ timestamp: data.timestamp,
+ });
+ return { stored: true };
+ });
+});
diff --git a/src/entrypoints/background/navigation.ts b/src/entrypoints/background/navigation.ts
new file mode 100644
index 0000000..ce4ecac
--- /dev/null
+++ b/src/entrypoints/background/navigation.ts
@@ -0,0 +1,59 @@
+import { onNavigationCompleted, onHistoryStateUpdated, onTabActivated, onTabUpdated, sendMessageToTab, getTab } from '@/lib/browser-api';
+import { isInjectableTab, injectContentScript } from './tab-manager';
+import { getActor, ready } from './actor';
+
+export function registerNavigationListeners() {
+ onNavigationCompleted(async (details) => {
+ if (details.frameId !== 0) return;
+ await ready;
+ const state = getActor().getSnapshot();
+ if (state.value === 'recording') {
+ getActor().send({ type: 'SPA_NAVIGATE', url: details.url });
+ }
+ });
+
+ onHistoryStateUpdated(async (details) => {
+ if (details.frameId !== 0) return;
+ await ready;
+ const state = getActor().getSnapshot();
+ if (state.value === 'recording') {
+ getActor().send({ type: 'SPA_NAVIGATE', url: details.url });
+ }
+ });
+
+ onTabActivated(async (activeInfo) => {
+ await ready;
+ const state = getActor().getSnapshot();
+ if (state.value !== 'recording') return;
+ if (!state.context.currentGuideId) return;
+
+ try {
+ await sendMessageToTab(activeInfo.tabId, { type: 'PING' });
+ } catch {
+ try {
+ const tab = await getTab(activeInfo.tabId);
+ if (isInjectableTab(tab)) {
+ await injectContentScript(activeInfo.tabId);
+ }
+ } catch {
+ }
+ }
+ });
+
+ onTabUpdated(async (tabId, changeInfo, tab) => {
+ if (changeInfo.status !== 'complete') return;
+ await ready;
+ const state = getActor().getSnapshot();
+ if (state.value !== 'recording') return;
+ if (!isInjectableTab(tab)) return;
+
+ try {
+ await sendMessageToTab(tabId, { type: 'PING' });
+ } catch {
+ try {
+ await injectContentScript(tabId);
+ } catch {
+ }
+ }
+ });
+}
diff --git a/src/entrypoints/background/step-pipeline.ts b/src/entrypoints/background/step-pipeline.ts
new file mode 100644
index 0000000..7f8b640
--- /dev/null
+++ b/src/entrypoints/background/step-pipeline.ts
@@ -0,0 +1,103 @@
+import { localStorage } from '@/lib/browser-api';
+import { captureAnnotated } from '@/capture/screenshot';
+import { buildFallbackDescription } from '@/capture/step-description';
+import { getAIDescription } from '@/capture/ai-description';
+import { db } from '@/guides/db';
+import { getActor } from './actor';
+import type { Browser } from '#imports';
+import type { ElementMeta } from '@/guides/types';
+
+let captureQueue: Promise<void> = Promise.resolve();
+
+function enqueue(fn: () => Promise<void>): void {
+ captureQueue = captureQueue
+ .then(fn)
+ .catch((err) => console.error('[Mimik] Capture error', err));
+}
+
+interface UserActionData {
+ guideId: string;
+ action: string;
+ elementMeta: ElementMeta;
+}
+
+export function handleUserAction(
+ data: UserActionData,
+ sender: Browser.runtime.MessageSender,
+): { stepId: string } | { ignored: true } | { error: string } {
+ const actor = getActor();
+ const snap = actor.getSnapshot();
+
+ if (snap.value !== 'recording') {
+ return { ignored: true };
+ }
+
+ const stepIndex = snap.context.stepCount;
+ actor.send({ type: 'USER_ACTION' });
+ const guideId = snap.context.currentGuideId!;
+ const stepId = crypto.randomUUID();
+ const tabId = sender.tab?.id;
+
+ if (!tabId) {
+ return { error: 'no tabId' };
+ }
+
+ enqueue(async () => {
+ const fallbackDescription = buildFallbackDescription(data.action, data.elementMeta);
+ const currentUrl = snap.context.currentUrl;
+
+ let screenshotId: string | undefined;
+ let screenshotBlob: Blob | undefined;
+ try {
+ const screenshot = await captureAnnotated(tabId, stepId, data.elementMeta);
+ screenshotId = screenshot.id;
+ screenshotBlob = screenshot.blob;
+ } catch (err) {
+ console.warn('[Mimik] Screenshot capture failed, storing step without screenshot', err);
+ }
+
+ await db.steps.add({
+ id: stepId,
+ guideId,
+ index: stepIndex,
+ description: fallbackDescription,
+ action: data.action,
+ url: currentUrl,
+ timestamp: Date.now(),
+ screenshotId,
+ });
+
+ const guide = await db.guides.get(guideId);
+ if (guide) {
+ await db.guides.update(guideId, {
+ stepIds: [...guide.stepIds, stepId],
+ updatedAt: Date.now(),
+ });
+ }
+
+ if (screenshotBlob) {
+ (async () => {
+ try {
+ const settings = await localStorage.get(['aiApiKey', 'aiProvider']);
+ if (settings.aiApiKey) {
+ const provider = (settings.aiProvider as 'openai' | 'anthropic') || 'openai';
+ const aiDescription = await getAIDescription(
+ screenshotBlob,
+ data.action,
+ data.elementMeta,
+ provider,
+ settings.aiApiKey as string,
+ );
+ if (aiDescription) {
+ await db.steps.update(stepId, { description: aiDescription });
+ }
+ }
+ } catch (err) {
+ console.error('[Mimik] AI description update failed', err);
+ }
+ })();
+ }
+ });
+
+ return { stepId };
+}
diff --git a/src/entrypoints/background/tab-manager.ts b/src/entrypoints/background/tab-manager.ts
new file mode 100644
index 0000000..d2a87ac
--- /dev/null
+++ b/src/entrypoints/background/tab-manager.ts
@@ -0,0 +1,66 @@
+import { sendMessageToTab, executeScript, getAllWindows, queryTabs } from '@/lib/browser-api';
+
+export function isInjectableTab(tab: { url?: string; pendingUrl?: string }): boolean {
+ const url = tab.url || tab.pendingUrl || '';
+ if (
+ !url ||
+ url.startsWith('chrome://') ||
+ url.startsWith('chrome-extension://') ||
+ url.startsWith('chrome.google.com/webstore') ||
+ url.startsWith('about:')
+ )
+ return false;
+ return /^https?:/.test(url);
+}
+
+export async function injectContentScript(tabId: number): Promise<void> {
+ try {
+ await sendMessageToTab(tabId, { type: 'PING' });
+ } catch {
+ try {
+ await executeScript(tabId, ['/content-scripts/content.js']);
+ } catch {
+ }
+ }
+}
+
+export async function injectAllTabs(): Promise<void> {
+ try {
+ const windows = await getAllWindows();
+ for (const win of windows) {
+ for (const tab of win.tabs || []) {
+ if (tab.id && isInjectableTab(tab)) {
+ injectContentScript(tab.id);
+ }
+ }
+ }
+ } catch (err) {
+ console.warn('[Mimik] injectAllTabs failed', err);
+ }
+}
+
+export async function broadcastStartCapture(guideId: string): Promise<void> {
+ try {
+ const tabs = await queryTabs({});
+ for (const tab of tabs) {
+ if (tab.id && isInjectableTab(tab)) {
+ sendMessageToTab(tab.id, { type: 'START_CAPTURE', guideId }).catch(() => {});
+ }
+ }
+ } catch (err) {
+ console.warn('[Mimik] broadcastStartCapture failed', err);
+ }
+}
+
+export async function broadcastStopCapture(): Promise<void> {
+ try {
+ const tabs = await queryTabs({});
+ for (const tab of tabs) {
+ if (tab.id) {
+ sendMessageToTab(tab.id, { type: 'STOP_CAPTURE' }).catch(() => {});
+ }
+ }
+ } catch (err) {
+ console.warn('[Mimik] broadcastStopCapture failed', err);
+ }
+}
diff --git a/src/entrypoints/background/types.ts b/src/entrypoints/background/types.ts
new file mode 100644
index 0000000..01e7f71
--- /dev/null
+++ b/src/entrypoints/background/types.ts
@@ -0,0 +1,5 @@
+import type { createActor } from 'xstate';
+import type { captureMachine } from '@/capture/machine';
+
+export type ActorRef = ReturnType<typeof createActor<typeof captureMachine>>;
+export type ActorReady = Promise<void>;
diff --git a/entrypoints/content.ts b/src/entrypoints/content.ts
similarity index 65%
rename from entrypoints/content.ts
rename to src/entrypoints/content.ts
index d4b840a..c1221c6 100644
--- a/entrypoints/content.ts
+++ b/src/entrypoints/content.ts
@@ -1,9 +1,11 @@
+import { browser } from '#imports';
import { defineContentScript } from 'wxt/utils/define-content-script';
-import { startCapture } from '../src/content/events';
-import { startRrwebRecording } from '../src/content/rrweb-recorder';
-import { updateUrl } from '../src/content/spa-nav';
+import { sendMessage } from '@/lib/messaging';
+import { startCapture } from '@/capture/events';
+import { startRrwebRecording } from '@/capture/rrweb-recorder';
+import { updateUrl } from '@/capture/spa-nav';
-const CLEANUP_EVENT = `mimik_remove_content_script_${chrome.runtime.id}`;
+const CLEANUP_EVENT = `mimik_remove_content_script_${browser.runtime.id}`;
export default defineContentScript({
matches: ['<all_urls>'],
@@ -36,17 +38,18 @@ export default defineContentScript({
function cleanup() {
destroyed = true;
endCapture();
- chrome.runtime.onMessage.removeListener(messageHandler);
+ browser.runtime.onMessage.removeListener(messageHandler);
document.removeEventListener(CLEANUP_EVENT, cleanup);
}
document.addEventListener(CLEANUP_EVENT, cleanup);
+ window.addEventListener('beforeunload', () => endCapture());
- window.addEventListener('beforeunload', () => {
- endCapture();
- });
-
- function messageHandler(msg: any, _sender: any, sendResponse: (r: any) => void) {
+ function messageHandler(
+ msg: Record<string, unknown>,
+ _sender: unknown,
+ sendResponse: (r: unknown) => void,
+ ) {
if (destroyed) return false;
if (msg.type === 'PING') {
@@ -60,7 +63,7 @@ export default defineContentScript({
}
if (msg.type === 'START_CAPTURE' && msg.guideId) {
- beginCapture(msg.guideId);
+ beginCapture(msg.guideId as string);
sendResponse({ started: true });
return true;
}
@@ -72,7 +75,7 @@ export default defineContentScript({
}
if (msg.type === 'SPA_NAVIGATE' && msg.url) {
- updateUrl(msg.url);
+ updateUrl(msg.url as string);
sendResponse({ updated: true });
return true;
}
@@ -80,18 +83,16 @@ export default defineContentScript({
return false;
}
- chrome.runtime.onMessage.addListener(messageHandler);
+ browser.runtime.onMessage.addListener(messageHandler);
- try {
- chrome.runtime.sendMessage({ type: 'GET_STATE' }, (response) => {
- if (chrome.runtime.lastError) return; // Extension context invalid
+ sendMessage('getState', undefined)
+ .then(res => {
if (destroyed) return;
- if (response?.state === 'recording' && response.currentGuideId) {
- beginCapture(response.currentGuideId);
+ if (res.state === 'recording' && res.currentGuideId) {
+ beginCapture(res.currentGuideId);
}
- });
- } catch {
- }
+ })
+ .catch(() => {});
console.log('[Mimik] Content script loaded');
},
diff --git a/entrypoints/fullview/index.html b/src/entrypoints/fullview/index.html
similarity index 100%
rename from entrypoints/fullview/index.html
rename to src/entrypoints/fullview/index.html
diff --git a/entrypoints/fullview/index.tsx b/src/entrypoints/fullview/index.tsx
similarity index 62%
rename from entrypoints/fullview/index.tsx
rename to src/entrypoints/fullview/index.tsx
index a9cd635..8224ec3 100644
--- a/entrypoints/fullview/index.tsx
+++ b/src/entrypoints/fullview/index.tsx
@@ -1,6 +1,6 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
-import FullViewApp from '../../src/fullview/App';
-import '../../src/sidepanel/index.css';
+import FullViewApp from '@/fullview/App';
+import '@/sidepanel/index.css';
ReactDOM.createRoot(document.getElementById('root')!).render(<FullViewApp />);
diff --git a/entrypoints/options/index.html b/src/entrypoints/options/index.html
similarity index 100%
rename from entrypoints/options/index.html
rename to src/entrypoints/options/index.html
diff --git a/entrypoints/options/index.tsx b/src/entrypoints/options/index.tsx
similarity index 63%
rename from entrypoints/options/index.tsx
rename to src/entrypoints/options/index.tsx
index 0d3aafa..84d3999 100644
--- a/entrypoints/options/index.tsx
+++ b/src/entrypoints/options/index.tsx
@@ -1,6 +1,6 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
-import App from '../../src/options/App';
-import '../../src/options/index.css';
+import App from '@/options/App';
+import '@/options/index.css';
ReactDOM.createRoot(document.getElementById('root')!).render(<App />);
diff --git a/entrypoints/sidepanel/index.html b/src/entrypoints/sidepanel/index.html
similarity index 100%
rename from entrypoints/sidepanel/index.html
rename to src/entrypoints/sidepanel/index.html
diff --git a/entrypoints/sidepanel/index.tsx b/src/entrypoints/sidepanel/index.tsx
similarity index 62%
rename from entrypoints/sidepanel/index.tsx
rename to src/entrypoints/sidepanel/index.tsx
index 8672d5d..dc1b324 100644
--- a/entrypoints/sidepanel/index.tsx
+++ b/src/entrypoints/sidepanel/index.tsx
@@ -1,6 +1,6 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
-import App from '../../src/sidepanel/App';
-import '../../src/sidepanel/index.css';
+import App from '@/sidepanel/App';
+import '@/sidepanel/index.css';
ReactDOM.createRoot(document.getElementById('root')!).render(<App />);
diff --git a/src/export/html-export.ts b/src/export/html-export.ts
index 4781a11..2618508 100644
--- a/src/export/html-export.ts
+++ b/src/export/html-export.ts
@@ -1,4 +1,4 @@
-import type { Guide, Step, Screenshot } from '../shared/types';
+import type { Guide, Step, Screenshot } from '@/guides/types';
function blobToBase64(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
diff --git a/src/export/markdown-export.ts b/src/export/markdown-export.ts
index f86e973..ec50f35 100644
--- a/src/export/markdown-export.ts
+++ b/src/export/markdown-export.ts
@@ -1,4 +1,4 @@
-import type { Guide, Step, Screenshot } from '../shared/types';
+import type { Guide, Step, Screenshot } from '@/guides/types';
function blobToBase64(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
diff --git a/src/export/pdf-export.ts b/src/export/pdf-export.ts
index 3125850..799e4a0 100644
--- a/src/export/pdf-export.ts
+++ b/src/export/pdf-export.ts
@@ -1,5 +1,5 @@
import { jsPDF } from 'jspdf';
-import type { Guide, Step, Screenshot } from '../shared/types';
+import type { Guide, Step, Screenshot } from '@/guides/types';
function blobToDataUrl(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
diff --git a/src/fullview/App.tsx b/src/fullview/App.tsx
index b02ede2..b866a67 100644
--- a/src/fullview/App.tsx
+++ b/src/fullview/App.tsx
@@ -4,7 +4,7 @@ import TopNav from './TopNav';
import LibraryContent from './LibraryContent';
import GuideContent from './GuideContent';
import GuideOutline from './GuideOutline';
-import type { Step } from '../shared/types';
+import type { Step } from '@/guides/types';
export default function FullViewApp() {
const route = useRoute();
diff --git a/src/fullview/GuideContent.tsx b/src/fullview/GuideContent.tsx
index f48da4d..a680826 100644
--- a/src/fullview/GuideContent.tsx
+++ b/src/fullview/GuideContent.tsx
@@ -1,9 +1,9 @@
import { useState, useEffect, useCallback, useRef } from 'react';
-import { getGuide, updateGuideTitle, updateStepDescription, deleteStep, reorderSteps, updateScreenshotBlob } from '../shared/guide-service';
-import type { Guide, Step, Screenshot } from '../shared/types';
-import StepCard from '../sidepanel/StepCard';
-import BlurCanvas from '../sidepanel/BlurCanvas';
-import ExportMenu from '../sidepanel/ExportMenu';
+import { getGuide, updateGuideTitle, updateStepDescription, deleteStep, reorderSteps, updateScreenshotBlob } from '@/guides/service';
+import type { Guide, Step, Screenshot } from '@/guides/types';
+import StepCard from '@/sidepanel/StepCard';
+import BlurCanvas from '@/sidepanel/BlurCanvas';
+import ExportMenu from '@/sidepanel/ExportMenu';
import { navigate } from './router';
interface GuideContentProps {
diff --git a/src/fullview/GuideOutline.tsx b/src/fullview/GuideOutline.tsx
index 1d65d45..a2f4950 100644
--- a/src/fullview/GuideOutline.tsx
+++ b/src/fullview/GuideOutline.tsx
@@ -1,4 +1,4 @@
-import type { Step } from '../shared/types';
+import type { Step } from '@/guides/types';
interface GuideOutlineProps {
steps: Step[];
diff --git a/src/fullview/LibraryContent.tsx b/src/fullview/LibraryContent.tsx
index 5176a7c..589a031 100644
--- a/src/fullview/LibraryContent.tsx
+++ b/src/fullview/LibraryContent.tsx
@@ -1,9 +1,9 @@
import { useState, useEffect, useCallback } from 'react';
import { LayoutGrid, LayoutList, Star, Trash2, RotateCcw, FileText } from 'lucide-react';
-import { getGuides, getStarredGuides, getTrashedGuides, softDeleteGuide, permanentlyDeleteGuide, restoreGuide, toggleStar, getFirstScreenshot } from '../shared/guide-service';
-import type { Guide, Screenshot } from '../shared/types';
+import { getGuides, getStarredGuides, getTrashedGuides, softDeleteGuide, permanentlyDeleteGuide, restoreGuide, toggleStar, getFirstScreenshot } from '@/guides/service';
+import type { Guide, Screenshot } from '@/guides/types';
import { navigate } from './router';
-import ZoomScreenshot from '../sidepanel/ZoomScreenshot';
+import ZoomScreenshot from '@/sidepanel/ZoomScreenshot';
interface LibraryContentProps {
category: 'all' | 'starred' | 'trash';
diff --git a/src/fullview/Sidebar.tsx b/src/fullview/Sidebar.tsx
index a723ab6..ea14cf7 100644
--- a/src/fullview/Sidebar.tsx
+++ b/src/fullview/Sidebar.tsx
@@ -1,7 +1,7 @@
import { FileText, Star, Trash2, ArrowLeft } from 'lucide-react';
import type { Route } from './router';
import { navigate } from './router';
-import type { Step } from '../shared/types';
+import type { Step } from '@/guides/types';
interface SidebarProps {
route: Route;
@@ -43,7 +43,7 @@ export default function Sidebar({
onClick={() => onStepClick?.(step.id)}
className={`w-full text-left px-3 py-1.5 rounded-md text-sm flex items-center gap-2 transition-colors ${
activeStepId === step.id
- ? 'bg-blue-50 text-blue-700'
+ ? 'bg-amber-50 text-amber-700'
: 'text-gray-600 hover:bg-gray-50'
}`}
>
diff --git a/src/shared/db-schema.ts b/src/guides/db.ts
similarity index 100%
rename from src/shared/db-schema.ts
rename to src/guides/db.ts
diff --git a/src/shared/messages.ts b/src/guides/messages.ts
similarity index 100%
rename from src/shared/messages.ts
rename to src/guides/messages.ts
diff --git a/src/shared/guide-service.ts b/src/guides/service.ts
similarity index 99%
rename from src/shared/guide-service.ts
rename to src/guides/service.ts
index 548c416..20c61db 100644
--- a/src/shared/guide-service.ts
+++ b/src/guides/service.ts
@@ -1,4 +1,4 @@
-import { db } from './db-schema';
+import { db } from './db';
import type { Guide, Step, Screenshot } from './types';
export async function getGuides(): Promise<Guide[]> {
diff --git a/src/shared/types.ts b/src/guides/types.ts
similarity index 100%
rename from src/shared/types.ts
rename to src/guides/types.ts
diff --git a/src/sidepanel/BlurCanvas.tsx b/src/sidepanel/BlurCanvas.tsx
index e3b8490..ddc2cc2 100644
--- a/src/sidepanel/BlurCanvas.tsx
+++ b/src/sidepanel/BlurCanvas.tsx
@@ -1,6 +1,6 @@
import { useRef, useState, useEffect, useCallback } from 'react';
import { Undo, Check, X } from 'lucide-react';
-import type { Screenshot } from '../shared/types';
+import type { Screenshot } from '@/guides/types';
interface BlurCanvasProps {
screenshot: Screenshot;
diff --git a/src/sidepanel/ExportMenu.tsx b/src/sidepanel/ExportMenu.tsx
index f0c25c4..cf32756 100644
--- a/src/sidepanel/ExportMenu.tsx
+++ b/src/sidepanel/ExportMenu.tsx
@@ -1,9 +1,9 @@
import { useState, useEffect, useRef } from 'react';
import { Download, FileCode, FileText, FileDown, Loader2 } from 'lucide-react';
-import type { Guide, Step, Screenshot } from '../shared/types';
-import { exportGuideAsHTML } from '../export/html-export';
-import { exportGuideAsMarkdown } from '../export/markdown-export';
-import { exportGuideAsPDF } from '../export/pdf-export';
+import type { Guide, Step, Screenshot } from '@/guides/types';
+import { exportGuideAsHTML } from '@/export/html-export';
+import { exportGuideAsMarkdown } from '@/export/markdown-export';
+import { exportGuideAsPDF } from '@/export/pdf-export';
interface ExportMenuProps {
guideId: string;
diff --git a/src/sidepanel/StepCard.tsx b/src/sidepanel/StepCard.tsx
index 69d5d7f..54bfc19 100644
--- a/src/sidepanel/StepCard.tsx
+++ b/src/sidepanel/StepCard.tsx
@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react';
import { Trash2, GripVertical, EyeOff, Copy, Check } from 'lucide-react';
-import type { Step, Screenshot } from '../shared/types';
+import type { Step, Screenshot } from '@/guides/types';
import ZoomScreenshot from './ZoomScreenshot';
interface DragHandleProps {
diff --git a/src/sidepanel/ZoomScreenshot.tsx b/src/sidepanel/ZoomScreenshot.tsx
index d6bd135..3b5dc59 100644
--- a/src/sidepanel/ZoomScreenshot.tsx
+++ b/src/sidepanel/ZoomScreenshot.tsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useRef } from 'react';
-import type { Screenshot } from '../shared/types';
+import type { Screenshot } from '@/guides/types';
interface ZoomScreenshotProps {
screenshot: Screenshot;
diff --git a/tsconfig.json b/tsconfig.json
index 26e654a..33b1608 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,19 +1,13 @@
{
+ "extends": "./.wxt/tsconfig.json",
"compilerOptions": {
- "target": "ESNext",
- "module": "ESNext",
- "moduleResolution": "Bundler",
- "strict": true,
"jsx": "react-jsx",
"lib": ["ESNext", "DOM", "DOM.Iterable"],
- "skipLibCheck": true,
- "resolveJsonModule": true,
"allowImportingTsExtensions": true,
- "noEmit": true,
+ "noExplicitAny": true,
"paths": {
"@/*": ["./src/*"]
}
},
- "include": ["entrypoints*", "tests/**/*", "wxt.config.ts"],
- "exclude": ["node_modules", ".output", ".wxt"]
+ "include": ["src/entrypoints*", "tests/**/*", "wxt.config.ts", ".wxt/wxt.d.ts"]
}
diff --git a/wxt.config.ts b/wxt.config.ts
index 5606e0d..01221d2 100644
--- a/wxt.config.ts
+++ b/wxt.config.ts
@@ -1,20 +1,34 @@
-import { defineConfig } from 'wxt';
-import tailwindcss from '@tailwindcss/vite';
+import { defineConfig } from "wxt";
+import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
- modules: ['@wxt-dev/module-react'],
+ modules: ["@wxt-dev/module-react"],
+ srcDir: "src",
+ imports: false,
+ alias: {
+ '@': 'src',
+ },
vite: () => ({
plugins: [tailwindcss()],
}),
manifest: {
- name: 'Mimik',
- description: 'Auto-capture browser workflows and generate step-by-step guides with annotated screenshots.',
- permissions: ['storage', 'activeTab', 'tabs', 'scripting', 'unlimitedStorage', 'sidePanel', 'webNavigation'],
- host_permissions: ['<all_urls>'],
- minimum_chrome_version: '118',
+ name: "Mimik",
+ description:
+ "Auto-capture browser workflows and generate step-by-step guides with annotated screenshots.",
+ permissions: [
+ "storage",
+ "activeTab",
+ "tabs",
+ "scripting",
+ "unlimitedStorage",
+ "sidePanel",
+ "webNavigation",
+ ],
+ host_permissions: ["<all_urls>"],
+ minimum_chrome_version: "118",
action: {},
side_panel: {
- default_path: 'sidepanel/index.html',
+ default_path: "sidepanel/index.html",
},
},
});