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: give every app component, hook and function its own file

Luis Ortiz338f2e3ff21e
diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsx
index e662441..b03a431 100644
--- a/apps/desktop/src/renderer/App.tsx
+++ b/apps/desktop/src/renderer/App.tsx
@@ -2,7 +2,7 @@ import { GuideContent, LibraryContent, navigate, SearchModal, TooltipProvider, T
import { useEffect, useState } from 'react';
import { CaptureSheet } from './CaptureSheet';
import { GuideZoom } from './GuideZoom';
-import { SettingsPanel } from './SettingsPanel';
+import { SettingsPanel } from './settings/SettingsPanel';
export function App() {
const route = useRoute();
diff --git a/apps/desktop/src/renderer/__tests__/shortcut-recorder.test.ts b/apps/desktop/src/renderer/__tests__/shortcut-recorder.test.ts
index 9fc0d10..b14f038 100644
--- a/apps/desktop/src/renderer/__tests__/shortcut-recorder.test.ts
+++ b/apps/desktop/src/renderer/__tests__/shortcut-recorder.test.ts
@@ -1,6 +1,6 @@
import type React from 'react';
import { describe, expect, it } from 'vitest';
-import { accelerator } from '../ShortcutRecorder';
+import { accelerator } from '../settings/lib/accelerator';
const press = (key: string, held: Partial<Record<'ctrlKey' | 'altKey' | 'shiftKey' | 'metaKey', boolean>> = {}) =>
({ key, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, ...held }) as React.KeyboardEvent;
diff --git a/apps/desktop/src/renderer/ai.ts b/apps/desktop/src/renderer/ai.ts
deleted file mode 100644
index 410cc41..0000000
--- a/apps/desktop/src/renderer/ai.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { getAIDescription } from '@mimik/core/capture/ai/description';
-import { resolveAiKey } from '@mimik/core/capture/ai/keys';
-import { type GuideMeta, generateGuideMeta } from '@mimik/core/capture/ai/meta';
-import { AI_PROVIDERS } from '@mimik/core/capture/ai/models';
-import { serializeScreenContext } from '@mimik/core/capture/ai/screen-context';
-import { localStorage } from '@mimik/core/env';
-import type { ElementMeta } from '@mimik/core/guides/types';
-
-const AI_SETTINGS = ['aiApiKeys', 'aiApiKey', 'aiProvider', 'aiModel', 'aiBaseUrl'] as const;
-
-interface Credentials {
- provider: string;
- model: string;
- apiKey: string;
- baseUrl?: string;
-}
-
-async function credentials(): Promise<Credentials | null> {
- const stored = await localStorage.get(AI_SETTINGS);
- const { provider, apiKey } = resolveAiKey(stored);
- if (!apiKey) return null;
- return {
- provider,
- apiKey,
- model: (stored.aiModel as string) || AI_PROVIDERS[provider].defaultModel,
- baseUrl: (stored.aiBaseUrl as string) || undefined,
- };
-}
-
-export async function describeStep(action: string, meta: ElementMeta): Promise<string | null> {
- const keys = await credentials();
- if (!keys) return null;
- try {
- return await getAIDescription(
- serializeScreenContext(action, meta),
- keys.provider,
- keys.model,
- keys.apiKey,
- keys.baseUrl,
- );
- } catch {
- return null;
- }
-}
-
-export async function nameGuide(steps: { description: string }[]): Promise<GuideMeta | null> {
- const keys = await credentials();
- if (!keys) return null;
- const described = steps
- .filter((step) => step.description)
- .map((step) => ({ description: step.description, url: '' }));
- if (described.length === 0) return null;
- const trimmed = described.length > 15 ? [...described.slice(0, 10), ...described.slice(-5)] : described;
- try {
- return await generateGuideMeta(trimmed, keys.provider, keys.model, keys.apiKey, keys.baseUrl);
- } catch {
- return null;
- }
-}
diff --git a/apps/desktop/src/renderer/ai/credentials.ts b/apps/desktop/src/renderer/ai/credentials.ts
new file mode 100644
index 0000000..d29cb89
--- /dev/null
+++ b/apps/desktop/src/renderer/ai/credentials.ts
@@ -0,0 +1,24 @@
+import { resolveAiKey } from '@mimik/core/capture/ai/keys';
+import { AI_PROVIDERS } from '@mimik/core/capture/ai/models';
+import { localStorage } from '@mimik/core/env';
+
+const AI_SETTINGS = ['aiApiKeys', 'aiApiKey', 'aiProvider', 'aiModel', 'aiBaseUrl'] as const;
+
+interface Credentials {
+ provider: string;
+ model: string;
+ apiKey: string;
+ baseUrl?: string;
+}
+
+export async function credentials(): Promise<Credentials | null> {
+ const stored = await localStorage.get(AI_SETTINGS);
+ const { provider, apiKey } = resolveAiKey(stored);
+ if (!apiKey) return null;
+ return {
+ provider,
+ apiKey,
+ model: (stored.aiModel as string) || AI_PROVIDERS[provider].defaultModel,
+ baseUrl: (stored.aiBaseUrl as string) || undefined,
+ };
+}
diff --git a/apps/desktop/src/renderer/ai/describe-step.ts b/apps/desktop/src/renderer/ai/describe-step.ts
new file mode 100644
index 0000000..8e448dc
--- /dev/null
+++ b/apps/desktop/src/renderer/ai/describe-step.ts
@@ -0,0 +1,20 @@
+import { getAIDescription } from '@mimik/core/capture/ai/description';
+import { serializeScreenContext } from '@mimik/core/capture/ai/screen-context';
+import type { ElementMeta } from '@mimik/core/guides/types';
+import { credentials } from './credentials';
+
+export async function describeStep(action: string, meta: ElementMeta): Promise<string | null> {
+ const keys = await credentials();
+ if (!keys) return null;
+ try {
+ return await getAIDescription(
+ serializeScreenContext(action, meta),
+ keys.provider,
+ keys.model,
+ keys.apiKey,
+ keys.baseUrl,
+ );
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/desktop/src/renderer/ai/name-guide.ts b/apps/desktop/src/renderer/ai/name-guide.ts
new file mode 100644
index 0000000..5050985
--- /dev/null
+++ b/apps/desktop/src/renderer/ai/name-guide.ts
@@ -0,0 +1,17 @@
+import { type GuideMeta, generateGuideMeta } from '@mimik/core/capture/ai/meta';
+import { credentials } from './credentials';
+
+export async function nameGuide(steps: { description: string }[]): Promise<GuideMeta | null> {
+ const keys = await credentials();
+ if (!keys) return null;
+ const described = steps
+ .filter((step) => step.description)
+ .map((step) => ({ description: step.description, url: '' }));
+ if (described.length === 0) return null;
+ const trimmed = described.length > 15 ? [...described.slice(0, 10), ...described.slice(-5)] : described;
+ try {
+ return await generateGuideMeta(trimmed, keys.provider, keys.model, keys.apiKey, keys.baseUrl);
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/desktop/src/renderer/capture-host.ts b/apps/desktop/src/renderer/capture-host.ts
index 059e485..c7bf8b8 100644
--- a/apps/desktop/src/renderer/capture-host.ts
+++ b/apps/desktop/src/renderer/capture-host.ts
@@ -7,7 +7,7 @@ import {
updateGuideDescription,
updateGuideTitle,
} from '@mimik/core/guides/service';
-import { nameGuide } from './ai';
+import { nameGuide } from './ai/name-guide';
import { DesktopCaptureSink } from './capture-sink';
const sink = new DesktopCaptureSink();
diff --git a/apps/desktop/src/renderer/capture-sink.ts b/apps/desktop/src/renderer/capture-sink.ts
index a2dc4ca..f270046 100644
--- a/apps/desktop/src/renderer/capture-sink.ts
+++ b/apps/desktop/src/renderer/capture-sink.ts
@@ -20,7 +20,7 @@ import {
} from '@mimik/core/guides/service';
import { screenshotForElement } from '@mimik/core/screenshot/record';
import type { CursorMark } from '@mimik/core/screenshot/types';
-import { describeStep } from './ai';
+import { describeStep } from './ai/describe-step';
export type DesktopCaptureStepData = CaptureStepData & {
cursor?: CursorMark;
diff --git a/apps/desktop/src/renderer/check-storage.ts b/apps/desktop/src/renderer/check-storage.ts
index 82b0bdb..b3cf6cc 100644
--- a/apps/desktop/src/renderer/check-storage.ts
+++ b/apps/desktop/src/renderer/check-storage.ts
@@ -1,115 +1,10 @@
import './core-env';
-import { db, MimikDB } from '@mimik/core/guides/db';
-import {
- addStepToGuide,
- createGuide,
- createSnapshot,
- createStep,
- getGuide,
- permanentlyDeleteGuide,
- saveScreenshot,
-} from '@mimik/core/guides/service';
-import Dexie from 'dexie';
-
-export interface CheckResult {
- name: string;
- ok: boolean;
- detail: string;
-}
-
-const MIGRATION_DB = 'mimik-migration-check';
-
-async function migration(): Promise<CheckResult> {
- await Dexie.delete(MIGRATION_DB);
-
- const v1 = new Dexie(MIGRATION_DB);
- v1.version(1).stores({
- guides: 'id, createdAt, updatedAt, starred, deletedAt',
- steps: 'id, guideId, index',
- screenshots: 'id, stepId',
- });
- await v1.open();
- await v1.table('guides').add({ id: 'legacy', title: 'Written at v1', createdAt: 1, updatedAt: 1, stepIds: [] });
- v1.close();
-
- const upgraded = new MimikDB(MIGRATION_DB);
- await upgraded.open();
- const survivor = await upgraded.guides.get('legacy');
- const snapshotCount = await upgraded.snapshots.count();
- const verno = upgraded.verno;
- upgraded.close();
- await Dexie.delete(MIGRATION_DB);
-
- return {
- name: 'v1 to v2 migration',
- ok: verno === 2 && survivor?.title === 'Written at v1' && snapshotCount === 0,
- detail: `reopened at v${verno}, v1 row ${survivor ? 'survived' : 'lost'}, snapshots table readable`,
- };
-}
-
-async function open(): Promise<CheckResult> {
- await db.open();
- const tables = db.tables.map((t) => t.name).sort();
- const expected = ['guides', 'screenshots', 'snapshots', 'steps'];
- return {
- name: 'MimikDB opens',
- ok: db.verno === 2 && expected.every((t) => tables.includes(t)),
- detail: `v${db.verno}, tables: ${tables.join(', ')}`,
- };
-}
-
-async function write(guideId: string): Promise<CheckResult> {
- const stepId = `${guideId}-step`;
- const screenshotId = `${guideId}-shot`;
-
- await createGuide(guideId);
- await saveScreenshot({
- id: screenshotId,
- stepId,
- blob: new Blob([new Uint8Array([137, 80, 78, 71])], { type: 'image/png' }),
- mimeType: 'image/png',
- width: 2,
- height: 2,
- });
- await createStep({
- id: stepId,
- guideId,
- index: 0,
- description: 'Click Save',
- action: 'click',
- url: '',
- app: { name: 'Mimik Desktop' },
- window: { title: 'Storage check' },
- timestamp: Date.now(),
- screenshotId,
- });
- await addStepToGuide(guideId, stepId);
- const snapshot = await createSnapshot(guideId);
-
- return {
- name: 'write through @mimik/core',
- ok: snapshot !== null,
- detail: snapshot
- ? `guide, step, screenshot and snapshot ${snapshot.id.slice(0, 8)} stored`
- : 'snapshot not created',
- };
-}
-
-async function read(guideId: string): Promise<CheckResult> {
- const found = await getGuide(guideId);
- const step = found?.steps[0];
- const shot = found ? found.screenshots.get(step?.id ?? '') : undefined;
- const blobBytes = shot ? (await shot.blob.arrayBuffer()).byteLength : 0;
- await permanentlyDeleteGuide(guideId);
-
- return {
- name: 'read from a second window',
- ok: Boolean(found) && step?.app?.name === 'Mimik Desktop' && blobBytes === 4,
- detail: found
- ? `${found.steps.length} step, app "${step?.app?.name}", screenshot blob ${blobBytes} bytes`
- : 'guide not found',
- };
-}
+import { migration } from './check-storage/migration';
+import { open } from './check-storage/open';
+import { read } from './check-storage/read';
+import { report } from './check-storage/report';
+import type { CheckResult } from './check-storage/types';
+import { write } from './check-storage/write';
async function run(): Promise<CheckResult[]> {
const [role, guideId] = (window.location.hash.slice(1) || 'write:unknown').split(':');
@@ -117,10 +12,6 @@ async function run(): Promise<CheckResult[]> {
return [await migration(), await open(), await write(guideId)];
}
-function report(results: CheckResult[]): void {
- console.log(`MIMIK_STORAGE_CHECK ${JSON.stringify(results)}`);
-}
-
run()
.then(report)
.catch((error) =>
diff --git a/apps/desktop/src/renderer/check-storage/migration.ts b/apps/desktop/src/renderer/check-storage/migration.ts
new file mode 100644
index 0000000..dc498bc
--- /dev/null
+++ b/apps/desktop/src/renderer/check-storage/migration.ts
@@ -0,0 +1,33 @@
+import { MimikDB } from '@mimik/core/guides/db';
+import Dexie from 'dexie';
+import type { CheckResult } from './types';
+
+const MIGRATION_DB = 'mimik-migration-check';
+
+export async function migration(): Promise<CheckResult> {
+ await Dexie.delete(MIGRATION_DB);
+
+ const v1 = new Dexie(MIGRATION_DB);
+ v1.version(1).stores({
+ guides: 'id, createdAt, updatedAt, starred, deletedAt',
+ steps: 'id, guideId, index',
+ screenshots: 'id, stepId',
+ });
+ await v1.open();
+ await v1.table('guides').add({ id: 'legacy', title: 'Written at v1', createdAt: 1, updatedAt: 1, stepIds: [] });
+ v1.close();
+
+ const upgraded = new MimikDB(MIGRATION_DB);
+ await upgraded.open();
+ const survivor = await upgraded.guides.get('legacy');
+ const snapshotCount = await upgraded.snapshots.count();
+ const verno = upgraded.verno;
+ upgraded.close();
+ await Dexie.delete(MIGRATION_DB);
+
+ return {
+ name: 'v1 to v2 migration',
+ ok: verno === 2 && survivor?.title === 'Written at v1' && snapshotCount === 0,
+ detail: `reopened at v${verno}, v1 row ${survivor ? 'survived' : 'lost'}, snapshots table readable`,
+ };
+}
diff --git a/apps/desktop/src/renderer/check-storage/open.ts b/apps/desktop/src/renderer/check-storage/open.ts
new file mode 100644
index 0000000..cd9df20
--- /dev/null
+++ b/apps/desktop/src/renderer/check-storage/open.ts
@@ -0,0 +1,13 @@
+import { db } from '@mimik/core/guides/db';
+import type { CheckResult } from './types';
+
+export async function open(): Promise<CheckResult> {
+ await db.open();
+ const tables = db.tables.map((t) => t.name).sort();
+ const expected = ['guides', 'screenshots', 'snapshots', 'steps'];
+ return {
+ name: 'MimikDB opens',
+ ok: db.verno === 2 && expected.every((t) => tables.includes(t)),
+ detail: `v${db.verno}, tables: ${tables.join(', ')}`,
+ };
+}
diff --git a/apps/desktop/src/renderer/check-storage/read.ts b/apps/desktop/src/renderer/check-storage/read.ts
new file mode 100644
index 0000000..fce78c3
--- /dev/null
+++ b/apps/desktop/src/renderer/check-storage/read.ts
@@ -0,0 +1,18 @@
+import { getGuide, permanentlyDeleteGuide } from '@mimik/core/guides/service';
+import type { CheckResult } from './types';
+
+export async function read(guideId: string): Promise<CheckResult> {
+ const found = await getGuide(guideId);
+ const step = found?.steps[0];
+ const shot = found ? found.screenshots.get(step?.id ?? '') : undefined;
+ const blobBytes = shot ? (await shot.blob.arrayBuffer()).byteLength : 0;
+ await permanentlyDeleteGuide(guideId);
+
+ return {
+ name: 'read from a second window',
+ ok: Boolean(found) && step?.app?.name === 'Mimik Desktop' && blobBytes === 4,
+ detail: found
+ ? `${found.steps.length} step, app "${step?.app?.name}", screenshot blob ${blobBytes} bytes`
+ : 'guide not found',
+ };
+}
diff --git a/apps/desktop/src/renderer/check-storage/report.ts b/apps/desktop/src/renderer/check-storage/report.ts
new file mode 100644
index 0000000..276acc0
--- /dev/null
+++ b/apps/desktop/src/renderer/check-storage/report.ts
@@ -0,0 +1,5 @@
+import type { CheckResult } from './types';
+
+export function report(results: CheckResult[]): void {
+ console.log(`MIMIK_STORAGE_CHECK ${JSON.stringify(results)}`);
+}
diff --git a/apps/desktop/src/renderer/check-storage/types.ts b/apps/desktop/src/renderer/check-storage/types.ts
new file mode 100644
index 0000000..d06ec26
--- /dev/null
+++ b/apps/desktop/src/renderer/check-storage/types.ts
@@ -0,0 +1,5 @@
+export interface CheckResult {
+ name: string;
+ ok: boolean;
+ detail: string;
+}
diff --git a/apps/desktop/src/renderer/check-storage/write.ts b/apps/desktop/src/renderer/check-storage/write.ts
new file mode 100644
index 0000000..3e7c2d9
--- /dev/null
+++ b/apps/desktop/src/renderer/check-storage/write.ts
@@ -0,0 +1,39 @@
+import { addStepToGuide, createGuide, createSnapshot, createStep, saveScreenshot } from '@mimik/core/guides/service';
+import type { CheckResult } from './types';
+
+export async function write(guideId: string): Promise<CheckResult> {
+ const stepId = `${guideId}-step`;
+ const screenshotId = `${guideId}-shot`;
+
+ await createGuide(guideId);
+ await saveScreenshot({
+ id: screenshotId,
+ stepId,
+ blob: new Blob([new Uint8Array([137, 80, 78, 71])], { type: 'image/png' }),
+ mimeType: 'image/png',
+ width: 2,
+ height: 2,
+ });
+ await createStep({
+ id: stepId,
+ guideId,
+ index: 0,
+ description: 'Click Save',
+ action: 'click',
+ url: '',
+ app: { name: 'Mimik Desktop' },
+ window: { title: 'Storage check' },
+ timestamp: Date.now(),
+ screenshotId,
+ });
+ await addStepToGuide(guideId, stepId);
+ const snapshot = await createSnapshot(guideId);
+
+ return {
+ name: 'write through @mimik/core',
+ ok: snapshot !== null,
+ detail: snapshot
+ ? `guide, step, screenshot and snapshot ${snapshot.id.slice(0, 8)} stored`
+ : 'snapshot not created',
+ };
+}
diff --git a/apps/desktop/src/renderer/overlay.ts b/apps/desktop/src/renderer/overlay.ts
index 343f66b..9f1511e 100644
--- a/apps/desktop/src/renderer/overlay.ts
+++ b/apps/desktop/src/renderer/overlay.ts
@@ -1,342 +1,11 @@
-import {
- MASCOT_ASPECT,
- MASCOT_BODY,
- MASCOT_CROWN,
- MASCOT_CROWN_SPLIT,
- MASCOT_FACES,
- MASCOT_SEAM,
- MASCOT_VIEW_BOX,
-} from '@mimik/ui';
-import { icon } from './icons';
import './overlay.css';
-
-interface LastStep {
- index: number;
- title: string;
- src: string;
-}
-
-interface Region {
- x: number;
- y: number;
- width: number;
- height: number;
-}
-
-const MIN = { width: 240, height: 160 };
-const HANDLES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] as const;
-type Handle = (typeof HANDLES)[number];
+import { boundary } from './overlay/boundary';
+import { controls } from './overlay/controls';
+import { editor } from './overlay/editor';
const [role, originX, originY] = window.location.hash.slice(1).split(':');
const origin = { x: Number(originX) || 0, y: Number(originY) || 0 };
-function el<K extends keyof HTMLElementTagNameMap>(
- tag: K,
- props: Partial<HTMLElementTagNameMap[K]> = {},
- ...children: (Node | string)[]
-): HTMLElementTagNameMap[K] {
- const node = Object.assign(document.createElement(tag), props);
- node.append(...children);
- return node;
-}
-
-function normalise(a: { x: number; y: number }, b: { x: number; y: number }): Region {
- return {
- x: Math.min(a.x, b.x),
- y: Math.min(a.y, b.y),
- width: Math.max(Math.abs(a.x - b.x), MIN.width),
- height: Math.max(Math.abs(a.y - b.y), MIN.height),
- };
-}
-
-function editor(): void {
- document.body.className = 'editor';
-
- const size = el('div', { id: 'size' });
- const region = el('div', { id: 'region', className: 'empty' }, size);
- for (const handle of HANDLES) {
- const node = el('div', { className: 'handle' });
- node.dataset.handle = handle;
- region.append(node);
- }
-
- const hint = el(
- 'div',
- { id: 'hint' },
- 'Drag to set the capture area β€” ',
- el('b', {}, 'Enter'),
- ' to confirm, ',
- el('b', {}, 'Esc'),
- ' to cancel',
- );
- document.body.append(region, hint);
-
- let rect: Region | null = null;
-
- function paint(): void {
- if (!rect) {
- region.className = 'empty';
- return;
- }
- const local = { left: rect.x - origin.x, top: rect.y - origin.y };
- const onScreen =
- local.left + rect.width > 0 &&
- local.top + rect.height > 0 &&
- local.left < window.innerWidth &&
- local.top < window.innerHeight;
- region.className = onScreen ? '' : 'empty';
- region.style.left = `${local.left}px`;
- region.style.top = `${local.top}px`;
- region.style.width = `${rect.width}px`;
- region.style.height = `${rect.height}px`;
- size.textContent = `${rect.width} Γ— ${rect.height}`;
- }
-
- function commit(next: Region): void {
- rect = next;
- paint();
- window.mimikOverlay.setRegion(next);
- }
-
- document.body.addEventListener('pointerdown', (event) => {
- const target = event.target as HTMLElement;
- const handle = target.dataset.handle as Handle | undefined;
- const moving = !handle && region.contains(target) && rect !== null;
- const start = { x: event.clientX + origin.x, y: event.clientY + origin.y };
- const from = rect ? { ...rect } : null;
-
- document.body.setPointerCapture(event.pointerId);
- event.preventDefault();
-
- const move = (e: PointerEvent) => {
- const point = { x: e.clientX + origin.x, y: e.clientY + origin.y };
- if (handle && from) {
- const left = handle.includes('w') ? point.x : from.x;
- const top = handle.includes('n') ? point.y : from.y;
- const right = handle.includes('e') ? point.x : from.x + from.width;
- const bottom = handle.includes('s') ? point.y : from.y + from.height;
- commit(normalise({ x: left, y: top }, { x: right, y: bottom }));
- } else if (moving && from) {
- commit({ ...from, x: from.x + (point.x - start.x), y: from.y + (point.y - start.y) });
- } else {
- commit(normalise(start, point));
- }
- };
-
- const up = () => {
- document.body.removeEventListener('pointermove', move);
- document.body.removeEventListener('pointerup', up);
- };
-
- document.body.addEventListener('pointermove', move);
- document.body.addEventListener('pointerup', up);
- });
-
- window.addEventListener('keydown', (event) => {
- if (event.key === 'Enter') window.mimikOverlay.command('arm');
- if (event.key === 'Escape') window.mimikOverlay.command('cancel');
- });
-
- window.mimikOverlay.region().then((current) => {
- rect = current;
- paint();
- });
- window.mimikOverlay.onUpdate((_state, current) => {
- rect = current;
- paint();
- });
-}
-
-function boundary(): void {
- document.body.className = 'boundary';
- document.body.append(el('div', { id: 'frame' }));
- const apply = (state: string) => document.body.setAttribute('data-state', state);
- window.mimikOverlay.state().then(apply);
- window.mimikOverlay.onUpdate(apply);
-}
-
-const MODES = [
- { id: 'window', label: 'Window' },
- { id: 'screen', label: 'Screen' },
- { id: 'area', label: 'Area' },
-] as const;
-
-const MODE_COMMAND: Record<string, string> = { window: 'mode:window', screen: 'mode:screen', area: 'mode:region' };
-const MODE_ID: Record<string, string> = { window: 'window', screen: 'screen', region: 'area' };
-
-function svg<K extends keyof SVGElementTagNameMap>(
- tag: K,
- attrs: Record<string, string | number>,
-): SVGElementTagNameMap[K] {
- const node = document.createElementNS('http://www.w3.org/2000/svg', tag);
- for (const [key, value] of Object.entries(attrs)) node.setAttribute(key, String(value));
- return node;
-}
-
-function mascot(size = 42): SVGSVGElement {
- const root = svg('svg', {
- viewBox: MASCOT_VIEW_BOX,
- width: size,
- height: Math.round(size * MASCOT_ASPECT),
- 'aria-hidden': 'true',
- });
- const clip = svg('clipPath', { id: 'mascot-crown-split' });
- clip.append(svg('path', { d: MASCOT_CROWN_SPLIT }));
- const defs = svg('defs', {});
- defs.append(clip);
- const face = MASCOT_FACES.happy;
- root.append(
- defs,
- svg('rect', { ...MASCOT_BODY, fill: 'var(--deep)' }),
- svg('path', { d: MASCOT_CROWN, fill: 'var(--violet-mid)' }),
- svg('path', { d: MASCOT_CROWN, fill: 'var(--accent)', 'clip-path': 'url(#mascot-crown-split)' }),
- svg('rect', { ...MASCOT_SEAM, fill: 'var(--lavender)' }),
- ...face.eyes.map((d) =>
- svg('path', {
- d,
- stroke: 'var(--lavender)',
- 'stroke-width': face.eyeWidth,
- fill: 'none',
- 'stroke-linecap': 'round',
- }),
- ),
- svg('path', {
- d: face.mouth,
- stroke: 'var(--lavender)',
- 'stroke-width': face.mouthWidth,
- fill: 'none',
- 'stroke-linecap': 'round',
- }),
- );
- return root;
-}
-
-function controls(): void {
- document.body.className = 'controls';
-
- let collapsed = false;
-
- const dot = el('span', { id: 'dot' });
- const label = el('span', { id: 'label' }, 'Ready');
- const counter = el('span', { id: 'counter' });
- const badge = el('span', { id: 'badge' });
- const collapse = el('button', { id: 'collapse', type: 'button', title: 'Collapse' });
- collapse.append(icon('chevronDown'));
- const head = el('div', { id: 'head' }, dot, label, counter, badge, collapse);
-
- const shot = el('img', { id: 'shot', alt: '' });
- const preview = el('div', { id: 'preview' }, shot);
- const stepTitle = el('p', { id: 'stepTitle' });
- const stepMeta = el('p', { id: 'stepMeta' });
- const tip = el('p', { id: 'tip' });
- const intro = el('div', { id: 'intro' }, el('div', { id: 'mascot' }, mascot()), tip);
- const body = el('div', { id: 'body' }, preview, stepTitle, stepMeta, intro);
-
- const modeLabel = el('p', { id: 'modeLabel' }, 'Capture mode');
- const modeRow = el('div', { id: 'modes' });
- const modeButtons = MODES.map(({ id, label: text }) => {
- const button = el('button', { type: 'button', className: 'mode' }, text);
- button.dataset.mode = id;
- button.addEventListener('click', () => window.mimikOverlay.command(MODE_COMMAND[id]));
- modeRow.append(button);
- return button;
- });
- const modes = el('div', { id: 'modeBlock' }, modeLabel, modeRow);
-
- const secondary = el('button', { id: 'secondary', type: 'button' });
- const primary = el('button', { id: 'primary', type: 'button', className: 'primary' });
- const foot = el('div', { id: 'foot' }, secondary, primary);
-
- document.body.append(head, body, modes, foot);
-
- const report = () => window.mimikOverlay.size(document.body.scrollWidth, document.body.scrollHeight);
-
- let shownIcon = '';
- let shownChevron = '';
-
- const render = (state: string, _region?: Region, last?: LastStep | null, mode?: string, busy = false) => {
- const armed = state === 'armed';
- document.body.setAttribute('data-state', state);
- document.body.classList.toggle('collapsed', collapsed);
-
- label.textContent = state === 'recording' ? 'Recording' : state === 'paused' ? 'Paused' : 'Ready';
- counter.textContent = last ? String(last.index) : '';
- counter.hidden = !last;
- badge.textContent = mode === 'screen' ? 'Full screen' : mode === 'region' ? 'Selected area' : 'Active window';
- badge.hidden = state !== 'armed';
-
- const chevron = collapsed ? 'up' : 'down';
- if (chevron !== shownChevron) {
- shownChevron = chevron;
- collapse.replaceChildren(icon(collapsed ? 'chevronUp' : 'chevronDown'));
- }
- collapse.title = collapsed ? 'Expand' : 'Collapse';
-
- if (last) {
- if (shot.getAttribute('src') !== last.src) shot.src = last.src;
- stepTitle.textContent = last.title;
- stepMeta.textContent = `Step ${last.index}`;
- }
- preview.hidden = !last;
- stepTitle.hidden = !last;
- stepMeta.hidden = !last;
- tip.textContent = armed
- ? 'Press Start, then work as you normally would. Every click becomes a step.'
- : 'Waiting for your first click.';
- intro.hidden = Boolean(last) || state === 'paused';
- body.hidden = collapsed || (state === 'paused' && !last);
-
- modes.hidden = collapsed || state !== 'paused';
- for (const button of modeButtons) button.classList.toggle('active', button.dataset.mode === MODE_ID[mode ?? '']);
-
- if (state !== shownIcon) {
- shownIcon = state;
- secondary.replaceChildren();
- if (!armed) secondary.append(icon(state === 'recording' ? 'pause' : 'play'));
- secondary.append(armed ? 'Close' : state === 'recording' ? 'Pause' : 'Resume');
- primary.replaceChildren(icon(armed ? 'video' : 'check'));
- primary.append(armed ? 'Start' : 'Finish');
- }
- secondary.dataset.command = armed ? 'cancel' : state === 'recording' ? 'pause' : 'resume';
- primary.dataset.command = armed ? 'start' : 'stop';
- primary.disabled = busy && !armed;
- foot.hidden = collapsed;
-
- requestAnimationFrame(report);
- };
-
- let latest: [string, Region | undefined, LastStep | null | undefined, string | undefined, boolean] = [
- 'armed',
- undefined,
- null,
- undefined,
- false,
- ];
- const paint = () => render(...latest);
-
- primary.addEventListener('click', () => window.mimikOverlay.command(primary.dataset.command ?? 'start'));
- secondary.addEventListener('click', () => window.mimikOverlay.command(secondary.dataset.command ?? 'cancel'));
- collapse.addEventListener('click', () => {
- collapsed = !collapsed;
- paint();
- });
- shot.addEventListener('load', report);
-
- Promise.all([
- window.mimikOverlay.state(),
- window.mimikOverlay.last(),
- window.mimikOverlay.mode(),
- window.mimikOverlay.busy(),
- ]).then(([state, last, mode, busy]) => {
- latest = [state, undefined, last, mode, busy];
- paint();
- });
- window.mimikOverlay.onUpdate((state, region, last, mode, busy) => {
- latest = [state, region, last, mode, busy];
- paint();
- });
-}
-
-if (role === 'editor') editor();
+if (role === 'editor') editor(origin);
else if (role === 'boundary') boundary();
else controls();
diff --git a/apps/desktop/src/renderer/overlay/boundary.ts b/apps/desktop/src/renderer/overlay/boundary.ts
new file mode 100644
index 0000000..4b80303
--- /dev/null
+++ b/apps/desktop/src/renderer/overlay/boundary.ts
@@ -0,0 +1,9 @@
+import { el } from './el';
+
+export function boundary(): void {
+ document.body.className = 'boundary';
+ document.body.append(el('div', { id: 'frame' }));
+ const apply = (state: string) => document.body.setAttribute('data-state', state);
+ window.mimikOverlay.state().then(apply);
+ window.mimikOverlay.onUpdate(apply);
+}
diff --git a/apps/desktop/src/renderer/overlay/controls.ts b/apps/desktop/src/renderer/overlay/controls.ts
new file mode 100644
index 0000000..ddc2194
--- /dev/null
+++ b/apps/desktop/src/renderer/overlay/controls.ts
@@ -0,0 +1,150 @@
+import { icon } from '../icons';
+import { el } from './el';
+import { mascot } from './mascot';
+import type { Region } from './types';
+
+interface LastStep {
+ index: number;
+ title: string;
+ src: string;
+}
+
+const MODES = [
+ { id: 'window', label: 'Window' },
+ { id: 'screen', label: 'Screen' },
+ { id: 'area', label: 'Area' },
+] as const;
+
+const MODE_COMMAND: Record<string, string> = {
+ window: 'mode:window',
+ screen: 'mode:screen',
+ area: 'mode:region',
+};
+
+const MODE_ID: Record<string, string> = { window: 'window', screen: 'screen', region: 'area' };
+
+export function controls(): void {
+ document.body.className = 'controls';
+
+ let collapsed = false;
+
+ const dot = el('span', { id: 'dot' });
+ const label = el('span', { id: 'label' }, 'Ready');
+ const counter = el('span', { id: 'counter' });
+ const badge = el('span', { id: 'badge' });
+ const collapse = el('button', { id: 'collapse', type: 'button', title: 'Collapse' });
+ collapse.append(icon('chevronDown'));
+ const head = el('div', { id: 'head' }, dot, label, counter, badge, collapse);
+
+ const shot = el('img', { id: 'shot', alt: '' });
+ const preview = el('div', { id: 'preview' }, shot);
+ const stepTitle = el('p', { id: 'stepTitle' });
+ const stepMeta = el('p', { id: 'stepMeta' });
+ const tip = el('p', { id: 'tip' });
+ const intro = el('div', { id: 'intro' }, el('div', { id: 'mascot' }, mascot()), tip);
+ const body = el('div', { id: 'body' }, preview, stepTitle, stepMeta, intro);
+
+ const modeLabel = el('p', { id: 'modeLabel' }, 'Capture mode');
+ const modeRow = el('div', { id: 'modes' });
+ const modeButtons = MODES.map(({ id, label: text }) => {
+ const button = el('button', { type: 'button', className: 'mode' }, text);
+ button.dataset.mode = id;
+ button.addEventListener('click', () => window.mimikOverlay.command(MODE_COMMAND[id]));
+ modeRow.append(button);
+ return button;
+ });
+ const modes = el('div', { id: 'modeBlock' }, modeLabel, modeRow);
+
+ const secondary = el('button', { id: 'secondary', type: 'button' });
+ const primary = el('button', { id: 'primary', type: 'button', className: 'primary' });
+ const foot = el('div', { id: 'foot' }, secondary, primary);
+
+ document.body.append(head, body, modes, foot);
+
+ const report = () => window.mimikOverlay.size(document.body.scrollWidth, document.body.scrollHeight);
+
+ let shownIcon = '';
+ let shownChevron = '';
+
+ const render = (state: string, _region?: Region, last?: LastStep | null, mode?: string, busy = false) => {
+ const armed = state === 'armed';
+ document.body.setAttribute('data-state', state);
+ document.body.classList.toggle('collapsed', collapsed);
+
+ label.textContent = state === 'recording' ? 'Recording' : state === 'paused' ? 'Paused' : 'Ready';
+ counter.textContent = last ? String(last.index) : '';
+ counter.hidden = !last;
+ badge.textContent = mode === 'screen' ? 'Full screen' : mode === 'region' ? 'Selected area' : 'Active window';
+ badge.hidden = state !== 'armed';
+
+ const chevron = collapsed ? 'up' : 'down';
+ if (chevron !== shownChevron) {
+ shownChevron = chevron;
+ collapse.replaceChildren(icon(collapsed ? 'chevronUp' : 'chevronDown'));
+ }
+ collapse.title = collapsed ? 'Expand' : 'Collapse';
+
+ if (last) {
+ if (shot.getAttribute('src') !== last.src) shot.src = last.src;
+ stepTitle.textContent = last.title;
+ stepMeta.textContent = `Step ${last.index}`;
+ }
+ preview.hidden = !last;
+ stepTitle.hidden = !last;
+ stepMeta.hidden = !last;
+ tip.textContent = armed
+ ? 'Press Start, then work as you normally would. Every click becomes a step.'
+ : 'Waiting for your first click.';
+ intro.hidden = Boolean(last) || state === 'paused';
+ body.hidden = collapsed || (state === 'paused' && !last);
+
+ modes.hidden = collapsed || state !== 'paused';
+ for (const button of modeButtons) button.classList.toggle('active', button.dataset.mode === MODE_ID[mode ?? '']);
+
+ if (state !== shownIcon) {
+ shownIcon = state;
+ secondary.replaceChildren();
+ if (!armed) secondary.append(icon(state === 'recording' ? 'pause' : 'play'));
+ secondary.append(armed ? 'Close' : state === 'recording' ? 'Pause' : 'Resume');
+ primary.replaceChildren(icon(armed ? 'video' : 'check'));
+ primary.append(armed ? 'Start' : 'Finish');
+ }
+ secondary.dataset.command = armed ? 'cancel' : state === 'recording' ? 'pause' : 'resume';
+ primary.dataset.command = armed ? 'start' : 'stop';
+ primary.disabled = busy && !armed;
+ foot.hidden = collapsed;
+
+ requestAnimationFrame(report);
+ };
+
+ let latest: [string, Region | undefined, LastStep | null | undefined, string | undefined, boolean] = [
+ 'armed',
+ undefined,
+ null,
+ undefined,
+ false,
+ ];
+ const paint = () => render(...latest);
+
+ primary.addEventListener('click', () => window.mimikOverlay.command(primary.dataset.command ?? 'start'));
+ secondary.addEventListener('click', () => window.mimikOverlay.command(secondary.dataset.command ?? 'cancel'));
+ collapse.addEventListener('click', () => {
+ collapsed = !collapsed;
+ paint();
+ });
+ shot.addEventListener('load', report);
+
+ Promise.all([
+ window.mimikOverlay.state(),
+ window.mimikOverlay.last(),
+ window.mimikOverlay.mode(),
+ window.mimikOverlay.busy(),
+ ]).then(([state, last, mode, busy]) => {
+ latest = [state, undefined, last, mode, busy];
+ paint();
+ });
+ window.mimikOverlay.onUpdate((state, region, last, mode, busy) => {
+ latest = [state, region, last, mode, busy];
+ paint();
+ });
+}
diff --git a/apps/desktop/src/renderer/overlay/editor.ts b/apps/desktop/src/renderer/overlay/editor.ts
new file mode 100644
index 0000000..5175487
--- /dev/null
+++ b/apps/desktop/src/renderer/overlay/editor.ts
@@ -0,0 +1,115 @@
+import { el } from './el';
+import type { Region } from './types';
+
+const MIN = { width: 240, height: 160 };
+
+const HANDLES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] as const;
+
+type Handle = (typeof HANDLES)[number];
+
+function normalise(a: { x: number; y: number }, b: { x: number; y: number }): Region {
+ return {
+ x: Math.min(a.x, b.x),
+ y: Math.min(a.y, b.y),
+ width: Math.max(Math.abs(a.x - b.x), MIN.width),
+ height: Math.max(Math.abs(a.y - b.y), MIN.height),
+ };
+}
+
+export function editor(origin: { x: number; y: number }): void {
+ document.body.className = 'editor';
+
+ const size = el('div', { id: 'size' });
+ const region = el('div', { id: 'region', className: 'empty' }, size);
+ for (const handle of HANDLES) {
+ const node = el('div', { className: 'handle' });
+ node.dataset.handle = handle;
+ region.append(node);
+ }
+
+ const hint = el(
+ 'div',
+ { id: 'hint' },
+ 'Drag to set the capture area β€” ',
+ el('b', {}, 'Enter'),
+ ' to confirm, ',
+ el('b', {}, 'Esc'),
+ ' to cancel',
+ );
+ document.body.append(region, hint);
+
+ let rect: Region | null = null;
+
+ function paint(): void {
+ if (!rect) {
+ region.className = 'empty';
+ return;
+ }
+ const local = { left: rect.x - origin.x, top: rect.y - origin.y };
+ const onScreen =
+ local.left + rect.width > 0 &&
+ local.top + rect.height > 0 &&
+ local.left < window.innerWidth &&
+ local.top < window.innerHeight;
+ region.className = onScreen ? '' : 'empty';
+ region.style.left = `${local.left}px`;
+ region.style.top = `${local.top}px`;
+ region.style.width = `${rect.width}px`;
+ region.style.height = `${rect.height}px`;
+ size.textContent = `${rect.width} Γ— ${rect.height}`;
+ }
+
+ function commit(next: Region): void {
+ rect = next;
+ paint();
+ window.mimikOverlay.setRegion(next);
+ }
+
+ document.body.addEventListener('pointerdown', (event) => {
+ const target = event.target as HTMLElement;
+ const handle = target.dataset.handle as Handle | undefined;
+ const moving = !handle && region.contains(target) && rect !== null;
+ const start = { x: event.clientX + origin.x, y: event.clientY + origin.y };
+ const from = rect ? { ...rect } : null;
+
+ document.body.setPointerCapture(event.pointerId);
+ event.preventDefault();
+
+ const move = (e: PointerEvent) => {
+ const point = { x: e.clientX + origin.x, y: e.clientY + origin.y };
+ if (handle && from) {
+ const left = handle.includes('w') ? point.x : from.x;
+ const top = handle.includes('n') ? point.y : from.y;
+ const right = handle.includes('e') ? point.x : from.x + from.width;
+ const bottom = handle.includes('s') ? point.y : from.y + from.height;
+ commit(normalise({ x: left, y: top }, { x: right, y: bottom }));
+ } else if (moving && from) {
+ commit({ ...from, x: from.x + (point.x - start.x), y: from.y + (point.y - start.y) });
+ } else {
+ commit(normalise(start, point));
+ }
+ };
+
+ const up = () => {
+ document.body.removeEventListener('pointermove', move);
+ document.body.removeEventListener('pointerup', up);
+ };
+
+ document.body.addEventListener('pointermove', move);
+ document.body.addEventListener('pointerup', up);
+ });
+
+ window.addEventListener('keydown', (event) => {
+ if (event.key === 'Enter') window.mimikOverlay.command('arm');
+ if (event.key === 'Escape') window.mimikOverlay.command('cancel');
+ });
+
+ window.mimikOverlay.region().then((current) => {
+ rect = current;
+ paint();
+ });
+ window.mimikOverlay.onUpdate((_state, current) => {
+ rect = current;
+ paint();
+ });
+}
diff --git a/apps/desktop/src/renderer/overlay/el.ts b/apps/desktop/src/renderer/overlay/el.ts
new file mode 100644
index 0000000..5ddfcb8
--- /dev/null
+++ b/apps/desktop/src/renderer/overlay/el.ts
@@ -0,0 +1,9 @@
+export function el<K extends keyof HTMLElementTagNameMap>(
+ tag: K,
+ props: Partial<HTMLElementTagNameMap[K]> = {},
+ ...children: (Node | string)[]
+): HTMLElementTagNameMap[K] {
+ const node = Object.assign(document.createElement(tag), props);
+ node.append(...children);
+ return node;
+}
diff --git a/apps/desktop/src/renderer/overlay/mascot.ts b/apps/desktop/src/renderer/overlay/mascot.ts
new file mode 100644
index 0000000..155890c
--- /dev/null
+++ b/apps/desktop/src/renderer/overlay/mascot.ts
@@ -0,0 +1,48 @@
+import {
+ MASCOT_ASPECT,
+ MASCOT_BODY,
+ MASCOT_CROWN,
+ MASCOT_CROWN_SPLIT,
+ MASCOT_FACES,
+ MASCOT_SEAM,
+ MASCOT_VIEW_BOX,
+} from '@mimik/ui';
+import { svg } from './svg';
+
+export function mascot(size = 42): SVGSVGElement {
+ const root = svg('svg', {
+ viewBox: MASCOT_VIEW_BOX,
+ width: size,
+ height: Math.round(size * MASCOT_ASPECT),
+ 'aria-hidden': 'true',
+ });
+ const clip = svg('clipPath', { id: 'mascot-crown-split' });
+ clip.append(svg('path', { d: MASCOT_CROWN_SPLIT }));
+ const defs = svg('defs', {});
+ defs.append(clip);
+ const face = MASCOT_FACES.happy;
+ root.append(
+ defs,
+ svg('rect', { ...MASCOT_BODY, fill: 'var(--deep)' }),
+ svg('path', { d: MASCOT_CROWN, fill: 'var(--violet-mid)' }),
+ svg('path', { d: MASCOT_CROWN, fill: 'var(--accent)', 'clip-path': 'url(#mascot-crown-split)' }),
+ svg('rect', { ...MASCOT_SEAM, fill: 'var(--lavender)' }),
+ ...face.eyes.map((d) =>
+ svg('path', {
+ d,
+ stroke: 'var(--lavender)',
+ 'stroke-width': face.eyeWidth,
+ fill: 'none',
+ 'stroke-linecap': 'round',
+ }),
+ ),
+ svg('path', {
+ d: face.mouth,
+ stroke: 'var(--lavender)',
+ 'stroke-width': face.mouthWidth,
+ fill: 'none',
+ 'stroke-linecap': 'round',
+ }),
+ );
+ return root;
+}
diff --git a/apps/desktop/src/renderer/overlay/svg.ts b/apps/desktop/src/renderer/overlay/svg.ts
new file mode 100644
index 0000000..ecdd727
--- /dev/null
+++ b/apps/desktop/src/renderer/overlay/svg.ts
@@ -0,0 +1,8 @@
+export function svg<K extends keyof SVGElementTagNameMap>(
+ tag: K,
+ attrs: Record<string, string | number>,
+): SVGElementTagNameMap[K] {
+ const node = document.createElementNS('http://www.w3.org/2000/svg', tag);
+ for (const [key, value] of Object.entries(attrs)) node.setAttribute(key, String(value));
+ return node;
+}
diff --git a/apps/desktop/src/renderer/overlay/types.ts b/apps/desktop/src/renderer/overlay/types.ts
new file mode 100644
index 0000000..d48e4ce
--- /dev/null
+++ b/apps/desktop/src/renderer/overlay/types.ts
@@ -0,0 +1,6 @@
+export interface Region {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
diff --git a/apps/desktop/src/renderer/settings/Card.tsx b/apps/desktop/src/renderer/settings/Card.tsx
new file mode 100644
index 0000000..48d5ff3
--- /dev/null
+++ b/apps/desktop/src/renderer/settings/Card.tsx
@@ -0,0 +1,16 @@
+import type { Command } from 'lucide-react';
+import type { ReactNode } from 'react';
+
+export function Card({ icon: Icon, title, children }: { icon: typeof Command; title: string; children: ReactNode }) {
+ return (
+ <div className="space-y-3.5 rounded-[10px] border border-border bg-card p-3.5">
+ <div className="flex items-center gap-2.5">
+ <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-secondary">
+ <Icon size={14} className="text-accent" />
+ </div>
+ <span className="text-xs font-bold text-foreground">{title}</span>
+ </div>
+ {children}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/settings/Field.tsx b/apps/desktop/src/renderer/settings/Field.tsx
new file mode 100644
index 0000000..f69181a
--- /dev/null
+++ b/apps/desktop/src/renderer/settings/Field.tsx
@@ -0,0 +1,10 @@
+import type { ReactNode } from 'react';
+
+export function Field({ label, children }: { label: string; children: ReactNode }) {
+ return (
+ <label className="flex items-center gap-3 text-sm text-foreground">
+ <span className="mr-auto">{label}</span>
+ {children}
+ </label>
+ );
+}
diff --git a/apps/desktop/src/renderer/SettingsPanel.tsx b/apps/desktop/src/renderer/settings/SettingsPanel.tsx
similarity index 85%
rename from apps/desktop/src/renderer/SettingsPanel.tsx
rename to apps/desktop/src/renderer/settings/SettingsPanel.tsx
index b0de354..e57e6aa 100644
--- a/apps/desktop/src/renderer/SettingsPanel.tsx
+++ b/apps/desktop/src/renderer/settings/SettingsPanel.tsx
@@ -13,10 +13,12 @@ import {
useKeyCheck,
} from '@mimik/ui';
import { Command, Keyboard, MonitorPlay } from 'lucide-react';
-import type { ReactNode } from 'react';
import { useEffect, useState } from 'react';
-import type { CaptureSettings, CaptureShortcuts } from '../main/capture/settings';
+import type { CaptureSettings, CaptureShortcuts } from '../../main/capture/settings';
+import { Card } from './Card';
+import { Field } from './Field';
import { ShortcutRecorder } from './ShortcutRecorder';
+import { Toggle } from './Toggle';
type Section = 'capture' | 'ai' | 'shortcuts';
@@ -44,56 +46,6 @@ const ZOOM_LEVELS = Array.from(
(_, i) => MIN_ZOOM + i * ZOOM_STEP,
);
-function Field({ label, children }: { label: string; children: ReactNode }) {
- return (
- <label className="flex items-center gap-3 text-sm text-foreground">
- <span className="mr-auto">{label}</span>
- {children}
- </label>
- );
-}
-
-function Card({ icon: Icon, title, children }: { icon: typeof Command; title: string; children: ReactNode }) {
- return (
- <div className="space-y-3.5 rounded-[10px] border border-border bg-card p-3.5">
- <div className="flex items-center gap-2.5">
- <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-secondary">
- <Icon size={14} className="text-accent" />
- </div>
- <span className="text-xs font-bold text-foreground">{title}</span>
- </div>
- {children}
- </div>
- );
-}
-
-function Toggle({
- checked,
- label,
- hint,
- onChange,
-}: {
- checked: boolean;
- label: string;
- hint?: string;
- onChange: (next: boolean) => void;
-}) {
- return (
- <label className="flex cursor-pointer items-start gap-3">
- <input
- type="checkbox"
- checked={checked}
- onChange={(e) => onChange(e.target.checked)}
- className="mt-0.5 h-4 w-4 shrink-0 accent-accent"
- />
- <span className="flex flex-col gap-0.5">
- <span className="text-sm text-foreground">{label}</span>
- {hint && <span className="text-xs text-muted-foreground">{hint}</span>}
- </span>
- </label>
- );
-}
-
export function SettingsPanel() {
const [section, setSection] = useState<Section>('capture');
const keyCheck = useKeyCheck(validateApiKey);
diff --git a/apps/desktop/src/renderer/ShortcutRecorder.tsx b/apps/desktop/src/renderer/settings/ShortcutRecorder.tsx
similarity index 75%
rename from apps/desktop/src/renderer/ShortcutRecorder.tsx
rename to apps/desktop/src/renderer/settings/ShortcutRecorder.tsx
index 18076b5..ceb52e3 100644
--- a/apps/desktop/src/renderer/ShortcutRecorder.tsx
+++ b/apps/desktop/src/renderer/settings/ShortcutRecorder.tsx
@@ -2,20 +2,7 @@ import { i18n } from '@mimik/core/env';
import { Button } from '@mimik/ui';
import { X } from 'lucide-react';
import { useState } from 'react';
-
-const MODIFIERS = new Set(['Control', 'Alt', 'Shift', 'Meta']);
-
-export function accelerator(event: React.KeyboardEvent): string | null {
- if (MODIFIERS.has(event.key)) return null;
- const held: string[] = [];
- if (event.metaKey) held.push('Super');
- if (event.ctrlKey) held.push('Control');
- if (event.altKey) held.push('Alt');
- if (event.shiftKey) held.push('Shift');
- if (held.length === 0) return null;
- const key = event.key.length === 1 ? event.key.toUpperCase() : event.key;
- return [...held, key].join('+');
-}
+import { accelerator } from './lib/accelerator';
interface ShortcutRecorderProps {
label: string;
diff --git a/apps/desktop/src/renderer/settings/Toggle.tsx b/apps/desktop/src/renderer/settings/Toggle.tsx
new file mode 100644
index 0000000..03245d6
--- /dev/null
+++ b/apps/desktop/src/renderer/settings/Toggle.tsx
@@ -0,0 +1,26 @@
+export function Toggle({
+ checked,
+ label,
+ hint,
+ onChange,
+}: {
+ checked: boolean;
+ label: string;
+ hint?: string;
+ onChange: (next: boolean) => void;
+}) {
+ return (
+ <label className="flex cursor-pointer items-start gap-3">
+ <input
+ type="checkbox"
+ checked={checked}
+ onChange={(e) => onChange(e.target.checked)}
+ className="mt-0.5 h-4 w-4 shrink-0 accent-accent"
+ />
+ <span className="flex flex-col gap-0.5">
+ <span className="text-sm text-foreground">{label}</span>
+ {hint && <span className="text-xs text-muted-foreground">{hint}</span>}
+ </span>
+ </label>
+ );
+}
diff --git a/apps/desktop/src/renderer/settings/lib/accelerator.ts b/apps/desktop/src/renderer/settings/lib/accelerator.ts
new file mode 100644
index 0000000..07607b3
--- /dev/null
+++ b/apps/desktop/src/renderer/settings/lib/accelerator.ts
@@ -0,0 +1,13 @@
+const MODIFIERS = new Set(['Control', 'Alt', 'Shift', 'Meta']);
+
+export function accelerator(event: React.KeyboardEvent): string | null {
+ if (MODIFIERS.has(event.key)) return null;
+ const held: string[] = [];
+ if (event.metaKey) held.push('Super');
+ if (event.ctrlKey) held.push('Control');
+ if (event.altKey) held.push('Alt');
+ if (event.shiftKey) held.push('Shift');
+ if (held.length === 0) return null;
+ const key = event.key.length === 1 ? event.key.toUpperCase() : event.key;
+ return [...held, key].join('+');
+}
diff --git a/packages/core/src/capture/ai/__tests__/errors.test.ts b/packages/core/src/capture/ai/__tests__/errors.test.ts
index 5d35272..6136ca4 100644
--- a/packages/core/src/capture/ai/__tests__/errors.test.ts
+++ b/packages/core/src/capture/ai/__tests__/errors.test.ts
@@ -2,7 +2,8 @@ import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { APICallError, RetryError } from 'ai';
import { describe, expect, it } from 'vitest';
-import { aiActionKey, aiFailureKey } from '@/ui/sidepanel/ai-status';
+import { aiActionKey } from '@/ui/sidepanel/lib/ai-action-key';
+import { aiFailureKey } from '@/ui/sidepanel/lib/ai-failure-key';
import { type AiFailureReason, describeAiFailure } from '../errors';
const LOCALES = ['en', 'de', 'es', 'fr', 'pt-BR', 'zh-CN'];
diff --git a/packages/core/src/capture/ai/__tests__/meta.test.ts b/packages/core/src/capture/ai/__tests__/meta.test.ts
index e2fbf41..a866b94 100644
--- a/packages/core/src/capture/ai/__tests__/meta.test.ts
+++ b/packages/core/src/capture/ai/__tests__/meta.test.ts
@@ -13,10 +13,6 @@ vi.mock('ai', () => ({
vi.mock('../provider', () => ({ createModel: () => ({ id: 'test-model' }) }));
-vi.mock('@/lib/browser-api', () => ({
- localStorage: { get: vi.fn().mockResolvedValue({ aiLanguage: 'en' }) },
-}));
-
import { generateGuideMeta, parseGuideMeta } from '../meta';
const steps = [{ description: 'Click Directory', url: 'https://admin.okta.com/users' }];
diff --git a/packages/ui/src/ai/hooks/use-ask-ai.tsx b/packages/ui/src/ai/hooks/use-ask-ai.tsx
index 4458315..eaca60a 100644
--- a/packages/ui/src/ai/hooks/use-ask-ai.tsx
+++ b/packages/ui/src/ai/hooks/use-ask-ai.tsx
@@ -5,7 +5,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { Toast } from '../../common/components/Toast';
import { Tooltip, TooltipContent, TooltipTrigger } from '../../components/ui/tooltip';
-import { send } from '../../env';
+import { messages } from '../../env';
import { rewriteErrorMessage } from '../lib/rewrite-error';
const PRESET_LABEL_KEYS = {
@@ -120,7 +120,7 @@ export function useAskAi(value: string, onReplace: (next: string) => void, enabl
setBusy(true);
setError(null);
try {
- const response = await send('rewriteSelection', { text: target.core, instruction: prompt });
+ const response = await messages.send('rewriteSelection', { text: target.core, instruction: prompt });
if (response.error) {
setError(rewriteErrorMessage(response.error));
return;
diff --git a/packages/ui/src/ai/hooks/use-guide-description.ts b/packages/ui/src/ai/hooks/use-guide-description.ts
index 63a6432..b2d90d9 100644
--- a/packages/ui/src/ai/hooks/use-guide-description.ts
+++ b/packages/ui/src/ai/hooks/use-guide-description.ts
@@ -1,6 +1,6 @@
import { updateGuideDescription } from '@mimik/core/guides/service';
import { useCallback, useState } from 'react';
-import { send } from '../../env';
+import { messages } from '../../env';
import { guideDescriptionErrorMessage } from '../lib/guide-description-error';
export interface GuideDescription {
@@ -34,7 +34,7 @@ export function useGuideDescription(guideId: string, onWritten: (next: string) =
setGenerating(true);
setError(null);
try {
- const result = await send('generateGuideDescription', { guideId });
+ const result = await messages.send('generateGuideDescription', { guideId });
if (result.error) {
setError(guideDescriptionErrorMessage(result.error));
return;
diff --git a/packages/ui/src/env.ts b/packages/ui/src/env.ts
index 21986a7..557fa2b 100644
--- a/packages/ui/src/env.ts
+++ b/packages/ui/src/env.ts
@@ -60,6 +60,6 @@ export const panel: UiEnv['panel'] = {
requestHostPermissions: () => env().panel.requestHostPermissions(),
};
-export function send<T = any>(name: string, payload?: unknown): Promise<T> {
- return env().send<T>(name, payload);
-}
+export const messages: Pick<UiEnv, 'send'> = {
+ send: (name, payload) => env().send(name, payload),
+};
diff --git a/packages/ui/src/guide/components/GuideContent.tsx b/packages/ui/src/guide/components/GuideContent.tsx
index 34eb57d..587f586 100644
--- a/packages/ui/src/guide/components/GuideContent.tsx
+++ b/packages/ui/src/guide/components/GuideContent.tsx
@@ -24,7 +24,7 @@ import { AnnotationEditor } from '../../annotation/components/AnnotationEditor';
import { FaviconImg } from '../../common/components/FaviconImg';
import { Toast } from '../../common/components/Toast';
import { Tooltip, TooltipContent, TooltipTrigger } from '../../components/ui/tooltip';
-import { panel, send, tabs } from '../../env';
+import { messages, panel, tabs } from '../../env';
import { VersionHistoryPanel } from '../../history/components/VersionHistoryPanel';
import { useFullview } from '../../stores/use-fullview';
import { buildPreview } from '../lib/build-preview';
@@ -416,7 +416,7 @@ export function GuideContent({ guideId, initialStepId, initialTool }: GuideConte
<button
onClick={() => {
panel.open();
- void send('startGuideMe', { guideId });
+ void messages.send('startGuideMe', { guideId });
}}
className="inline-flex items-center gap-1.5 text-[11px] font-semibold text-primary-foreground bg-primary hover:bg-primary/90 px-3 py-0.5 rounded-full transition-colors ml-auto"
>
diff --git a/src/capture/events/__tests__/capture-sink.test.ts b/src/capture/events/__tests__/capture-sink.test.ts
index fdbafbe..9a298cd 100644
--- a/src/capture/events/__tests__/capture-sink.test.ts
+++ b/src/capture/events/__tests__/capture-sink.test.ts
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { CaptureSink, CaptureStepData } from '@/core/capture/sink';
import { type CaptureHandle, startCapture } from '../handlers';
-vi.mock('@/lib/browser-api', () => ({
+vi.mock('@/lib/browser-api/local-storage', () => ({
localStorage: { get: vi.fn().mockResolvedValue({}), set: vi.fn().mockResolvedValue(undefined) },
}));
diff --git a/src/capture/events/__tests__/click-replay.test.ts b/src/capture/events/__tests__/click-replay.test.ts
index e5abded..dd6d67c 100644
--- a/src/capture/events/__tests__/click-replay.test.ts
+++ b/src/capture/events/__tests__/click-replay.test.ts
@@ -5,7 +5,7 @@ import { type CaptureHandle, startCapture } from '../handlers';
vi.mock('@/lib/messaging', () => ({ sendMessage: vi.fn(), onMessage: vi.fn() }));
-vi.mock('@/lib/browser-api', () => ({
+vi.mock('@/lib/browser-api/local-storage', () => ({
localStorage: { get: vi.fn().mockResolvedValue({}), set: vi.fn().mockResolvedValue(undefined) },
}));
diff --git a/src/capture/events/__tests__/hover-ring-latch.test.ts b/src/capture/events/__tests__/hover-ring-latch.test.ts
index d436630..9d1f279 100644
--- a/src/capture/events/__tests__/hover-ring-latch.test.ts
+++ b/src/capture/events/__tests__/hover-ring-latch.test.ts
@@ -6,7 +6,7 @@ import { type CaptureHandle, startCapture } from '../handlers';
vi.mock('@/lib/messaging', () => ({ sendMessage: vi.fn(), onMessage: vi.fn() }));
-vi.mock('@/lib/browser-api', () => ({
+vi.mock('@/lib/browser-api/local-storage', () => ({
localStorage: {
get: vi.fn().mockResolvedValue({}),
set: vi.fn().mockResolvedValue(undefined),
diff --git a/src/capture/events/handlers.ts b/src/capture/events/handlers.ts
index fd47892..0e90983 100644
--- a/src/capture/events/handlers.ts
+++ b/src/capture/events/handlers.ts
@@ -15,7 +15,7 @@ import {
import { isReplayedClick, replayClick, replayInit, shouldInterceptClick } from '@/core/capture/events/click-intercept';
import type { CaptureSink } from '@/core/capture/sink';
import { DEFAULT_TARGET_COLOR } from '@/core/screenshot/types';
-import { localStorage } from '@/lib/browser-api';
+import { localStorage } from '@/lib/browser-api/local-storage';
import { HoverRing } from '@/lib/hover-ring';
import { InputSession } from './input-session';
diff --git a/src/capture/recordable-tabs.ts b/src/capture/recordable-tabs.ts
index f0f909a..cb1797c 100644
--- a/src/capture/recordable-tabs.ts
+++ b/src/capture/recordable-tabs.ts
@@ -1,4 +1,4 @@
-import { queryTabs } from '@/lib/browser-api';
+import { queryTabs } from '@/lib/browser-api/query-tabs';
const WEBSTORE_PREFIXES = ['https://chrome.google.com/webstore', 'https://chromewebstore.google.com'];
diff --git a/src/capture/start-insert-recording.ts b/src/capture/start-insert-recording.ts
index ed55c57..6151719 100644
--- a/src/capture/start-insert-recording.ts
+++ b/src/capture/start-insert-recording.ts
@@ -1,5 +1,8 @@
import { logger } from '@mimik/core/logger';
-import { focusWindow, getTab, requestHostPermissions, updateTab } from '@/lib/browser-api';
+import { focusWindow } from '@/lib/browser-api/focus-window';
+import { getTab } from '@/lib/browser-api/get-tab';
+import { requestHostPermissions } from '@/lib/browser-api/request-host-permissions';
+import { updateTab } from '@/lib/browser-api/update-tab';
import { sendMessage } from '@/lib/messaging';
import { isRecordableUrl } from './recordable-tabs';
diff --git a/src/entrypoints/background/__tests__/guide-meta.test.ts b/src/entrypoints/background/__tests__/guide-meta.test.ts
index 895c422..74222c5 100644
--- a/src/entrypoints/background/__tests__/guide-meta.test.ts
+++ b/src/entrypoints/background/__tests__/guide-meta.test.ts
@@ -28,7 +28,7 @@ vi.mock('@/core/guides/service', () => ({
updateGuideTitle: updateGuideTitleMock,
}));
-vi.mock('@/lib/browser-api', () => ({ localStorage: { get: localStorageGetMock } }));
+vi.mock('@/lib/browser-api/local-storage', () => ({ localStorage: { get: localStorageGetMock } }));
import { AI_PROVIDERS } from '@/core/capture/ai/models';
import { generateDescriptionOnDemand, generateGuideMetaOnStop } from '../guide-meta';
diff --git a/src/entrypoints/background/actor.ts b/src/entrypoints/background/actor.ts
index 1b18e37..51b9fab 100644
--- a/src/entrypoints/background/actor.ts
+++ b/src/entrypoints/background/actor.ts
@@ -1,8 +1,8 @@
import { logger } from '@mimik/core/logger';
import { createActor } from 'xstate';
import { type CaptureSnapshot, type CaptureStateValue, captureMachine } from '@/core/capture/machine';
-import { sessionStorage } from '@/lib/browser-api';
-import type { PanelStateUpdate } from '@/lib/port';
+import { sessionStorage } from '@/lib/browser-api/session-storage';
+import type { PanelStateUpdate } from '@/lib/port/types';
import type { ActorRef } from './types';
const STORAGE_KEY = 'machineSnapshot';
diff --git a/src/entrypoints/background/ai-description.ts b/src/entrypoints/background/ai-description.ts
index 75fbff6..dadfd82 100644
--- a/src/entrypoints/background/ai-description.ts
+++ b/src/entrypoints/background/ai-description.ts
@@ -4,8 +4,8 @@ import { describeAiFailure } from '@/core/capture/ai/errors';
import { resolveAiKey } from '@/core/capture/ai/keys';
import { AI_PROVIDERS } from '@/core/capture/ai/models';
import { type DOMContext, serializeDOMContext } from '@/core/capture/dom/context';
-import { localStorage } from '@/lib/browser-api';
-import { broadcastAiToPanel } from '@/lib/port';
+import { localStorage } from '@/lib/browser-api/local-storage';
+import { broadcastAiToPanel } from '@/lib/port/broadcast-ai-to-panel';
export async function generateAiDescription(domContext: DOMContext): Promise<string | undefined> {
const settings = await localStorage.get(['aiApiKeys', 'aiApiKey', 'aiProvider', 'aiModel', 'aiBaseUrl']);
diff --git a/src/entrypoints/background/guide-meta.ts b/src/entrypoints/background/guide-meta.ts
index 02076ee..e2e4952 100644
--- a/src/entrypoints/background/guide-meta.ts
+++ b/src/entrypoints/background/guide-meta.ts
@@ -11,7 +11,7 @@ import {
updateGuideDescription,
updateGuideTitle,
} from '@/core/guides/service';
-import { localStorage } from '@/lib/browser-api';
+import { localStorage } from '@/lib/browser-api/local-storage';
import type { GenerateGuideDescriptionResponse, GuideDescriptionError } from '@/lib/messaging';
import { drainDescriptions } from './description-queue';
import { whenNarrationSettled } from './voice';
diff --git a/src/entrypoints/background/index.ts b/src/entrypoints/background/index.ts
index 7e8d7fc..cb146ce 100644
--- a/src/entrypoints/background/index.ts
+++ b/src/entrypoints/background/index.ts
@@ -15,17 +15,16 @@ import {
mergeGuideInto,
} from '@/core/guides/service';
import type { Step } from '@/core/guides/types';
-import {
- getActiveTab,
- localStorage,
- sendMessageToTab,
- setSidePanelBehavior,
- toggleSidebar,
- updateTab,
-} from '@/lib/browser-api';
+import { getActiveTab } from '@/lib/browser-api/get-active-tab';
+import { localStorage } from '@/lib/browser-api/local-storage';
+import { sendMessageToTab } from '@/lib/browser-api/send-message-to-tab';
+import { setSidePanelBehavior } from '@/lib/browser-api/set-side-panel-behavior';
+import { toggleSidebar } from '@/lib/browser-api/toggle-sidebar';
+import { updateTab } from '@/lib/browser-api/update-tab';
import { onMessage } from '@/lib/messaging';
-import { broadcastStateToPanel, setupPortListener } from '@/lib/port';
-import { recordUpdate } from '@/lib/update-notice';
+import { broadcastStateToPanel } from '@/lib/port/broadcast-state-to-panel';
+import { setupPortListener } from '@/lib/port/setup-port-listener';
+import { recordUpdate } from '@/lib/update-notice/record-update';
import { getActor, getStateUpdate, initActor, initActorFallback, waitUntilReady } from './actor';
import { generateDescriptionOnDemand, generateGuideMetaOnStop, settlePendingDescriptions } from './guide-meta';
import { registerNavigationListeners } from './navigation';
diff --git a/src/entrypoints/background/navigation.ts b/src/entrypoints/background/navigation.ts
index fe8cdd8..4736a94 100644
--- a/src/entrypoints/background/navigation.ts
+++ b/src/entrypoints/background/navigation.ts
@@ -1,13 +1,11 @@
import { logger } from '@mimik/core/logger';
import { CaptureState } from '@/core/capture/machine';
-import {
- getTab,
- onHistoryStateUpdated,
- onNavigationCompleted,
- onTabActivated,
- onTabUpdated,
- sendMessageToTab,
-} from '@/lib/browser-api';
+import { getTab } from '@/lib/browser-api/get-tab';
+import { onHistoryStateUpdated } from '@/lib/browser-api/on-history-state-updated';
+import { onNavigationCompleted } from '@/lib/browser-api/on-navigation-completed';
+import { onTabActivated } from '@/lib/browser-api/on-tab-activated';
+import { onTabUpdated } from '@/lib/browser-api/on-tab-updated';
+import { sendMessageToTab } from '@/lib/browser-api/send-message-to-tab';
import { TabMessage } from '@/lib/tab-messages';
import { getActor, waitUntilReady } from './actor';
import { injectContentScript, isInjectableTab } from './tab-manager';
diff --git a/src/entrypoints/background/step-pipeline.ts b/src/entrypoints/background/step-pipeline.ts
index 153e9db..2a228ee 100644
--- a/src/entrypoints/background/step-pipeline.ts
+++ b/src/entrypoints/background/step-pipeline.ts
@@ -15,7 +15,8 @@ import {
} from '@/core/guides/service';
import type { ElementMeta } from '@/core/guides/types';
import { screenshotForElement } from '@/core/screenshot/record';
-import { captureVisibleTab, localStorage } from '@/lib/browser-api';
+import { captureVisibleTab } from '@/lib/browser-api/capture-visible-tab';
+import { localStorage } from '@/lib/browser-api/local-storage';
import type { CaptureStepData, CaptureStepResponse } from '@/lib/messaging';
import { getActor } from './actor';
import { generateAiDescription } from './ai-description';
diff --git a/src/entrypoints/background/tab-manager.ts b/src/entrypoints/background/tab-manager.ts
index c447fc1..1ef7c18 100644
--- a/src/entrypoints/background/tab-manager.ts
+++ b/src/entrypoints/background/tab-manager.ts
@@ -1,5 +1,7 @@
import { logger } from '@mimik/core/logger';
-import { executeScript, queryTabs, sendMessageToTab } from '@/lib/browser-api';
+import { executeScript } from '@/lib/browser-api/execute-script';
+import { queryTabs } from '@/lib/browser-api/query-tabs';
+import { sendMessageToTab } from '@/lib/browser-api/send-message-to-tab';
import { TabMessage } from '@/lib/tab-messages';
export function isInjectableTab(tab: { url?: string; pendingUrl?: string }): boolean {
diff --git a/src/entrypoints/background/voice.ts b/src/entrypoints/background/voice.ts
index e4ba79a..3337aa5 100644
--- a/src/entrypoints/background/voice.ts
+++ b/src/entrypoints/background/voice.ts
@@ -3,24 +3,26 @@ import { CaptureState } from '@/core/capture/machine';
import { hasVoiceApiKey, VOICE_KEY_SETTINGS } from '@/core/capture/voice/api-key';
import { narrationUpdates } from '@/core/capture/voice/narration-updates';
import { applyNarrationToSteps, findExistingStepIds, getStepsForGuide } from '@/core/guides/service';
-import { localStorage, onMessage as onRuntimeMessage } from '@/lib/browser-api';
+import { localStorage } from '@/lib/browser-api/local-storage';
+import { onMessage as onRuntimeMessage } from '@/lib/browser-api/on-message';
+import { closeVoiceHost } from '@/lib/offscreen/close-voice-host';
+import { closeVoiceHostIfIdle } from '@/lib/offscreen/close-voice-host-if-idle';
+import { ensureVoiceHost } from '@/lib/offscreen/ensure-voice-host';
+import { flushVoiceCapture } from '@/lib/offscreen/flush-voice-capture';
+import { hasVoiceHost } from '@/lib/offscreen/has-voice-host';
+import { openMicPermissionPage } from '@/lib/offscreen/open-mic-permission-page';
+import { queryMicPermission } from '@/lib/offscreen/query-mic-permission';
+import { registerVoicePanelRelay } from '@/lib/offscreen/register-voice-panel-relay';
+import { startVoiceCapture } from '@/lib/offscreen/start-voice-capture';
+import { stopVoiceCapture } from '@/lib/offscreen/stop-voice-capture';
+import { supportsVoice } from '@/lib/offscreen/supports-voice';
+import { broadcastVoiceToPanel } from '@/lib/port/broadcast-voice-to-panel';
+import type { PanelVoiceUpdate, VoicePhase } from '@/lib/port/types';
+import { handedOffPcm } from '@/lib/voice/handed-off-pcm';
+import { isVoiceMessageFor } from '@/lib/voice/is-voice-message-for';
+import { narrateRecording, type VoiceRecording } from '@/lib/voice/narrate-recording';
+import { readTranscriptionSettings } from '@/lib/voice/read-transcription-settings';
import {
- closeVoiceHost,
- closeVoiceHostIfIdle,
- ensureVoiceHost,
- flushVoiceCapture,
- hasVoiceHost,
- openMicPermissionPage,
- queryMicPermission,
- registerVoicePanelRelay,
- startVoiceCapture,
- stopVoiceCapture,
- supportsVoice,
-} from '@/lib/offscreen';
-import type { VoicePhase } from '@/lib/port';
-import { broadcastVoiceToPanel, type PanelVoiceUpdate } from '@/lib/port';
-import {
- isVoiceMessageFor,
VOICE_BACKGROUND_TARGET,
type VoiceErrorEvent,
type VoiceEvent,
@@ -29,9 +31,8 @@ import {
type VoicePermissionResultEvent,
type VoiceResultEvent,
type VoiceStepMark,
-} from '@/lib/voice-messages';
-import { narrateRecording, readTranscriptionSettings, type VoiceRecording } from '@/lib/voice-narration';
-import { handedOffPcm, voiceStopAction } from '@/lib/voice-recovery';
+} from '@/lib/voice/voice-message';
+import { voiceStopAction } from '@/lib/voice/voice-stop-action';
import { discardDeferred } from './deferred-descriptions';
import { describeStepNow, describeUnnarratedSteps } from './describe-unnarrated';
diff --git a/src/entrypoints/offscreen/index.ts b/src/entrypoints/offscreen/index.ts
index 3219edc..110a259 100644
--- a/src/entrypoints/offscreen/index.ts
+++ b/src/entrypoints/offscreen/index.ts
@@ -1,5 +1,5 @@
import '@/lib/core-env';
import '@/lib/ui-env';
-import { startVoiceHost } from '@/lib/voice-host';
+import { startVoiceHost } from '@/lib/voice/start-voice-host';
startVoiceHost();
diff --git a/src/entrypoints/sidepanel/index.tsx b/src/entrypoints/sidepanel/index.tsx
index 1f3f26f..d326280 100644
--- a/src/entrypoints/sidepanel/index.tsx
+++ b/src/entrypoints/sidepanel/index.tsx
@@ -1,7 +1,7 @@
import '@/lib/core-env';
import '@/lib/ui-env';
import ReactDOM from 'react-dom/client';
-import { startSidepanelVoiceHost } from '@/lib/sidepanel-voice-host';
+import { startSidepanelVoiceHost } from '@/lib/voice/start-sidepanel-voice-host';
import { App } from '@/ui/sidepanel/App';
import '@mimik/ui/global.css';
diff --git a/src/lib/__tests__/port.test.ts b/src/lib/__tests__/port.test.ts
index e17518e..57b4fcd 100644
--- a/src/lib/__tests__/port.test.ts
+++ b/src/lib/__tests__/port.test.ts
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, type Mock, vi } from 'vitest';
-import type { PanelStateUpdate, PanelVoiceUpdate } from '../port';
+import type { PanelStateUpdate, PanelVoiceUpdate } from '../port/types';
type PanelMessage = PanelStateUpdate | PanelVoiceUpdate;
@@ -34,7 +34,9 @@ const DONE: PanelVoiceUpdate = { type: 'VOICE_UPDATE', phase: 'idle', narrated:
const connectListeners: Array<(port: FakePort) => void> = [];
-let port: typeof import('../port');
+let port: typeof import('../port/setup-port-listener') &
+ typeof import('../port/broadcast-state-to-panel') &
+ typeof import('../port/broadcast-voice-to-panel');
let onPanelConnect: Mock<(port: unknown) => void>;
async function loadBackground() {
@@ -49,7 +51,11 @@ async function loadBackground() {
connectListeners.push(handler);
};
- port = await import('../port');
+ port = {
+ ...(await import('../port/setup-port-listener')),
+ ...(await import('../port/broadcast-state-to-panel')),
+ ...(await import('../port/broadcast-voice-to-panel')),
+ };
onPanelConnect = vi.fn<(port: unknown) => void>();
port.setupPortListener(onPanelConnect);
}
diff --git a/src/lib/__tests__/storage-typing.test.ts b/src/lib/__tests__/storage-typing.test.ts
index 73123d7..0568827 100644
--- a/src/lib/__tests__/storage-typing.test.ts
+++ b/src/lib/__tests__/storage-typing.test.ts
@@ -1,6 +1,6 @@
import { describe, expectTypeOf, it } from 'vitest';
import type { Settings } from '@/core/guides/types';
-import { localStorage } from '@/lib/browser-api';
+import { localStorage } from '@/lib/browser-api/local-storage';
describe('storage access is checked against the declared settings', () => {
it('returns the declared type for a key, not unknown', async () => {
diff --git a/src/lib/__tests__/update-notice.test.ts b/src/lib/__tests__/update-notice.test.ts
index 585088f..bd4c0ac 100644
--- a/src/lib/__tests__/update-notice.test.ts
+++ b/src/lib/__tests__/update-notice.test.ts
@@ -1,6 +1,9 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { browser } from '#imports';
-import { dismissUpdateNotice, readUpdateNotice, recordUpdate, UPDATE_NOTICE_KEY } from '../update-notice';
+import { UPDATE_NOTICE_KEY } from '../update-notice/constants';
+import { dismissUpdateNotice } from '../update-notice/dismiss-update-notice';
+import { readUpdateNotice } from '../update-notice/read-update-notice';
+import { recordUpdate } from '../update-notice/record-update';
describe('update notice', () => {
beforeEach(async () => {
diff --git a/src/lib/__tests__/voice-messages.test.ts b/src/lib/__tests__/voice-messages.test.ts
index ac5b903..052fd73 100644
--- a/src/lib/__tests__/voice-messages.test.ts
+++ b/src/lib/__tests__/voice-messages.test.ts
@@ -1,12 +1,12 @@
import { describe, expect, it } from 'vitest';
+import { isVoiceMessageFor } from '../voice/is-voice-message-for';
import {
- isVoiceMessageFor,
VOICE_BACKGROUND_TARGET,
VOICE_OFFSCREEN_TARGET,
VoiceMessage,
type VoiceStartRequest,
voiceMessage,
-} from '../voice-messages';
+} from '../voice/voice-message';
describe('voiceMessage', () => {
it('stamps a timestamp so webext-core ignores the message instead of throwing', () => {
diff --git a/src/lib/__tests__/voice-recovery.test.ts b/src/lib/__tests__/voice-recovery.test.ts
index 8fe1965..949f822 100644
--- a/src/lib/__tests__/voice-recovery.test.ts
+++ b/src/lib/__tests__/voice-recovery.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it } from 'vitest';
-import { handedOffPcm, isVoiceStatus, voiceStopAction } from '../voice-recovery';
+import { handedOffPcm } from '../voice/handed-off-pcm';
+import { isVoiceStatus } from '../voice/is-voice-status';
+import { voiceStopAction } from '../voice/voice-stop-action';
describe('isVoiceStatus', () => {
it('accepts a status response from a live microphone host', () => {
diff --git a/src/lib/browser-api.ts b/src/lib/browser-api.ts
deleted file mode 100644
index c68ca8e..0000000
--- a/src/lib/browser-api.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-import type { PublicPath } from 'wxt/browser';
-import { type Browser, browser } from '#imports';
-import type { Settings, SettingsKey } from '@/core/guides/types';
-
-type HtmlPublicPath = Extract<PublicPath, `${string}.html`>;
-type ScriptPath = Extract<PublicPath, `${string}.js`>;
-
-export function sendMessage(msg: Record<string, unknown>): Promise<unknown> {
- return browser.runtime.sendMessage(msg);
-}
-
-export function sendMessageWithCallback(msg: Record<string, unknown>, callback: (response: unknown) => void): void {
- browser.runtime.sendMessage(msg, callback);
-}
-
-export function sendMessageToTab(tabId: number, msg: Record<string, unknown>): Promise<unknown> {
- return browser.tabs.sendMessage(tabId, msg);
-}
-
-export function onMessage(
- handler: (
- msg: unknown,
- sender: Browser.runtime.MessageSender,
- sendResponse: (response?: unknown) => void,
- ) => boolean | undefined,
-): void {
- browser.runtime.onMessage.addListener(handler);
-}
-
-export function offMessage(handler: (...args: unknown[]) => unknown): void {
- browser.runtime.onMessage.removeListener(handler);
-}
-
-export function getLastError(): Browser.runtime.LastError | undefined {
- return browser.runtime.lastError;
-}
-
-export function getExtensionURL(path: PublicPath): string;
-export function getExtensionURL(path: `${HtmlPublicPath}${string}`): string;
-export function getExtensionURL(path: string): string {
- return (browser.runtime as { getURL(p: string): string }).getURL(path);
-}
-
-export function getExtensionId(): string {
- return browser.runtime.id;
-}
-
-export function queryTabs(query: Browser.tabs.QueryInfo): Promise<Browser.tabs.Tab[]> {
- return browser.tabs.query(query);
-}
-
-export async function getActiveTab(): Promise<Browser.tabs.Tab | undefined> {
- const tabs = await browser.tabs.query({
- active: true,
- lastFocusedWindow: true,
- });
- return tabs[0];
-}
-
-export function getTab(tabId: number): Promise<Browser.tabs.Tab> {
- return browser.tabs.get(tabId);
-}
-
-export function createTab(options: Browser.tabs.CreateProperties): Promise<Browser.tabs.Tab> {
- return browser.tabs.create(options);
-}
-
-export function updateTab(tabId: number, props: Browser.tabs.UpdateProperties): Promise<Browser.tabs.Tab | undefined> {
- return browser.tabs.update(tabId, props);
-}
-
-export function onTabActivated(handler: (activeInfo: Browser.tabs.OnActivatedInfo) => void): void {
- browser.tabs.onActivated.addListener(handler);
-}
-
-export function onTabUpdated(
- handler: (tabId: number, changeInfo: Browser.tabs.OnUpdatedInfo, tab: Browser.tabs.Tab) => void,
-): void {
- browser.tabs.onUpdated.addListener(handler);
-}
-
-export function getAllWindows(): Promise<Browser.windows.Window[]> {
- return browser.windows.getAll({ populate: true });
-}
-
-export function focusWindow(windowId: number): Promise<Browser.windows.Window> {
- return browser.windows.update(windowId, { focused: true });
-}
-
-export function captureVisibleTab(format: 'jpeg' | 'png' = 'jpeg', quality = 90): Promise<string> {
- return browser.tabs.captureVisibleTab({ format, quality });
-}
-
-export function executeScript(tabId: number, files: ScriptPath[], allFrames = true): Promise<unknown> {
- return browser.scripting.executeScript({
- target: { tabId, allFrames },
- files,
- });
-}
-
-export const sessionStorage = {
- get: (key: string) => browser.storage.session.get(key),
- set: (items: Record<string, unknown>) => browser.storage.session.set(items),
- remove: (key: string) => browser.storage.session.remove(key),
-};
-
-export const localStorage = {
- get: <K extends SettingsKey>(keys: readonly K[]) =>
- browser.storage.local.get(keys as unknown as K) as Promise<Partial<Pick<Settings, K>>>,
- set: (items: Partial<Settings>) => browser.storage.local.set(items),
-};
-
-export function setSidePanelBehavior(openOnActionClick: boolean): void {
- if (import.meta.env.BROWSER === 'firefox') return;
- browser.sidePanel.setPanelBehavior({
- openPanelOnActionClick: openOnActionClick,
- });
-}
-
-const sidebarAction = () =>
- (browser as unknown as { sidebarAction: { open(): Promise<void> | undefined; toggle(): void } }).sidebarAction;
-
-export function openSidebar(): void {
- try {
- if (import.meta.env.BROWSER === 'firefox') {
- sidebarAction()
- .open()
- ?.catch(() => undefined);
- } else {
- browser.sidePanel.open({ windowId: browser.windows.WINDOW_ID_CURRENT })?.catch(() => undefined);
- }
- } catch {
- return;
- }
-}
-
-export function toggleSidebar(): void {
- if (import.meta.env.BROWSER === 'firefox') {
- sidebarAction().toggle();
- }
-}
-
-export function requestHostPermissions(): Promise<boolean> {
- if (import.meta.env.BROWSER !== 'firefox') return Promise.resolve(true);
- try {
- return browser.permissions.request({ origins: ['<all_urls>'] }).catch(() => false);
- } catch {
- return Promise.resolve(false);
- }
-}
-
-export async function hasHostPermissions(): Promise<boolean> {
- if (import.meta.env.BROWSER !== 'firefox') return true;
- try {
- return await browser.permissions.contains({ origins: ['<all_urls>'] });
- } catch {
- return false;
- }
-}
-
-export function onNavigationCompleted(
- handler: (details: Browser.webNavigation.WebNavigationFramedCallbackDetails) => void,
-): void {
- browser.webNavigation.onCompleted.addListener(handler);
-}
-
-export function onHistoryStateUpdated(
- handler: (details: Browser.webNavigation.WebNavigationTransitionCallbackDetails) => void,
-): void {
- browser.webNavigation.onHistoryStateUpdated.addListener(handler);
-}
diff --git a/src/lib/browser-api/capture-visible-tab.ts b/src/lib/browser-api/capture-visible-tab.ts
new file mode 100644
index 0000000..8cb4801
--- /dev/null
+++ b/src/lib/browser-api/capture-visible-tab.ts
@@ -0,0 +1,5 @@
+import { browser } from '#imports';
+
+export function captureVisibleTab(format: 'jpeg' | 'png' = 'jpeg', quality = 90): Promise<string> {
+ return browser.tabs.captureVisibleTab({ format, quality });
+}
diff --git a/src/lib/browser-api/create-tab.ts b/src/lib/browser-api/create-tab.ts
new file mode 100644
index 0000000..8995539
--- /dev/null
+++ b/src/lib/browser-api/create-tab.ts
@@ -0,0 +1,5 @@
+import { type Browser, browser } from '#imports';
+
+export function createTab(options: Browser.tabs.CreateProperties): Promise<Browser.tabs.Tab> {
+ return browser.tabs.create(options);
+}
diff --git a/src/lib/browser-api/execute-script.ts b/src/lib/browser-api/execute-script.ts
new file mode 100644
index 0000000..e3b1eb2
--- /dev/null
+++ b/src/lib/browser-api/execute-script.ts
@@ -0,0 +1,11 @@
+import type { PublicPath } from 'wxt/browser';
+import { browser } from '#imports';
+
+type ScriptPath = Extract<PublicPath, `${string}.js`>;
+
+export function executeScript(tabId: number, files: ScriptPath[], allFrames = true): Promise<unknown> {
+ return browser.scripting.executeScript({
+ target: { tabId, allFrames },
+ files,
+ });
+}
diff --git a/src/lib/browser-api/focus-window.ts b/src/lib/browser-api/focus-window.ts
new file mode 100644
index 0000000..868dd56
--- /dev/null
+++ b/src/lib/browser-api/focus-window.ts
@@ -0,0 +1,5 @@
+import { type Browser, browser } from '#imports';
+
+export function focusWindow(windowId: number): Promise<Browser.windows.Window> {
+ return browser.windows.update(windowId, { focused: true });
+}
diff --git a/src/lib/browser-api/get-active-tab.ts b/src/lib/browser-api/get-active-tab.ts
new file mode 100644
index 0000000..2dbec71
--- /dev/null
+++ b/src/lib/browser-api/get-active-tab.ts
@@ -0,0 +1,9 @@
+import { type Browser, browser } from '#imports';
+
+export async function getActiveTab(): Promise<Browser.tabs.Tab | undefined> {
+ const tabs = await browser.tabs.query({
+ active: true,
+ lastFocusedWindow: true,
+ });
+ return tabs[0];
+}
diff --git a/src/lib/browser-api/get-all-windows.ts b/src/lib/browser-api/get-all-windows.ts
new file mode 100644
index 0000000..bfbe525
--- /dev/null
+++ b/src/lib/browser-api/get-all-windows.ts
@@ -0,0 +1,5 @@
+import { type Browser, browser } from '#imports';
+
+export function getAllWindows(): Promise<Browser.windows.Window[]> {
+ return browser.windows.getAll({ populate: true });
+}
diff --git a/src/lib/browser-api/get-extension-id.ts b/src/lib/browser-api/get-extension-id.ts
new file mode 100644
index 0000000..75f75bb
--- /dev/null
+++ b/src/lib/browser-api/get-extension-id.ts
@@ -0,0 +1,5 @@
+import { browser } from '#imports';
+
+export function getExtensionId(): string {
+ return browser.runtime.id;
+}
diff --git a/src/lib/browser-api/get-extension-url.ts b/src/lib/browser-api/get-extension-url.ts
new file mode 100644
index 0000000..679e462
--- /dev/null
+++ b/src/lib/browser-api/get-extension-url.ts
@@ -0,0 +1,12 @@
+import type { PublicPath } from 'wxt/browser';
+import { browser } from '#imports';
+
+type HtmlPublicPath = Extract<PublicPath, `${string}.html`>;
+
+export function getExtensionURL(path: PublicPath): string;
+
+export function getExtensionURL(path: `${HtmlPublicPath}${string}`): string;
+
+export function getExtensionURL(path: string): string {
+ return (browser.runtime as { getURL(p: string): string }).getURL(path);
+}
diff --git a/src/lib/browser-api/get-last-error.ts b/src/lib/browser-api/get-last-error.ts
new file mode 100644
index 0000000..4d30a12
--- /dev/null
+++ b/src/lib/browser-api/get-last-error.ts
@@ -0,0 +1,5 @@
+import { type Browser, browser } from '#imports';
+
+export function getLastError(): Browser.runtime.LastError | undefined {
+ return browser.runtime.lastError;
+}
diff --git a/src/lib/browser-api/get-tab.ts b/src/lib/browser-api/get-tab.ts
new file mode 100644
index 0000000..61d763a
--- /dev/null
+++ b/src/lib/browser-api/get-tab.ts
@@ -0,0 +1,5 @@
+import { type Browser, browser } from '#imports';
+
+export function getTab(tabId: number): Promise<Browser.tabs.Tab> {
+ return browser.tabs.get(tabId);
+}
diff --git a/src/lib/browser-api/has-host-permissions.ts b/src/lib/browser-api/has-host-permissions.ts
new file mode 100644
index 0000000..56c2a66
--- /dev/null
+++ b/src/lib/browser-api/has-host-permissions.ts
@@ -0,0 +1,10 @@
+import { browser } from '#imports';
+
+export async function hasHostPermissions(): Promise<boolean> {
+ if (import.meta.env.BROWSER !== 'firefox') return true;
+ try {
+ return await browser.permissions.contains({ origins: ['<all_urls>'] });
+ } catch {
+ return false;
+ }
+}
diff --git a/src/lib/browser-api/local-storage.ts b/src/lib/browser-api/local-storage.ts
new file mode 100644
index 0000000..a28ef9d
--- /dev/null
+++ b/src/lib/browser-api/local-storage.ts
@@ -0,0 +1,8 @@
+import { browser } from '#imports';
+import type { Settings, SettingsKey } from '@/core/guides/types';
+
+export const localStorage = {
+ get: <K extends SettingsKey>(keys: readonly K[]) =>
+ browser.storage.local.get(keys as unknown as K) as Promise<Partial<Pick<Settings, K>>>,
+ set: (items: Partial<Settings>) => browser.storage.local.set(items),
+};
diff --git a/src/lib/browser-api/off-message.ts b/src/lib/browser-api/off-message.ts
new file mode 100644
index 0000000..e254b74
--- /dev/null
+++ b/src/lib/browser-api/off-message.ts
@@ -0,0 +1,5 @@
+import { browser } from '#imports';
+
+export function offMessage(handler: (...args: unknown[]) => unknown): void {
+ browser.runtime.onMessage.removeListener(handler);
+}
diff --git a/src/lib/browser-api/on-history-state-updated.ts b/src/lib/browser-api/on-history-state-updated.ts
new file mode 100644
index 0000000..7036bce
--- /dev/null
+++ b/src/lib/browser-api/on-history-state-updated.ts
@@ -0,0 +1,7 @@
+import { type Browser, browser } from '#imports';
+
+export function onHistoryStateUpdated(
+ handler: (details: Browser.webNavigation.WebNavigationTransitionCallbackDetails) => void,
+): void {
+ browser.webNavigation.onHistoryStateUpdated.addListener(handler);
+}
diff --git a/src/lib/browser-api/on-message.ts b/src/lib/browser-api/on-message.ts
new file mode 100644
index 0000000..8734262
--- /dev/null
+++ b/src/lib/browser-api/on-message.ts
@@ -0,0 +1,11 @@
+import { type Browser, browser } from '#imports';
+
+export function onMessage(
+ handler: (
+ msg: unknown,
+ sender: Browser.runtime.MessageSender,
+ sendResponse: (response?: unknown) => void,
+ ) => boolean | undefined,
+): void {
+ browser.runtime.onMessage.addListener(handler);
+}
diff --git a/src/lib/browser-api/on-navigation-completed.ts b/src/lib/browser-api/on-navigation-completed.ts
new file mode 100644
index 0000000..e70a7d5
--- /dev/null
+++ b/src/lib/browser-api/on-navigation-completed.ts
@@ -0,0 +1,7 @@
+import { type Browser, browser } from '#imports';
+
+export function onNavigationCompleted(
+ handler: (details: Browser.webNavigation.WebNavigationFramedCallbackDetails) => void,
+): void {
+ browser.webNavigation.onCompleted.addListener(handler);
+}
diff --git a/src/lib/browser-api/on-tab-activated.ts b/src/lib/browser-api/on-tab-activated.ts
new file mode 100644
index 0000000..7cbb912
--- /dev/null
+++ b/src/lib/browser-api/on-tab-activated.ts
@@ -0,0 +1,5 @@
+import { type Browser, browser } from '#imports';
+
+export function onTabActivated(handler: (activeInfo: Browser.tabs.OnActivatedInfo) => void): void {
+ browser.tabs.onActivated.addListener(handler);
+}
diff --git a/src/lib/browser-api/on-tab-updated.ts b/src/lib/browser-api/on-tab-updated.ts
new file mode 100644
index 0000000..9af1069
--- /dev/null
+++ b/src/lib/browser-api/on-tab-updated.ts
@@ -0,0 +1,7 @@
+import { type Browser, browser } from '#imports';
+
+export function onTabUpdated(
+ handler: (tabId: number, changeInfo: Browser.tabs.OnUpdatedInfo, tab: Browser.tabs.Tab) => void,
+): void {
+ browser.tabs.onUpdated.addListener(handler);
+}
diff --git a/src/lib/browser-api/open-sidebar.ts b/src/lib/browser-api/open-sidebar.ts
new file mode 100644
index 0000000..79810df
--- /dev/null
+++ b/src/lib/browser-api/open-sidebar.ts
@@ -0,0 +1,16 @@
+import { browser } from '#imports';
+import { sidebarAction } from './sidebar-action';
+
+export function openSidebar(): void {
+ try {
+ if (import.meta.env.BROWSER === 'firefox') {
+ sidebarAction()
+ .open()
+ ?.catch(() => undefined);
+ } else {
+ browser.sidePanel.open({ windowId: browser.windows.WINDOW_ID_CURRENT })?.catch(() => undefined);
+ }
+ } catch {
+ return;
+ }
+}
diff --git a/src/lib/browser-api/query-tabs.ts b/src/lib/browser-api/query-tabs.ts
new file mode 100644
index 0000000..53c11df
--- /dev/null
+++ b/src/lib/browser-api/query-tabs.ts
@@ -0,0 +1,5 @@
+import { type Browser, browser } from '#imports';
+
+export function queryTabs(query: Browser.tabs.QueryInfo): Promise<Browser.tabs.Tab[]> {
+ return browser.tabs.query(query);
+}
diff --git a/src/lib/browser-api/request-host-permissions.ts b/src/lib/browser-api/request-host-permissions.ts
new file mode 100644
index 0000000..dd2a675
--- /dev/null
+++ b/src/lib/browser-api/request-host-permissions.ts
@@ -0,0 +1,10 @@
+import { browser } from '#imports';
+
+export function requestHostPermissions(): Promise<boolean> {
+ if (import.meta.env.BROWSER !== 'firefox') return Promise.resolve(true);
+ try {
+ return browser.permissions.request({ origins: ['<all_urls>'] }).catch(() => false);
+ } catch {
+ return Promise.resolve(false);
+ }
+}
diff --git a/src/lib/browser-api/send-message-to-tab.ts b/src/lib/browser-api/send-message-to-tab.ts
new file mode 100644
index 0000000..a5006b1
--- /dev/null
+++ b/src/lib/browser-api/send-message-to-tab.ts
@@ -0,0 +1,5 @@
+import { browser } from '#imports';
+
+export function sendMessageToTab(tabId: number, msg: Record<string, unknown>): Promise<unknown> {
+ return browser.tabs.sendMessage(tabId, msg);
+}
diff --git a/src/lib/browser-api/send-message-with-callback.ts b/src/lib/browser-api/send-message-with-callback.ts
new file mode 100644
index 0000000..ccc97e5
--- /dev/null
+++ b/src/lib/browser-api/send-message-with-callback.ts
@@ -0,0 +1,5 @@
+import { browser } from '#imports';
+
+export function sendMessageWithCallback(msg: Record<string, unknown>, callback: (response: unknown) => void): void {
+ browser.runtime.sendMessage(msg, callback);
+}
diff --git a/src/lib/browser-api/send-message.ts b/src/lib/browser-api/send-message.ts
new file mode 100644
index 0000000..6647a67
--- /dev/null
+++ b/src/lib/browser-api/send-message.ts
@@ -0,0 +1,5 @@
+import { browser } from '#imports';
+
+export function sendMessage(msg: Record<string, unknown>): Promise<unknown> {
+ return browser.runtime.sendMessage(msg);
+}
diff --git a/src/lib/browser-api/session-storage.ts b/src/lib/browser-api/session-storage.ts
new file mode 100644
index 0000000..a865d28
--- /dev/null
+++ b/src/lib/browser-api/session-storage.ts
@@ -0,0 +1,7 @@
+import { browser } from '#imports';
+
+export const sessionStorage = {
+ get: (key: string) => browser.storage.session.get(key),
+ set: (items: Record<string, unknown>) => browser.storage.session.set(items),
+ remove: (key: string) => browser.storage.session.remove(key),
+};
diff --git a/src/lib/browser-api/set-side-panel-behavior.ts b/src/lib/browser-api/set-side-panel-behavior.ts
new file mode 100644
index 0000000..856ef56
--- /dev/null
+++ b/src/lib/browser-api/set-side-panel-behavior.ts
@@ -0,0 +1,8 @@
+import { browser } from '#imports';
+
+export function setSidePanelBehavior(openOnActionClick: boolean): void {
+ if (import.meta.env.BROWSER === 'firefox') return;
+ browser.sidePanel.setPanelBehavior({
+ openPanelOnActionClick: openOnActionClick,
+ });
+}
diff --git a/src/lib/browser-api/sidebar-action.ts b/src/lib/browser-api/sidebar-action.ts
new file mode 100644
index 0000000..9b1cd9e
--- /dev/null
+++ b/src/lib/browser-api/sidebar-action.ts
@@ -0,0 +1,4 @@
+import { browser } from '#imports';
+
+export const sidebarAction = () =>
+ (browser as unknown as { sidebarAction: { open(): Promise<void> | undefined; toggle(): void } }).sidebarAction;
diff --git a/src/lib/browser-api/toggle-sidebar.ts b/src/lib/browser-api/toggle-sidebar.ts
new file mode 100644
index 0000000..f8882a9
--- /dev/null
+++ b/src/lib/browser-api/toggle-sidebar.ts
@@ -0,0 +1,7 @@
+import { sidebarAction } from './sidebar-action';
+
+export function toggleSidebar(): void {
+ if (import.meta.env.BROWSER === 'firefox') {
+ sidebarAction().toggle();
+ }
+}
diff --git a/src/lib/browser-api/update-tab.ts b/src/lib/browser-api/update-tab.ts
new file mode 100644
index 0000000..fd44261
--- /dev/null
+++ b/src/lib/browser-api/update-tab.ts
@@ -0,0 +1,5 @@
+import { type Browser, browser } from '#imports';
+
+export function updateTab(tabId: number, props: Browser.tabs.UpdateProperties): Promise<Browser.tabs.Tab | undefined> {
+ return browser.tabs.update(tabId, props);
+}
diff --git a/src/lib/core-env.ts b/src/lib/core-env.ts
index a0c8932..0a9f9db 100644
--- a/src/lib/core-env.ts
+++ b/src/lib/core-env.ts
@@ -1,6 +1,7 @@
import { i18n } from '#imports';
import { configureCore } from '@/core/env';
-import { getExtensionURL, localStorage } from '@/lib/browser-api';
+import { getExtensionURL } from '@/lib/browser-api/get-extension-url';
+import { localStorage } from '@/lib/browser-api/local-storage';
configureCore({
client: 'extension',
diff --git a/src/lib/offscreen.ts b/src/lib/offscreen.ts
deleted file mode 100644
index c1e0101..0000000
--- a/src/lib/offscreen.ts
+++ /dev/null
@@ -1,246 +0,0 @@
-import { logger } from '@mimik/core/logger';
-import { createTab, getExtensionURL, onMessage, sendMessage } from './browser-api';
-import { localVoiceHost } from './voice-local';
-import {
- isVoiceMessageFor,
- VOICE_BACKGROUND_TARGET,
- VOICE_OFFSCREEN_TARGET,
- VOICE_SIDEPANEL_TARGET,
- type VoiceAbortRequest,
- type VoiceAbortResponse,
- type VoiceFlushRequest,
- type VoiceFlushResponse,
- VoiceMessage,
- type VoicePermissionQueryRequest,
- type VoicePermissionQueryResponse,
- type VoicePermissionResultEvent,
- type VoiceRequest,
- type VoiceStartRequest,
- type VoiceStartResponse,
- type VoiceStatusRequest,
- type VoiceStatusResponse,
- type VoiceStepMark,
- type VoiceStopRequest,
- type VoiceStopResponse,
- type VoiceTranscriptionSettings,
- voiceMessage,
-} from './voice-messages';
-import { isVoiceStatus } from './voice-recovery';
-
-const IS_FIREFOX = import.meta.env.BROWSER === 'firefox';
-
-const OFFSCREEN_PATH = '/offscreen.html';
-const MIC_PERMISSION_PATH = '/mic-permission.html';
-const OFFSCREEN_REASON = 'USER_MEDIA';
-const OFFSCREEN_JUSTIFICATION = 'Recording microphone narration while a guide is being captured';
-const OFFSCREEN_CONTEXT = 'OFFSCREEN_DOCUMENT';
-
-interface OffscreenApi {
- createDocument(options: { url: string; reasons: string[]; justification: string }): Promise<void>;
- closeDocument(): Promise<void>;
-}
-
-interface ContextsApi {
- getContexts(filter: { contextTypes: string[] }): Promise<unknown[]>;
-}
-
-function offscreenApi(): OffscreenApi | undefined {
- return (globalThis as { chrome?: { offscreen?: OffscreenApi } }).chrome?.offscreen;
-}
-
-function contextsApi(): ContextsApi | undefined {
- const runtime = (globalThis as { chrome?: { runtime?: Partial<ContextsApi> } }).chrome?.runtime;
- return typeof runtime?.getContexts === 'function' ? (runtime as ContextsApi) : undefined;
-}
-
-let creating: Promise<void> | null = null;
-
-export function supportsOffscreen(): boolean {
- return offscreenApi() !== undefined;
-}
-
-export async function hasOffscreenDocument(): Promise<boolean> {
- const api = contextsApi();
- if (!api) return false;
- try {
- const contexts = await api.getContexts({ contextTypes: [OFFSCREEN_CONTEXT] });
- return contexts.length > 0;
- } catch {
- return false;
- }
-}
-
-export async function ensureOffscreenDocument(): Promise<boolean> {
- const api = offscreenApi();
- if (!api) return false;
- if (await hasOffscreenDocument()) return true;
-
- creating ??= api.createDocument({
- url: getExtensionURL(OFFSCREEN_PATH),
- reasons: [OFFSCREEN_REASON],
- justification: OFFSCREEN_JUSTIFICATION,
- });
-
- try {
- await creating;
- return true;
- } catch (error) {
- logger.error('voice: failed to create the offscreen document', error);
- return hasOffscreenDocument();
- } finally {
- creating = null;
- }
-}
-
-export async function closeOffscreenDocument(): Promise<void> {
- const api = offscreenApi();
- if (!api) return;
- if (!(await hasOffscreenDocument())) return;
- try {
- await api.closeDocument();
- } catch (error) {
- logger.error('voice: failed to close the offscreen document', error);
- }
-}
-
-async function requestMicrophoneInPage(): Promise<boolean> {
- try {
- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
- for (const track of stream.getTracks()) track.stop();
- return true;
- } catch (error) {
- logger.warn('voice: microphone access was not granted', error);
- return false;
- }
-}
-
-async function promptForMicrophone(): Promise<void> {
- const granted = await requestMicrophoneInPage();
- void sendMessage(
- voiceMessage<VoicePermissionResultEvent>({
- type: VoiceMessage.VOICE_PERMISSION_RESULT,
- target: VOICE_BACKGROUND_TARGET,
- state: granted ? 'granted' : 'denied',
- }) as unknown as Record<string, unknown>,
- ).catch(() => undefined);
-}
-
-export function openMicPermissionPage(tabId?: number): Promise<unknown> {
- if (IS_FIREFOX) {
- if (localVoiceHost() === null) return Promise.resolve(undefined);
- return promptForMicrophone();
- }
- const url = getExtensionURL(tabId === undefined ? MIC_PERMISSION_PATH : `${MIC_PERMISSION_PATH}?tabId=${tabId}`);
- return createTab({ url, active: true });
-}
-
-function request<T>(message: VoiceRequest): Promise<T> {
- const local = IS_FIREFOX ? localVoiceHost() : null;
- if (local) return local.handle(message) as Promise<T>;
- return sendMessage(message as unknown as Record<string, unknown>) as Promise<T>;
-}
-
-export function supportsVoice(): boolean {
- return IS_FIREFOX || supportsOffscreen();
-}
-
-export function ensureVoiceHost(): Promise<boolean> {
- if (IS_FIREFOX) return Promise.resolve(true);
- return ensureOffscreenDocument();
-}
-
-export async function hasVoiceHost(): Promise<boolean> {
- if (!IS_FIREFOX) return hasOffscreenDocument();
- return isVoiceStatus(await getVoiceStatus().catch(() => null));
-}
-
-export async function closeVoiceHost(): Promise<void> {
- if (IS_FIREFOX) return;
- await closeOffscreenDocument();
-}
-
-export async function closeVoiceHostIfIdle(): Promise<void> {
- if (IS_FIREFOX) return;
- const status = await getVoiceStatus().catch(() => null);
- if (!isVoiceStatus(status)) {
- logger.warn('voice: host status unavailable, leaving the document open');
- return;
- }
- if (status.recording || status.transcribing) return;
- await closeOffscreenDocument();
-}
-
-export function registerVoicePanelRelay(): void {
- if (!IS_FIREFOX) return;
- onMessage((message) => {
- if (!isVoiceMessageFor(VOICE_SIDEPANEL_TARGET, message)) return undefined;
- void sendMessage(message as unknown as Record<string, unknown>).catch(() => undefined);
- return undefined;
- });
-}
-
-async function answered<T>(message: VoiceRequest, missing: T): Promise<T> {
- const response = await request<T | undefined>(message).catch((error: unknown) => {
- logger.warn('voice: the microphone host did not answer', message.type, error);
- return undefined;
- });
- return response ?? missing;
-}
-
-export function startVoiceCapture(deviceId?: string): Promise<VoiceStartResponse> {
- return answered<VoiceStartResponse>(
- voiceMessage<VoiceStartRequest>({ type: VoiceMessage.VOICE_START, target: VOICE_OFFSCREEN_TARGET, deviceId }),
- { started: false, reason: 'unsupported', error: 'No microphone host is available' },
- );
-}
-
-export function stopVoiceCapture(
- guideId: string,
- steps: VoiceStepMark[],
- settings: VoiceTranscriptionSettings,
-): Promise<VoiceStopResponse> {
- return answered<VoiceStopResponse>(
- voiceMessage<VoiceStopRequest>({
- type: VoiceMessage.VOICE_STOP,
- target: VOICE_OFFSCREEN_TARGET,
- guideId,
- steps,
- settings,
- }),
- { ok: false, reason: 'stream-ended', error: 'The microphone host is no longer available' },
- );
-}
-
-export function flushVoiceCapture(
- guideId: string,
- step: VoiceStepMark,
- settings: VoiceTranscriptionSettings,
-): Promise<VoiceFlushResponse> {
- return answered<VoiceFlushResponse>(
- voiceMessage<VoiceFlushRequest>({
- type: VoiceMessage.VOICE_FLUSH,
- target: VOICE_OFFSCREEN_TARGET,
- guideId,
- step,
- settings,
- }),
- { ok: false, reason: 'stream-ended', error: 'The microphone host is no longer available' },
- );
-}
-
-export function abortVoiceCapture(): Promise<VoiceAbortResponse> {
- return request(voiceMessage<VoiceAbortRequest>({ type: VoiceMessage.VOICE_ABORT, target: VOICE_OFFSCREEN_TARGET }));
-}
-
-export function getVoiceStatus(): Promise<VoiceStatusResponse> {
- return request(voiceMessage<VoiceStatusRequest>({ type: VoiceMessage.VOICE_STATUS, target: VOICE_OFFSCREEN_TARGET }));
-}
-
-export function queryMicPermission(): Promise<VoicePermissionQueryResponse> {
- return request(
- voiceMessage<VoicePermissionQueryRequest>({
- type: VoiceMessage.VOICE_PERMISSION_QUERY,
- target: VOICE_OFFSCREEN_TARGET,
- }),
- );
-}
diff --git a/src/lib/offscreen/abort-voice-capture.ts b/src/lib/offscreen/abort-voice-capture.ts
new file mode 100644
index 0000000..8717339
--- /dev/null
+++ b/src/lib/offscreen/abort-voice-capture.ts
@@ -0,0 +1,12 @@
+import {
+ VOICE_OFFSCREEN_TARGET,
+ type VoiceAbortRequest,
+ type VoiceAbortResponse,
+ VoiceMessage,
+ voiceMessage,
+} from '../voice/voice-message';
+import { request } from './request';
+
+export function abortVoiceCapture(): Promise<VoiceAbortResponse> {
+ return request(voiceMessage<VoiceAbortRequest>({ type: VoiceMessage.VOICE_ABORT, target: VOICE_OFFSCREEN_TARGET }));
+}
diff --git a/src/lib/offscreen/answered.ts b/src/lib/offscreen/answered.ts
new file mode 100644
index 0000000..f528f17
--- /dev/null
+++ b/src/lib/offscreen/answered.ts
@@ -0,0 +1,11 @@
+import { logger } from '@mimik/core/logger';
+import type { VoiceRequest } from '../voice/voice-message';
+import { request } from './request';
+
+export async function answered<T>(message: VoiceRequest, missing: T): Promise<T> {
+ const response = await request<T | undefined>(message).catch((error: unknown) => {
+ logger.warn('voice: the microphone host did not answer', message.type, error);
+ return undefined;
+ });
+ return response ?? missing;
+}
diff --git a/src/lib/offscreen/close-offscreen-document.ts b/src/lib/offscreen/close-offscreen-document.ts
new file mode 100644
index 0000000..f34bb71
--- /dev/null
+++ b/src/lib/offscreen/close-offscreen-document.ts
@@ -0,0 +1,14 @@
+import { logger } from '@mimik/core/logger';
+import { hasOffscreenDocument } from './has-offscreen-document';
+import { offscreenApi } from './offscreen-api';
+
+export async function closeOffscreenDocument(): Promise<void> {
+ const api = offscreenApi();
+ if (!api) return;
+ if (!(await hasOffscreenDocument())) return;
+ try {
+ await api.closeDocument();
+ } catch (error) {
+ logger.error('voice: failed to close the offscreen document', error);
+ }
+}
diff --git a/src/lib/offscreen/close-voice-host-if-idle.ts b/src/lib/offscreen/close-voice-host-if-idle.ts
new file mode 100644
index 0000000..6975cd1
--- /dev/null
+++ b/src/lib/offscreen/close-voice-host-if-idle.ts
@@ -0,0 +1,16 @@
+import { logger } from '@mimik/core/logger';
+import { isVoiceStatus } from '../voice/is-voice-status';
+import { closeOffscreenDocument } from './close-offscreen-document';
+import { IS_FIREFOX } from './constants';
+import { getVoiceStatus } from './get-voice-status';
+
+export async function closeVoiceHostIfIdle(): Promise<void> {
+ if (IS_FIREFOX) return;
+ const status = await getVoiceStatus().catch(() => null);
+ if (!isVoiceStatus(status)) {
+ logger.warn('voice: host status unavailable, leaving the document open');
+ return;
+ }
+ if (status.recording || status.transcribing) return;
+ await closeOffscreenDocument();
+}
diff --git a/src/lib/offscreen/close-voice-host.ts b/src/lib/offscreen/close-voice-host.ts
new file mode 100644
index 0000000..5f2cca8
--- /dev/null
+++ b/src/lib/offscreen/close-voice-host.ts
@@ -0,0 +1,7 @@
+import { closeOffscreenDocument } from './close-offscreen-document';
+import { IS_FIREFOX } from './constants';
+
+export async function closeVoiceHost(): Promise<void> {
+ if (IS_FIREFOX) return;
+ await closeOffscreenDocument();
+}
diff --git a/src/lib/offscreen/constants.ts b/src/lib/offscreen/constants.ts
new file mode 100644
index 0000000..38baf1a
--- /dev/null
+++ b/src/lib/offscreen/constants.ts
@@ -0,0 +1 @@
+export const IS_FIREFOX = import.meta.env.BROWSER === 'firefox';
diff --git a/src/lib/offscreen/ensure-offscreen-document.ts b/src/lib/offscreen/ensure-offscreen-document.ts
new file mode 100644
index 0000000..1c26f4c
--- /dev/null
+++ b/src/lib/offscreen/ensure-offscreen-document.ts
@@ -0,0 +1,32 @@
+import { logger } from '@mimik/core/logger';
+import { getExtensionURL } from '../browser-api/get-extension-url';
+import { hasOffscreenDocument } from './has-offscreen-document';
+import { offscreenApi } from './offscreen-api';
+
+const OFFSCREEN_PATH = '/offscreen.html';
+const OFFSCREEN_REASON = 'USER_MEDIA';
+const OFFSCREEN_JUSTIFICATION = 'Recording microphone narration while a guide is being captured';
+
+const creating: { current: Promise<void> | null } = { current: null };
+
+export async function ensureOffscreenDocument(): Promise<boolean> {
+ const api = offscreenApi();
+ if (!api) return false;
+ if (await hasOffscreenDocument()) return true;
+
+ creating.current ??= api.createDocument({
+ url: getExtensionURL(OFFSCREEN_PATH),
+ reasons: [OFFSCREEN_REASON],
+ justification: OFFSCREEN_JUSTIFICATION,
+ });
+
+ try {
+ await creating.current;
+ return true;
+ } catch (error) {
+ logger.error('voice: failed to create the offscreen document', error);
+ return hasOffscreenDocument();
+ } finally {
+ creating.current = null;
+ }
+}
diff --git a/src/lib/offscreen/ensure-voice-host.ts b/src/lib/offscreen/ensure-voice-host.ts
new file mode 100644
index 0000000..94adbcd
--- /dev/null
+++ b/src/lib/offscreen/ensure-voice-host.ts
@@ -0,0 +1,7 @@
+import { IS_FIREFOX } from './constants';
+import { ensureOffscreenDocument } from './ensure-offscreen-document';
+
+export function ensureVoiceHost(): Promise<boolean> {
+ if (IS_FIREFOX) return Promise.resolve(true);
+ return ensureOffscreenDocument();
+}
diff --git a/src/lib/offscreen/flush-voice-capture.ts b/src/lib/offscreen/flush-voice-capture.ts
new file mode 100644
index 0000000..f42a91d
--- /dev/null
+++ b/src/lib/offscreen/flush-voice-capture.ts
@@ -0,0 +1,27 @@
+import {
+ VOICE_OFFSCREEN_TARGET,
+ type VoiceFlushRequest,
+ type VoiceFlushResponse,
+ VoiceMessage,
+ type VoiceStepMark,
+ type VoiceTranscriptionSettings,
+ voiceMessage,
+} from '../voice/voice-message';
+import { answered } from './answered';
+
+export function flushVoiceCapture(
+ guideId: string,
+ step: VoiceStepMark,
+ settings: VoiceTranscriptionSettings,
+): Promise<VoiceFlushResponse> {
+ return answered<VoiceFlushResponse>(
+ voiceMessage<VoiceFlushRequest>({
+ type: VoiceMessage.VOICE_FLUSH,
+ target: VOICE_OFFSCREEN_TARGET,
+ guideId,
+ step,
+ settings,
+ }),
+ { ok: false, reason: 'stream-ended', error: 'The microphone host is no longer available' },
+ );
+}
diff --git a/src/lib/offscreen/get-voice-status.ts b/src/lib/offscreen/get-voice-status.ts
new file mode 100644
index 0000000..e15f0d8
--- /dev/null
+++ b/src/lib/offscreen/get-voice-status.ts
@@ -0,0 +1,12 @@
+import {
+ VOICE_OFFSCREEN_TARGET,
+ VoiceMessage,
+ type VoiceStatusRequest,
+ type VoiceStatusResponse,
+ voiceMessage,
+} from '../voice/voice-message';
+import { request } from './request';
+
+export function getVoiceStatus(): Promise<VoiceStatusResponse> {
+ return request(voiceMessage<VoiceStatusRequest>({ type: VoiceMessage.VOICE_STATUS, target: VOICE_OFFSCREEN_TARGET }));
+}
diff --git a/src/lib/offscreen/has-offscreen-document.ts b/src/lib/offscreen/has-offscreen-document.ts
new file mode 100644
index 0000000..ece1d7f
--- /dev/null
+++ b/src/lib/offscreen/has-offscreen-document.ts
@@ -0,0 +1,21 @@
+const OFFSCREEN_CONTEXT = 'OFFSCREEN_DOCUMENT';
+
+interface ContextsApi {
+ getContexts(filter: { contextTypes: string[] }): Promise<unknown[]>;
+}
+
+function contextsApi(): ContextsApi | undefined {
+ const runtime = (globalThis as { chrome?: { runtime?: Partial<ContextsApi> } }).chrome?.runtime;
+ return typeof runtime?.getContexts === 'function' ? (runtime as ContextsApi) : undefined;
+}
+
+export async function hasOffscreenDocument(): Promise<boolean> {
+ const api = contextsApi();
+ if (!api) return false;
+ try {
+ const contexts = await api.getContexts({ contextTypes: [OFFSCREEN_CONTEXT] });
+ return contexts.length > 0;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/lib/offscreen/has-voice-host.ts b/src/lib/offscreen/has-voice-host.ts
new file mode 100644
index 0000000..9b0eed0
--- /dev/null
+++ b/src/lib/offscreen/has-voice-host.ts
@@ -0,0 +1,9 @@
+import { isVoiceStatus } from '../voice/is-voice-status';
+import { IS_FIREFOX } from './constants';
+import { getVoiceStatus } from './get-voice-status';
+import { hasOffscreenDocument } from './has-offscreen-document';
+
+export async function hasVoiceHost(): Promise<boolean> {
+ if (!IS_FIREFOX) return hasOffscreenDocument();
+ return isVoiceStatus(await getVoiceStatus().catch(() => null));
+}
diff --git a/src/lib/offscreen/offscreen-api.ts b/src/lib/offscreen/offscreen-api.ts
new file mode 100644
index 0000000..46cc822
--- /dev/null
+++ b/src/lib/offscreen/offscreen-api.ts
@@ -0,0 +1,8 @@
+interface OffscreenApi {
+ createDocument(options: { url: string; reasons: string[]; justification: string }): Promise<void>;
+ closeDocument(): Promise<void>;
+}
+
+export function offscreenApi(): OffscreenApi | undefined {
+ return (globalThis as { chrome?: { offscreen?: OffscreenApi } }).chrome?.offscreen;
+}
diff --git a/src/lib/offscreen/open-mic-permission-page.ts b/src/lib/offscreen/open-mic-permission-page.ts
new file mode 100644
index 0000000..e126b45
--- /dev/null
+++ b/src/lib/offscreen/open-mic-permission-page.ts
@@ -0,0 +1,16 @@
+import { createTab } from '../browser-api/create-tab';
+import { getExtensionURL } from '../browser-api/get-extension-url';
+import { localVoiceHost } from '../voice/local-voice-host';
+import { IS_FIREFOX } from './constants';
+import { promptForMicrophone } from './prompt-for-microphone';
+
+const MIC_PERMISSION_PATH = '/mic-permission.html';
+
+export function openMicPermissionPage(tabId?: number): Promise<unknown> {
+ if (IS_FIREFOX) {
+ if (localVoiceHost.current === null) return Promise.resolve(undefined);
+ return promptForMicrophone();
+ }
+ const url = getExtensionURL(tabId === undefined ? MIC_PERMISSION_PATH : `${MIC_PERMISSION_PATH}?tabId=${tabId}`);
+ return createTab({ url, active: true });
+}
diff --git a/src/lib/offscreen/prompt-for-microphone.ts b/src/lib/offscreen/prompt-for-microphone.ts
new file mode 100644
index 0000000..ce5dd5b
--- /dev/null
+++ b/src/lib/offscreen/prompt-for-microphone.ts
@@ -0,0 +1,30 @@
+import { logger } from '@mimik/core/logger';
+import { sendMessage } from '../browser-api/send-message';
+import {
+ VOICE_BACKGROUND_TARGET,
+ VoiceMessage,
+ type VoicePermissionResultEvent,
+ voiceMessage,
+} from '../voice/voice-message';
+
+async function requestMicrophoneInPage(): Promise<boolean> {
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ for (const track of stream.getTracks()) track.stop();
+ return true;
+ } catch (error) {
+ logger.warn('voice: microphone access was not granted', error);
+ return false;
+ }
+}
+
+export async function promptForMicrophone(): Promise<void> {
+ const granted = await requestMicrophoneInPage();
+ void sendMessage(
+ voiceMessage<VoicePermissionResultEvent>({
+ type: VoiceMessage.VOICE_PERMISSION_RESULT,
+ target: VOICE_BACKGROUND_TARGET,
+ state: granted ? 'granted' : 'denied',
+ }) as unknown as Record<string, unknown>,
+ ).catch(() => undefined);
+}
diff --git a/src/lib/offscreen/query-mic-permission.ts b/src/lib/offscreen/query-mic-permission.ts
new file mode 100644
index 0000000..fa4a55b
--- /dev/null
+++ b/src/lib/offscreen/query-mic-permission.ts
@@ -0,0 +1,17 @@
+import {
+ VOICE_OFFSCREEN_TARGET,
+ VoiceMessage,
+ type VoicePermissionQueryRequest,
+ type VoicePermissionQueryResponse,
+ voiceMessage,
+} from '../voice/voice-message';
+import { request } from './request';
+
+export function queryMicPermission(): Promise<VoicePermissionQueryResponse> {
+ return request(
+ voiceMessage<VoicePermissionQueryRequest>({
+ type: VoiceMessage.VOICE_PERMISSION_QUERY,
+ target: VOICE_OFFSCREEN_TARGET,
+ }),
+ );
+}
diff --git a/src/lib/offscreen/register-voice-panel-relay.ts b/src/lib/offscreen/register-voice-panel-relay.ts
new file mode 100644
index 0000000..12a435f
--- /dev/null
+++ b/src/lib/offscreen/register-voice-panel-relay.ts
@@ -0,0 +1,14 @@
+import { onMessage } from '../browser-api/on-message';
+import { sendMessage } from '../browser-api/send-message';
+import { isVoiceMessageFor } from '../voice/is-voice-message-for';
+import { VOICE_SIDEPANEL_TARGET } from '../voice/voice-message';
+import { IS_FIREFOX } from './constants';
+
+export function registerVoicePanelRelay(): void {
+ if (!IS_FIREFOX) return;
+ onMessage((message) => {
+ if (!isVoiceMessageFor(VOICE_SIDEPANEL_TARGET, message)) return undefined;
+ void sendMessage(message as unknown as Record<string, unknown>).catch(() => undefined);
+ return undefined;
+ });
+}
diff --git a/src/lib/offscreen/request.ts b/src/lib/offscreen/request.ts
new file mode 100644
index 0000000..cf1823f
--- /dev/null
+++ b/src/lib/offscreen/request.ts
@@ -0,0 +1,10 @@
+import { sendMessage } from '../browser-api/send-message';
+import { localVoiceHost } from '../voice/local-voice-host';
+import type { VoiceRequest } from '../voice/voice-message';
+import { IS_FIREFOX } from './constants';
+
+export function request<T>(message: VoiceRequest): Promise<T> {
+ const local = IS_FIREFOX ? localVoiceHost.current : null;
+ if (local) return local.handle(message) as Promise<T>;
+ return sendMessage(message as unknown as Record<string, unknown>) as Promise<T>;
+}
diff --git a/src/lib/offscreen/start-voice-capture.ts b/src/lib/offscreen/start-voice-capture.ts
new file mode 100644
index 0000000..0c2ce43
--- /dev/null
+++ b/src/lib/offscreen/start-voice-capture.ts
@@ -0,0 +1,15 @@
+import {
+ VOICE_OFFSCREEN_TARGET,
+ VoiceMessage,
+ type VoiceStartRequest,
+ type VoiceStartResponse,
+ voiceMessage,
+} from '../voice/voice-message';
+import { answered } from './answered';
+
+export function startVoiceCapture(deviceId?: string): Promise<VoiceStartResponse> {
+ return answered<VoiceStartResponse>(
+ voiceMessage<VoiceStartRequest>({ type: VoiceMessage.VOICE_START, target: VOICE_OFFSCREEN_TARGET, deviceId }),
+ { started: false, reason: 'unsupported', error: 'No microphone host is available' },
+ );
+}
diff --git a/src/lib/offscreen/stop-voice-capture.ts b/src/lib/offscreen/stop-voice-capture.ts
new file mode 100644
index 0000000..54c729d
--- /dev/null
+++ b/src/lib/offscreen/stop-voice-capture.ts
@@ -0,0 +1,27 @@
+import {
+ VOICE_OFFSCREEN_TARGET,
+ VoiceMessage,
+ type VoiceStepMark,
+ type VoiceStopRequest,
+ type VoiceStopResponse,
+ type VoiceTranscriptionSettings,
+ voiceMessage,
+} from '../voice/voice-message';
+import { answered } from './answered';
+
+export function stopVoiceCapture(
+ guideId: string,
+ steps: VoiceStepMark[],
+ settings: VoiceTranscriptionSettings,
+): Promise<VoiceStopResponse> {
+ return answered<VoiceStopResponse>(
+ voiceMessage<VoiceStopRequest>({
+ type: VoiceMessage.VOICE_STOP,
+ target: VOICE_OFFSCREEN_TARGET,
+ guideId,
+ steps,
+ settings,
+ }),
+ { ok: false, reason: 'stream-ended', error: 'The microphone host is no longer available' },
+ );
+}
diff --git a/src/lib/offscreen/supports-offscreen.ts b/src/lib/offscreen/supports-offscreen.ts
new file mode 100644
index 0000000..de0c050
--- /dev/null
+++ b/src/lib/offscreen/supports-offscreen.ts
@@ -0,0 +1,5 @@
+import { offscreenApi } from './offscreen-api';
+
+export function supportsOffscreen(): boolean {
+ return offscreenApi() !== undefined;
+}
diff --git a/src/lib/offscreen/supports-voice.ts b/src/lib/offscreen/supports-voice.ts
new file mode 100644
index 0000000..aed5747
--- /dev/null
+++ b/src/lib/offscreen/supports-voice.ts
@@ -0,0 +1,6 @@
+import { IS_FIREFOX } from './constants';
+import { supportsOffscreen } from './supports-offscreen';
+
+export function supportsVoice(): boolean {
+ return IS_FIREFOX || supportsOffscreen();
+}
diff --git a/src/lib/port.ts b/src/lib/port.ts
deleted file mode 100644
index e19d772..0000000
--- a/src/lib/port.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-import { logger } from '@mimik/core/logger';
-import { browser } from '#imports';
-import type { AiFailureReason } from '@/core/capture/ai/errors';
-import type { CaptureStateValue } from '@/core/capture/machine';
-import type { VoiceErrorReason } from '@/lib/voice-messages';
-
-const PORT_NAME = 'mimik-panel';
-const OBSERVER_PORT_NAME = 'mimik-panel-observer';
-
-export interface PanelStateUpdate {
- type: 'STATE_UPDATE';
- state: CaptureStateValue;
- stepCount: number;
- currentGuideId: string | null;
-}
-
-export type VoicePhase = 'idle' | 'recording' | 'transcribing' | 'error';
-
-export interface PanelVoiceUpdate {
- type: 'VOICE_UPDATE';
- phase: VoicePhase;
- reason?: VoiceErrorReason;
- error?: string;
- narrated?: number;
-}
-
-export interface PanelAiUpdate {
- type: 'AI_UPDATE';
- reason: AiFailureReason;
- status?: number;
- provider: string;
-}
-
-type PortMessage = PanelStateUpdate | PanelVoiceUpdate | PanelAiUpdate;
-type Port = ReturnType<typeof browser.runtime.connect>;
-
-function openPort(
- name: string,
- onPortMessage: (msg: PortMessage) => void,
- onConnect?: () => void,
- onDisconnect?: () => void,
-): () => void {
- let port: Port | null = null;
- let destroyed = false;
-
- function connect() {
- if (destroyed) return;
-
- try {
- port = browser.runtime.connect({ name });
- logger.debug('Port connected to background', name);
- onConnect?.();
-
- port.onMessage.addListener(onPortMessage);
-
- port.onDisconnect.addListener(() => {
- port = null;
- if (!destroyed) {
- logger.debug('Port disconnected, reconnecting in 1s...');
- onDisconnect?.();
- setTimeout(connect, 1000);
- }
- });
- } catch {
- if (!destroyed) {
- logger.debug('Port connect failed, retrying in 1s...');
- setTimeout(connect, 1000);
- }
- }
- }
-
- connect();
-
- return () => {
- destroyed = true;
- port?.disconnect();
- port = null;
- };
-}
-
-export function connectToBackground(callbacks: {
- onStateUpdate: (update: PanelStateUpdate) => void;
- onConnect: () => void;
- onDisconnect: () => void;
- onVoiceUpdate?: (update: PanelVoiceUpdate) => void;
- onAiUpdate?: (update: PanelAiUpdate) => void;
-}): () => void {
- return openPort(
- PORT_NAME,
- (msg) => {
- if (msg.type === 'STATE_UPDATE') {
- callbacks.onStateUpdate(msg);
- } else if (msg.type === 'VOICE_UPDATE') {
- callbacks.onVoiceUpdate?.(msg);
- } else if (msg.type === 'AI_UPDATE') {
- callbacks.onAiUpdate?.(msg);
- }
- },
- callbacks.onConnect,
- callbacks.onDisconnect,
- );
-}
-
-export function observeVoiceFromBackground(
- onVoiceUpdate: (update: PanelVoiceUpdate) => void,
- onConnect?: () => void,
-): () => void {
- return openPort(
- OBSERVER_PORT_NAME,
- (msg) => {
- if (msg.type === 'VOICE_UPDATE') onVoiceUpdate(msg);
- },
- onConnect,
- );
-}
-
-const panelPorts = new Set<Port>();
-const observerPorts = new Set<Port>();
-let lastVoiceUpdate: PanelVoiceUpdate | null = null;
-
-export function setupPortListener(onPanelConnect?: (port: Port) => void) {
- browser.runtime.onConnect.addListener((port) => {
- if (port.name === OBSERVER_PORT_NAME) {
- observerPorts.add(port);
- if (lastVoiceUpdate) postTo(port, lastVoiceUpdate);
- port.onDisconnect.addListener(() => {
- observerPorts.delete(port);
- });
- return;
- }
-
- if (port.name !== PORT_NAME) return;
-
- panelPorts.add(port);
- onPanelConnect?.(port);
-
- port.onDisconnect.addListener(() => {
- panelPorts.delete(port);
- });
- });
-}
-
-function postTo(port: Port, message: PortMessage): boolean {
- try {
- port.postMessage(message);
- return true;
- } catch {
- return false;
- }
-}
-
-function broadcastTo(ports: Set<Port>, message: PortMessage): void {
- for (const port of ports) {
- if (!postTo(port, message)) ports.delete(port);
- }
-}
-
-export function broadcastStateToPanel(update: PanelStateUpdate): void {
- broadcastTo(panelPorts, update);
-}
-
-export function broadcastAiToPanel(update: PanelAiUpdate): void {
- broadcastTo(panelPorts, update);
-}
-
-export function broadcastVoiceToPanel(update: PanelVoiceUpdate): void {
- lastVoiceUpdate = update;
- broadcastTo(panelPorts, update);
- broadcastTo(observerPorts, update);
-}
diff --git a/src/lib/port/broadcast-ai-to-panel.ts b/src/lib/port/broadcast-ai-to-panel.ts
new file mode 100644
index 0000000..6a3f005
--- /dev/null
+++ b/src/lib/port/broadcast-ai-to-panel.ts
@@ -0,0 +1,7 @@
+import { broadcastTo } from './broadcast-to';
+import { panelPorts } from './state';
+import type { PanelAiUpdate } from './types';
+
+export function broadcastAiToPanel(update: PanelAiUpdate): void {
+ broadcastTo(panelPorts, update);
+}
diff --git a/src/lib/port/broadcast-state-to-panel.ts b/src/lib/port/broadcast-state-to-panel.ts
new file mode 100644
index 0000000..0ba43a8
--- /dev/null
+++ b/src/lib/port/broadcast-state-to-panel.ts
@@ -0,0 +1,7 @@
+import { broadcastTo } from './broadcast-to';
+import { panelPorts } from './state';
+import type { PanelStateUpdate } from './types';
+
+export function broadcastStateToPanel(update: PanelStateUpdate): void {
+ broadcastTo(panelPorts, update);
+}
diff --git a/src/lib/port/broadcast-to.ts b/src/lib/port/broadcast-to.ts
new file mode 100644
index 0000000..f2817a4
--- /dev/null
+++ b/src/lib/port/broadcast-to.ts
@@ -0,0 +1,8 @@
+import { postTo } from './post-to';
+import type { Port, PortMessage } from './types';
+
+export function broadcastTo(ports: Set<Port>, message: PortMessage): void {
+ for (const port of ports) {
+ if (!postTo(port, message)) ports.delete(port);
+ }
+}
diff --git a/src/lib/port/broadcast-voice-to-panel.ts b/src/lib/port/broadcast-voice-to-panel.ts
new file mode 100644
index 0000000..5db8dbb
--- /dev/null
+++ b/src/lib/port/broadcast-voice-to-panel.ts
@@ -0,0 +1,9 @@
+import { broadcastTo } from './broadcast-to';
+import { lastVoice, observerPorts, panelPorts } from './state';
+import type { PanelVoiceUpdate } from './types';
+
+export function broadcastVoiceToPanel(update: PanelVoiceUpdate): void {
+ lastVoice.current = update;
+ broadcastTo(panelPorts, update);
+ broadcastTo(observerPorts, update);
+}
diff --git a/src/lib/port/connect-to-background.ts b/src/lib/port/connect-to-background.ts
new file mode 100644
index 0000000..9b750b8
--- /dev/null
+++ b/src/lib/port/connect-to-background.ts
@@ -0,0 +1,26 @@
+import { PORT_NAME } from './constants';
+import { openPort } from './open-port';
+import type { PanelAiUpdate, PanelStateUpdate, PanelVoiceUpdate } from './types';
+
+export function connectToBackground(callbacks: {
+ onStateUpdate: (update: PanelStateUpdate) => void;
+ onConnect: () => void;
+ onDisconnect: () => void;
+ onVoiceUpdate?: (update: PanelVoiceUpdate) => void;
+ onAiUpdate?: (update: PanelAiUpdate) => void;
+}): () => void {
+ return openPort(
+ PORT_NAME,
+ (msg) => {
+ if (msg.type === 'STATE_UPDATE') {
+ callbacks.onStateUpdate(msg);
+ } else if (msg.type === 'VOICE_UPDATE') {
+ callbacks.onVoiceUpdate?.(msg);
+ } else if (msg.type === 'AI_UPDATE') {
+ callbacks.onAiUpdate?.(msg);
+ }
+ },
+ callbacks.onConnect,
+ callbacks.onDisconnect,
+ );
+}
diff --git a/src/lib/port/constants.ts b/src/lib/port/constants.ts
new file mode 100644
index 0000000..d19f461
--- /dev/null
+++ b/src/lib/port/constants.ts
@@ -0,0 +1,3 @@
+export const PORT_NAME = 'mimik-panel';
+
+export const OBSERVER_PORT_NAME = 'mimik-panel-observer';
diff --git a/src/lib/port/observe-voice-from-background.ts b/src/lib/port/observe-voice-from-background.ts
new file mode 100644
index 0000000..12d110a
--- /dev/null
+++ b/src/lib/port/observe-voice-from-background.ts
@@ -0,0 +1,16 @@
+import { OBSERVER_PORT_NAME } from './constants';
+import { openPort } from './open-port';
+import type { PanelVoiceUpdate } from './types';
+
+export function observeVoiceFromBackground(
+ onVoiceUpdate: (update: PanelVoiceUpdate) => void,
+ onConnect?: () => void,
+): () => void {
+ return openPort(
+ OBSERVER_PORT_NAME,
+ (msg) => {
+ if (msg.type === 'VOICE_UPDATE') onVoiceUpdate(msg);
+ },
+ onConnect,
+ );
+}
diff --git a/src/lib/port/open-port.ts b/src/lib/port/open-port.ts
new file mode 100644
index 0000000..1640d76
--- /dev/null
+++ b/src/lib/port/open-port.ts
@@ -0,0 +1,47 @@
+import { logger } from '@mimik/core/logger';
+import { browser } from '#imports';
+import type { Port, PortMessage } from './types';
+
+export function openPort(
+ name: string,
+ onPortMessage: (msg: PortMessage) => void,
+ onConnect?: () => void,
+ onDisconnect?: () => void,
+): () => void {
+ let port: Port | null = null;
+ let destroyed = false;
+
+ function connect() {
+ if (destroyed) return;
+
+ try {
+ port = browser.runtime.connect({ name });
+ logger.debug('Port connected to background', name);
+ onConnect?.();
+
+ port.onMessage.addListener(onPortMessage);
+
+ port.onDisconnect.addListener(() => {
+ port = null;
+ if (!destroyed) {
+ logger.debug('Port disconnected, reconnecting in 1s...');
+ onDisconnect?.();
+ setTimeout(connect, 1000);
+ }
+ });
+ } catch {
+ if (!destroyed) {
+ logger.debug('Port connect failed, retrying in 1s...');
+ setTimeout(connect, 1000);
+ }
+ }
+ }
+
+ connect();
+
+ return () => {
+ destroyed = true;
+ port?.disconnect();
+ port = null;
+ };
+}
diff --git a/src/lib/port/post-to.ts b/src/lib/port/post-to.ts
new file mode 100644
index 0000000..e7eb3f7
--- /dev/null
+++ b/src/lib/port/post-to.ts
@@ -0,0 +1,10 @@
+import type { Port, PortMessage } from './types';
+
+export function postTo(port: Port, message: PortMessage): boolean {
+ try {
+ port.postMessage(message);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/lib/port/setup-port-listener.ts b/src/lib/port/setup-port-listener.ts
new file mode 100644
index 0000000..889ffce
--- /dev/null
+++ b/src/lib/port/setup-port-listener.ts
@@ -0,0 +1,27 @@
+import { browser } from '#imports';
+import { OBSERVER_PORT_NAME, PORT_NAME } from './constants';
+import { postTo } from './post-to';
+import { lastVoice, observerPorts, panelPorts } from './state';
+import type { Port } from './types';
+
+export function setupPortListener(onPanelConnect?: (port: Port) => void) {
+ browser.runtime.onConnect.addListener((port) => {
+ if (port.name === OBSERVER_PORT_NAME) {
+ observerPorts.add(port);
+ if (lastVoice.current) postTo(port, lastVoice.current);
+ port.onDisconnect.addListener(() => {
+ observerPorts.delete(port);
+ });
+ return;
+ }
+
+ if (port.name !== PORT_NAME) return;
+
+ panelPorts.add(port);
+ onPanelConnect?.(port);
+
+ port.onDisconnect.addListener(() => {
+ panelPorts.delete(port);
+ });
+ });
+}
diff --git a/src/lib/port/state.ts b/src/lib/port/state.ts
new file mode 100644
index 0000000..9e843ce
--- /dev/null
+++ b/src/lib/port/state.ts
@@ -0,0 +1,7 @@
+import type { PanelVoiceUpdate, Port } from './types';
+
+export const panelPorts = new Set<Port>();
+
+export const observerPorts = new Set<Port>();
+
+export const lastVoice: { current: PanelVoiceUpdate | null } = { current: null };
diff --git a/src/lib/port/types.ts b/src/lib/port/types.ts
new file mode 100644
index 0000000..9313dd3
--- /dev/null
+++ b/src/lib/port/types.ts
@@ -0,0 +1,32 @@
+import type { browser } from '#imports';
+import type { AiFailureReason } from '@/core/capture/ai/errors';
+import type { CaptureStateValue } from '@/core/capture/machine';
+import type { VoiceErrorReason } from '@/lib/voice/voice-message';
+
+export interface PanelStateUpdate {
+ type: 'STATE_UPDATE';
+ state: CaptureStateValue;
+ stepCount: number;
+ currentGuideId: string | null;
+}
+
+export type VoicePhase = 'idle' | 'recording' | 'transcribing' | 'error';
+
+export interface PanelVoiceUpdate {
+ type: 'VOICE_UPDATE';
+ phase: VoicePhase;
+ reason?: VoiceErrorReason;
+ error?: string;
+ narrated?: number;
+}
+
+export interface PanelAiUpdate {
+ type: 'AI_UPDATE';
+ reason: AiFailureReason;
+ status?: number;
+ provider: string;
+}
+
+export type PortMessage = PanelStateUpdate | PanelVoiceUpdate | PanelAiUpdate;
+
+export type Port = ReturnType<typeof browser.runtime.connect>;
diff --git a/src/lib/ui-env.ts b/src/lib/ui-env.ts
index 31cb097..788e507 100644
--- a/src/lib/ui-env.ts
+++ b/src/lib/ui-env.ts
@@ -1,16 +1,14 @@
import { configureUi } from '@mimik/ui/env';
import { getRecordableTabs } from '@/capture/recordable-tabs';
import { startInsertRecording } from '@/capture/start-insert-recording';
-import {
- createTab,
- focusWindow,
- getActiveTab,
- getTab,
- openSidebar,
- queryTabs,
- requestHostPermissions,
- updateTab,
-} from '@/lib/browser-api';
+import { createTab } from '@/lib/browser-api/create-tab';
+import { focusWindow } from '@/lib/browser-api/focus-window';
+import { getActiveTab } from '@/lib/browser-api/get-active-tab';
+import { getTab } from '@/lib/browser-api/get-tab';
+import { openSidebar } from '@/lib/browser-api/open-sidebar';
+import { queryTabs } from '@/lib/browser-api/query-tabs';
+import { requestHostPermissions } from '@/lib/browser-api/request-host-permissions';
+import { updateTab } from '@/lib/browser-api/update-tab';
import { sendMessage } from '@/lib/messaging';
configureUi({
diff --git a/src/lib/update-notice.ts b/src/lib/update-notice.ts
deleted file mode 100644
index 5959222..0000000
--- a/src/lib/update-notice.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { browser } from '#imports';
-
-export const UPDATE_NOTICE_KEY = 'updateNotice';
-
-export async function recordUpdate(reason: string): Promise<void> {
- if (reason !== 'update') return;
- await browser.storage.local.set({ [UPDATE_NOTICE_KEY]: browser.runtime.getManifest().version });
-}
-
-export async function readUpdateNotice(): Promise<string | undefined> {
- const data = await browser.storage.local.get([UPDATE_NOTICE_KEY]);
- return data?.[UPDATE_NOTICE_KEY] as string | undefined;
-}
-
-export function dismissUpdateNotice(): Promise<void> {
- return browser.storage.local.remove(UPDATE_NOTICE_KEY);
-}
diff --git a/src/lib/update-notice/constants.ts b/src/lib/update-notice/constants.ts
new file mode 100644
index 0000000..1f91502
--- /dev/null
+++ b/src/lib/update-notice/constants.ts
@@ -0,0 +1 @@
+export const UPDATE_NOTICE_KEY = 'updateNotice';
diff --git a/src/lib/update-notice/dismiss-update-notice.ts b/src/lib/update-notice/dismiss-update-notice.ts
new file mode 100644
index 0000000..42caf1c
--- /dev/null
+++ b/src/lib/update-notice/dismiss-update-notice.ts
@@ -0,0 +1,6 @@
+import { browser } from '#imports';
+import { UPDATE_NOTICE_KEY } from './constants';
+
+export function dismissUpdateNotice(): Promise<void> {
+ return browser.storage.local.remove(UPDATE_NOTICE_KEY);
+}
diff --git a/src/lib/update-notice/read-update-notice.ts b/src/lib/update-notice/read-update-notice.ts
new file mode 100644
index 0000000..4645b84
--- /dev/null
+++ b/src/lib/update-notice/read-update-notice.ts
@@ -0,0 +1,7 @@
+import { browser } from '#imports';
+import { UPDATE_NOTICE_KEY } from './constants';
+
+export async function readUpdateNotice(): Promise<string | undefined> {
+ const data = await browser.storage.local.get([UPDATE_NOTICE_KEY]);
+ return data?.[UPDATE_NOTICE_KEY] as string | undefined;
+}
diff --git a/src/lib/update-notice/record-update.ts b/src/lib/update-notice/record-update.ts
new file mode 100644
index 0000000..509ffb4
--- /dev/null
+++ b/src/lib/update-notice/record-update.ts
@@ -0,0 +1,7 @@
+import { browser } from '#imports';
+import { UPDATE_NOTICE_KEY } from './constants';
+
+export async function recordUpdate(reason: string): Promise<void> {
+ if (reason !== 'update') return;
+ await browser.storage.local.set({ [UPDATE_NOTICE_KEY]: browser.runtime.getManifest().version });
+}
diff --git a/src/lib/voice-local.ts b/src/lib/voice-local.ts
deleted file mode 100644
index 494f74e..0000000
--- a/src/lib/voice-local.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { VoiceRequest } from './voice-messages';
-
-export interface LocalVoiceHost {
- handle(request: VoiceRequest): Promise<unknown>;
-}
-
-let host: LocalVoiceHost | null = null;
-
-export function setLocalVoiceHost(next: LocalVoiceHost | null): void {
- host = next;
-}
-
-export function localVoiceHost(): LocalVoiceHost | null {
- return host;
-}
diff --git a/src/lib/voice-recovery.ts b/src/lib/voice-recovery.ts
deleted file mode 100644
index 46c4389..0000000
--- a/src/lib/voice-recovery.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import type { VoiceStatusResponse } from './voice-messages';
-
-export type VoiceStopAction = 'stop-host' | 'recover' | 'report-lost' | 'skip';
-
-export function isVoiceStatus(value: unknown): value is VoiceStatusResponse {
- if (typeof value !== 'object' || value === null) return false;
- const candidate = value as Partial<VoiceStatusResponse>;
- return typeof candidate.recording === 'boolean' && typeof candidate.transcribing === 'boolean';
-}
-
-export function handedOffPcm(value: unknown): Int16Array | null {
- if (value instanceof Int16Array) return value.length > 0 ? value : null;
- if (value instanceof ArrayBuffer) return value.byteLength > 0 ? new Int16Array(value) : null;
- if (ArrayBuffer.isView(value)) {
- return value.byteLength > 0 ? new Int16Array(value.buffer, value.byteOffset, value.byteLength / 2) : null;
- }
- return null;
-}
-
-export function voiceStopAction(input: {
- hostAlive: boolean;
- hasOrphanAudio: boolean;
- wasRecording: boolean;
-}): VoiceStopAction {
- if (input.hasOrphanAudio) return 'recover';
- if (input.hostAlive) return 'stop-host';
- return input.wasRecording ? 'report-lost' : 'skip';
-}
diff --git a/src/lib/voice/concat.ts b/src/lib/voice/concat.ts
new file mode 100644
index 0000000..34a7317
--- /dev/null
+++ b/src/lib/voice/concat.ts
@@ -0,0 +1,9 @@
+export function concat(chunks: Int16Array[], samples: number): Int16Array {
+ const pcm = new Int16Array(samples);
+ let offset = 0;
+ for (const chunk of chunks) {
+ pcm.set(chunk, offset);
+ offset += chunk.length;
+ }
+ return pcm;
+}
diff --git a/src/lib/voice-host.ts b/src/lib/voice/create-voice-host.ts
similarity index 76%
rename from src/lib/voice-host.ts
rename to src/lib/voice/create-voice-host.ts
index 4733a4e..511ffb6 100644
--- a/src/lib/voice-host.ts
+++ b/src/lib/voice/create-voice-host.ts
@@ -1,24 +1,26 @@
import { logger } from '@mimik/core/logger';
import { partialRecording } from '@/core/capture/voice/partial-recording';
import type { NarrationResult } from '@/core/capture/voice/types';
-import { getExtensionURL, onMessage, sendMessage } from './browser-api';
-import { MicRecorder, type MicRecording } from './mic-recorder';
+import { getExtensionURL } from '../browser-api/get-extension-url';
+import { sendMessage } from '../browser-api/send-message';
+import { describeError } from './describe-error';
+import { MicRecorder } from './mic-recorder';
+import { EMPTY_NARRATION, narrateRecording, type VoiceRecording } from './narrate-recording';
+import { permissionState } from './permission-state';
+import type { TranscriptionSettings } from './read-transcription-settings';
+import { startFailureReason } from './start-failure-reason';
+import { usableRecording } from './usable-recording';
import {
- isVoiceMessageFor,
VOICE_BACKGROUND_TARGET,
- VOICE_OFFSCREEN_TARGET,
VOICE_SIDEPANEL_TARGET,
type VoiceEpochEvent,
type VoiceErrorEvent,
- type VoiceErrorReason,
type VoiceEvent,
type VoiceFlushRequest,
type VoiceFlushResponse,
type VoiceHandoffEvent,
type VoiceLevelEvent,
VoiceMessage,
- type VoicePermissionQueryResponse,
- type VoicePermissionState,
type VoiceRequest,
type VoiceResultEvent,
type VoiceStartRequest,
@@ -27,8 +29,7 @@ import {
type VoiceStopRequest,
type VoiceStopResponse,
voiceMessage,
-} from './voice-messages';
-import { EMPTY_NARRATION, narrateRecording, type TranscriptionSettings, type VoiceRecording } from './voice-narration';
+} from './voice-message';
export interface VoiceHost {
handle(request: VoiceRequest): Promise<unknown>;
@@ -40,37 +41,6 @@ function emit(event: VoiceEvent): void {
void sendMessage(event as unknown as Record<string, unknown>).catch(() => undefined);
}
-function describe(error: unknown): string {
- return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
-}
-
-function startFailureReason(error: unknown): VoiceErrorReason {
- if (!(error instanceof Error)) return 'unknown';
- if (error.name === 'NotAllowedError' || error.name === 'SecurityError') return 'permission-denied';
- if (error.name === 'NotFoundError' || error.name === 'OverconstrainedError') return 'no-device';
- if (error.name === 'NotSupportedError') return 'unsupported';
- return 'unknown';
-}
-
-function usableRecording(recording: MicRecording): VoiceRecording | null {
- if (recording.audioEpochMs === null || recording.pcm.length === 0) return null;
- return {
- pcm: recording.pcm,
- sampleRate: recording.sampleRate,
- audioEpochMs: recording.audioEpochMs,
- durationSeconds: recording.durationSeconds,
- };
-}
-
-async function permissionState(): Promise<VoicePermissionQueryResponse> {
- try {
- const result = await navigator.permissions.query({ name: 'microphone' as PermissionName });
- return { state: result.state as VoicePermissionState };
- } catch {
- return { state: 'unknown' };
- }
-}
-
export function createVoiceHost(): VoiceHost {
let pending = 0;
let retained: VoiceRecording | null = null;
@@ -144,7 +114,7 @@ export function createVoiceHost(): VoiceHost {
} catch (error) {
recorder.release();
logger.error('voice: microphone capture failed to start', error);
- return { started: false, reason: startFailureReason(error), error: describe(error) };
+ return { started: false, reason: startFailureReason(error), error: describeError(error) };
}
}
@@ -263,21 +233,3 @@ export function createVoiceHost(): VoiceHost {
return { handle, status, surrender };
}
-
-export function startVoiceHost(): VoiceHost {
- const host = createVoiceHost();
-
- onMessage((message, _sender, sendResponse) => {
- if (!isVoiceMessageFor(VOICE_OFFSCREEN_TARGET, message)) return undefined;
- host
- .handle(message as VoiceRequest)
- .then(sendResponse)
- .catch((error: unknown) => {
- logger.error('voice: host could not handle request', message, error);
- sendResponse({ ok: false, started: false, reason: 'unknown', error: String(error) });
- });
- return true;
- });
-
- return host;
-}
diff --git a/src/lib/voice/describe-error.ts b/src/lib/voice/describe-error.ts
new file mode 100644
index 0000000..d289566
--- /dev/null
+++ b/src/lib/voice/describe-error.ts
@@ -0,0 +1,3 @@
+export function describeError(error: unknown): string {
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
+}
diff --git a/src/lib/voice/handed-off-pcm.ts b/src/lib/voice/handed-off-pcm.ts
new file mode 100644
index 0000000..956817e
--- /dev/null
+++ b/src/lib/voice/handed-off-pcm.ts
@@ -0,0 +1,8 @@
+export function handedOffPcm(value: unknown): Int16Array | null {
+ if (value instanceof Int16Array) return value.length > 0 ? value : null;
+ if (value instanceof ArrayBuffer) return value.byteLength > 0 ? new Int16Array(value) : null;
+ if (ArrayBuffer.isView(value)) {
+ return value.byteLength > 0 ? new Int16Array(value.buffer, value.byteOffset, value.byteLength / 2) : null;
+ }
+ return null;
+}
diff --git a/src/lib/voice/is-voice-message-for.ts b/src/lib/voice/is-voice-message-for.ts
new file mode 100644
index 0000000..28ee528
--- /dev/null
+++ b/src/lib/voice/is-voice-message-for.ts
@@ -0,0 +1,9 @@
+import { type VoiceEnvelope, VoiceMessage, type VoiceTarget } from './voice-message';
+
+export function isVoiceMessageFor(target: VoiceTarget, message: unknown): message is VoiceEnvelope {
+ if (typeof message !== 'object' || message === null) return false;
+ const candidate = message as Partial<VoiceEnvelope>;
+ return (
+ candidate.target === target && typeof candidate.type === 'string' && Object.hasOwn(VoiceMessage, candidate.type)
+ );
+}
diff --git a/src/lib/voice/is-voice-status.ts b/src/lib/voice/is-voice-status.ts
new file mode 100644
index 0000000..776c88f
--- /dev/null
+++ b/src/lib/voice/is-voice-status.ts
@@ -0,0 +1,7 @@
+import type { VoiceStatusResponse } from './voice-message';
+
+export function isVoiceStatus(value: unknown): value is VoiceStatusResponse {
+ if (typeof value !== 'object' || value === null) return false;
+ const candidate = value as Partial<VoiceStatusResponse>;
+ return typeof candidate.recording === 'boolean' && typeof candidate.transcribing === 'boolean';
+}
diff --git a/src/lib/voice/local-voice-host.ts b/src/lib/voice/local-voice-host.ts
new file mode 100644
index 0000000..6f3b166
--- /dev/null
+++ b/src/lib/voice/local-voice-host.ts
@@ -0,0 +1,7 @@
+import type { VoiceRequest } from './voice-message';
+
+export interface LocalVoiceHost {
+ handle(request: VoiceRequest): Promise<unknown>;
+}
+
+export const localVoiceHost: { current: LocalVoiceHost | null } = { current: null };
diff --git a/src/lib/mic-recorder.ts b/src/lib/voice/mic-recorder.ts
similarity index 80%
rename from src/lib/mic-recorder.ts
rename to src/lib/voice/mic-recorder.ts
index f47f48e..cb013b8 100644
--- a/src/lib/mic-recorder.ts
+++ b/src/lib/voice/mic-recorder.ts
@@ -1,4 +1,6 @@
import { SPEECH_RMS_THRESHOLD } from '@/core/capture/voice/energy-gate';
+import { concat } from './concat';
+import { openStream } from './open-stream';
export const TARGET_SAMPLE_RATE = 16000;
export const PCM_WORKLET_NAME = 'pcm-processor';
@@ -8,15 +10,6 @@ const LEVEL_FLOOR_DB = -60;
const LEVEL_SMOOTHING = 0.6;
const MS_PER_S = 1000;
-const AUDIO_CONSTRAINTS: MediaTrackConstraints = {
- channelCount: 1,
- echoCancellation: true,
- noiseSuppression: true,
- autoGainControl: true,
-};
-
-const DEVICE_ERRORS = ['OverconstrainedError', 'NotFoundError', 'NotReadableError'];
-
export interface MicRecorderEvents {
onEpoch(audioEpochMs: number): void;
onLevel(level: number, speaking: boolean): void;
@@ -35,35 +28,6 @@ export interface MicRecording {
durationSeconds: number;
}
-function isDeviceError(error: unknown): boolean {
- return error instanceof Error && DEVICE_ERRORS.includes(error.name);
-}
-
-async function openStream(deviceId?: string): Promise<{ stream: MediaStream; usedFallbackDevice: boolean }> {
- if (deviceId) {
- try {
- const stream = await navigator.mediaDevices.getUserMedia({
- audio: { ...AUDIO_CONSTRAINTS, deviceId: { exact: deviceId } },
- });
- return { stream, usedFallbackDevice: false };
- } catch (error) {
- if (!isDeviceError(error)) throw error;
- }
- }
- const stream = await navigator.mediaDevices.getUserMedia({ audio: AUDIO_CONSTRAINTS });
- return { stream, usedFallbackDevice: deviceId !== undefined };
-}
-
-function concat(chunks: Int16Array[], samples: number): Int16Array {
- const pcm = new Int16Array(samples);
- let offset = 0;
- for (const chunk of chunks) {
- pcm.set(chunk, offset);
- offset += chunk.length;
- }
- return pcm;
-}
-
export class MicRecorder {
private stream: MediaStream | null = null;
private context: AudioContext | null = null;
diff --git a/src/lib/voice-narration.ts b/src/lib/voice/narrate-recording.ts
similarity index 62%
rename from src/lib/voice-narration.ts
rename to src/lib/voice/narrate-recording.ts
index a75e284..d188cbc 100644
--- a/src/lib/voice-narration.ts
+++ b/src/lib/voice/narrate-recording.ts
@@ -1,18 +1,11 @@
import { logger } from '@mimik/core/logger';
-import { resolveVoiceApiKey, VOICE_KEY_SETTINGS } from '@/core/capture/voice/api-key';
import { detectSpeechByEnergy } from '@/core/capture/voice/energy-gate';
import { runNarrationPipeline } from '@/core/capture/voice/pipeline';
import { buildStepWindows } from '@/core/capture/voice/step-windows';
-import { createTranscriber, type VoiceProvider } from '@/core/capture/voice/transcribe';
+import { createTranscriber } from '@/core/capture/voice/transcribe';
import type { NarrationResult } from '@/core/capture/voice/types';
-import { localStorage } from './browser-api';
-import type { VoiceStepMark } from './voice-messages';
-
-export interface TranscriptionSettings {
- provider: VoiceProvider;
- apiKey: string;
- language?: string;
-}
+import type { TranscriptionSettings } from './read-transcription-settings';
+import type { VoiceStepMark } from './voice-message';
export interface VoiceRecording {
pcm: Int16Array;
@@ -34,17 +27,6 @@ export const EMPTY_NARRATION: NarrationResult = {
},
};
-export async function readTranscriptionSettings(): Promise<TranscriptionSettings> {
- const stored = await localStorage.get([...VOICE_KEY_SETTINGS, 'voiceLanguage', 'aiLanguage']);
- const { provider, apiKey } = resolveVoiceApiKey(stored);
- const locale = (stored.voiceLanguage ?? stored.aiLanguage) as string | undefined;
- return {
- provider,
- apiKey,
- language: locale ? locale.split('-')[0] : undefined,
- };
-}
-
export async function narrateRecording(
recording: VoiceRecording,
steps: VoiceStepMark[],
diff --git a/src/lib/voice/open-stream.ts b/src/lib/voice/open-stream.ts
new file mode 100644
index 0000000..08ad921
--- /dev/null
+++ b/src/lib/voice/open-stream.ts
@@ -0,0 +1,27 @@
+const AUDIO_CONSTRAINTS: MediaTrackConstraints = {
+ channelCount: 1,
+ echoCancellation: true,
+ noiseSuppression: true,
+ autoGainControl: true,
+};
+
+const DEVICE_ERRORS = ['OverconstrainedError', 'NotFoundError', 'NotReadableError'];
+
+function isDeviceError(error: unknown): boolean {
+ return error instanceof Error && DEVICE_ERRORS.includes(error.name);
+}
+
+export async function openStream(deviceId?: string): Promise<{ stream: MediaStream; usedFallbackDevice: boolean }> {
+ if (deviceId) {
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({
+ audio: { ...AUDIO_CONSTRAINTS, deviceId: { exact: deviceId } },
+ });
+ return { stream, usedFallbackDevice: false };
+ } catch (error) {
+ if (!isDeviceError(error)) throw error;
+ }
+ }
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: AUDIO_CONSTRAINTS });
+ return { stream, usedFallbackDevice: deviceId !== undefined };
+}
diff --git a/src/lib/voice/permission-state.ts b/src/lib/voice/permission-state.ts
new file mode 100644
index 0000000..3b47c56
--- /dev/null
+++ b/src/lib/voice/permission-state.ts
@@ -0,0 +1,10 @@
+import type { VoicePermissionQueryResponse, VoicePermissionState } from './voice-message';
+
+export async function permissionState(): Promise<VoicePermissionQueryResponse> {
+ try {
+ const result = await navigator.permissions.query({ name: 'microphone' as PermissionName });
+ return { state: result.state as VoicePermissionState };
+ } catch {
+ return { state: 'unknown' };
+ }
+}
diff --git a/src/lib/voice/read-transcription-settings.ts b/src/lib/voice/read-transcription-settings.ts
new file mode 100644
index 0000000..fdbb932
--- /dev/null
+++ b/src/lib/voice/read-transcription-settings.ts
@@ -0,0 +1,20 @@
+import { resolveVoiceApiKey, VOICE_KEY_SETTINGS } from '@/core/capture/voice/api-key';
+import type { VoiceProvider } from '@/core/capture/voice/transcribe';
+import { localStorage } from '../browser-api/local-storage';
+
+export interface TranscriptionSettings {
+ provider: VoiceProvider;
+ apiKey: string;
+ language?: string;
+}
+
+export async function readTranscriptionSettings(): Promise<TranscriptionSettings> {
+ const stored = await localStorage.get([...VOICE_KEY_SETTINGS, 'voiceLanguage', 'aiLanguage']);
+ const { provider, apiKey } = resolveVoiceApiKey(stored);
+ const locale = (stored.voiceLanguage ?? stored.aiLanguage) as string | undefined;
+ return {
+ provider,
+ apiKey,
+ language: locale ? locale.split('-')[0] : undefined,
+ };
+}
diff --git a/src/lib/voice/start-failure-reason.ts b/src/lib/voice/start-failure-reason.ts
new file mode 100644
index 0000000..39b68c9
--- /dev/null
+++ b/src/lib/voice/start-failure-reason.ts
@@ -0,0 +1,9 @@
+import type { VoiceErrorReason } from './voice-message';
+
+export function startFailureReason(error: unknown): VoiceErrorReason {
+ if (!(error instanceof Error)) return 'unknown';
+ if (error.name === 'NotAllowedError' || error.name === 'SecurityError') return 'permission-denied';
+ if (error.name === 'NotFoundError' || error.name === 'OverconstrainedError') return 'no-device';
+ if (error.name === 'NotSupportedError') return 'unsupported';
+ return 'unknown';
+}
diff --git a/src/lib/sidepanel-voice-host.ts b/src/lib/voice/start-sidepanel-voice-host.ts
similarity index 78%
rename from src/lib/sidepanel-voice-host.ts
rename to src/lib/voice/start-sidepanel-voice-host.ts
index a6d821c..50919d8 100644
--- a/src/lib/sidepanel-voice-host.ts
+++ b/src/lib/voice/start-sidepanel-voice-host.ts
@@ -1,13 +1,13 @@
import { logger } from '@mimik/core/logger';
-import { setLocalVoiceHost } from './voice-local';
+import { localVoiceHost } from './local-voice-host';
export function startSidepanelVoiceHost(): void {
if (import.meta.env.BROWSER !== 'firefox') return;
- void import('./voice-host')
+ void import('./start-voice-host')
.then(({ startVoiceHost }) => {
const host = startVoiceHost();
- setLocalVoiceHost(host);
+ localVoiceHost.current = host;
window.addEventListener('pagehide', () => host.surrender());
logger.debug('voice: sidebar microphone host ready');
})
diff --git a/src/lib/voice/start-voice-host.ts b/src/lib/voice/start-voice-host.ts
new file mode 100644
index 0000000..3597075
--- /dev/null
+++ b/src/lib/voice/start-voice-host.ts
@@ -0,0 +1,23 @@
+import { logger } from '@mimik/core/logger';
+import { onMessage } from '../browser-api/on-message';
+import { createVoiceHost, type VoiceHost } from './create-voice-host';
+import { isVoiceMessageFor } from './is-voice-message-for';
+import { VOICE_OFFSCREEN_TARGET, type VoiceRequest } from './voice-message';
+
+export function startVoiceHost(): VoiceHost {
+ const host = createVoiceHost();
+
+ onMessage((message, _sender, sendResponse) => {
+ if (!isVoiceMessageFor(VOICE_OFFSCREEN_TARGET, message)) return undefined;
+ host
+ .handle(message as VoiceRequest)
+ .then(sendResponse)
+ .catch((error: unknown) => {
+ logger.error('voice: host could not handle request', message, error);
+ sendResponse({ ok: false, started: false, reason: 'unknown', error: String(error) });
+ });
+ return true;
+ });
+
+ return host;
+}
diff --git a/src/lib/voice/usable-recording.ts b/src/lib/voice/usable-recording.ts
new file mode 100644
index 0000000..c63d1c7
--- /dev/null
+++ b/src/lib/voice/usable-recording.ts
@@ -0,0 +1,12 @@
+import type { MicRecording } from './mic-recorder';
+import type { VoiceRecording } from './narrate-recording';
+
+export function usableRecording(recording: MicRecording): VoiceRecording | null {
+ if (recording.audioEpochMs === null || recording.pcm.length === 0) return null;
+ return {
+ pcm: recording.pcm,
+ sampleRate: recording.sampleRate,
+ audioEpochMs: recording.audioEpochMs,
+ durationSeconds: recording.durationSeconds,
+ };
+}
diff --git a/src/lib/voice-messages.ts b/src/lib/voice/voice-message.ts
similarity index 93%
rename from src/lib/voice-messages.ts
rename to src/lib/voice/voice-message.ts
index 511f0f8..03f3ea4 100644
--- a/src/lib/voice-messages.ts
+++ b/src/lib/voice/voice-message.ts
@@ -184,11 +184,3 @@ export type VoiceEvent =
export function voiceMessage<T extends VoiceEnvelope>(message: Omit<T, 'timestamp'>): T {
return { ...message, timestamp: Date.now() } as T;
}
-
-export function isVoiceMessageFor(target: VoiceTarget, message: unknown): message is VoiceEnvelope {
- if (typeof message !== 'object' || message === null) return false;
- const candidate = message as Partial<VoiceEnvelope>;
- return (
- candidate.target === target && typeof candidate.type === 'string' && Object.hasOwn(VoiceMessage, candidate.type)
- );
-}
diff --git a/src/lib/voice/voice-stop-action.ts b/src/lib/voice/voice-stop-action.ts
new file mode 100644
index 0000000..14d7660
--- /dev/null
+++ b/src/lib/voice/voice-stop-action.ts
@@ -0,0 +1,11 @@
+export type VoiceStopAction = 'stop-host' | 'recover' | 'report-lost' | 'skip';
+
+export function voiceStopAction(input: {
+ hostAlive: boolean;
+ hasOrphanAudio: boolean;
+ wasRecording: boolean;
+}): VoiceStopAction {
+ if (input.hasOrphanAudio) return 'recover';
+ if (input.hostAlive) return 'stop-host';
+ return input.wasRecording ? 'report-lost' : 'skip';
+}
diff --git a/src/ui/fullview/App.tsx b/src/ui/fullview/App.tsx
index 56af3ef..d6a474e 100644
--- a/src/ui/fullview/App.tsx
+++ b/src/ui/fullview/App.tsx
@@ -1,6 +1,6 @@
import { GuideContent, LibraryContent, SearchModal, TooltipProvider, TopNav, useFullview, useRoute } from '@mimik/ui';
import { useEffect } from 'react';
-import { openSidebar } from '@/lib/browser-api';
+import { openSidebar } from '@/lib/browser-api/open-sidebar';
import { UpdateNotice } from '@/ui/shared/UpdateNotice';
import { VoiceNotice } from './components/VoiceNotice';
diff --git a/src/ui/fullview/__tests__/voice-notice.test.ts b/src/ui/fullview/__tests__/voice-notice.test.ts
index fc27134..fd2dca7 100644
--- a/src/ui/fullview/__tests__/voice-notice.test.ts
+++ b/src/ui/fullview/__tests__/voice-notice.test.ts
@@ -1,8 +1,9 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
-import type { PanelVoiceUpdate, VoicePhase } from '@/lib/port';
-import { VOICE_CONFIRM_MS, voiceNotice, voiceSignature } from '../voice-notice';
+import type { PanelVoiceUpdate, VoicePhase } from '@/lib/port/types';
+import { VOICE_CONFIRM_MS, voiceNotice } from '../lib/voice-notice';
+import { voiceSignature } from '../lib/voice-signature';
const LOCALES = ['en', 'es', 'fr', 'pt-BR', 'zh-CN'];
diff --git a/src/ui/fullview/components/VoiceNotice.tsx b/src/ui/fullview/components/VoiceNotice.tsx
index 25eaf1d..09235eb 100644
--- a/src/ui/fullview/components/VoiceNotice.tsx
+++ b/src/ui/fullview/components/VoiceNotice.tsx
@@ -2,9 +2,10 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@mimik/ui';
import { Check, Loader2, TriangleAlert, X } from 'lucide-react';
import { useEffect, useState } from 'react';
import { browser, i18n } from '#imports';
-import { getVoiceStatus } from '@/lib/offscreen';
-import { observeVoiceFromBackground, type PanelVoiceUpdate } from '@/lib/port';
-import { voiceNotice } from '../voice-notice';
+import { getVoiceStatus } from '@/lib/offscreen/get-voice-status';
+import { observeVoiceFromBackground } from '@/lib/port/observe-voice-from-background';
+import type { PanelVoiceUpdate } from '@/lib/port/types';
+import { voiceNotice } from '../lib/voice-notice';
const IDLE: PanelVoiceUpdate = { type: 'VOICE_UPDATE', phase: 'idle' };
diff --git a/src/ui/fullview/voice-notice.ts b/src/ui/fullview/lib/voice-notice.ts
similarity index 82%
rename from src/ui/fullview/voice-notice.ts
rename to src/ui/fullview/lib/voice-notice.ts
index a46f9fa..ec4e787 100644
--- a/src/ui/fullview/voice-notice.ts
+++ b/src/ui/fullview/lib/voice-notice.ts
@@ -1,5 +1,7 @@
-import type { PanelVoiceUpdate } from '@/lib/port';
-import { narratedKey, voiceErrorKey } from '@/ui/sidepanel/voice-status';
+import type { PanelVoiceUpdate } from '@/lib/port/types';
+import { narratedKey } from '@/ui/sidepanel/lib/narrated-key';
+import { voiceErrorKey } from '@/ui/sidepanel/lib/voice-error-key';
+import { voiceSignature } from './voice-signature';
export const VOICE_CONFIRM_MS = 7000;
@@ -15,10 +17,6 @@ export interface VoiceNotice {
autoDismissMs: number | null;
}
-export function voiceSignature(update: PanelVoiceUpdate): string {
- return `${update.phase}:${update.reason ?? ''}:${update.narrated ?? ''}`;
-}
-
export function voiceNotice(update: PanelVoiceUpdate, seenLive: boolean): VoiceNotice | null {
const signature = voiceSignature(update);
diff --git a/src/ui/fullview/lib/voice-signature.ts b/src/ui/fullview/lib/voice-signature.ts
new file mode 100644
index 0000000..4d30bda
--- /dev/null
+++ b/src/ui/fullview/lib/voice-signature.ts
@@ -0,0 +1,5 @@
+import type { PanelVoiceUpdate } from '@/lib/port/types';
+
+export function voiceSignature(update: PanelVoiceUpdate): string {
+ return `${update.phase}:${update.reason ?? ''}:${update.narrated ?? ''}`;
+}
diff --git a/src/ui/mic-permission/App.tsx b/src/ui/mic-permission/App.tsx
index b686aee..54247be 100644
--- a/src/ui/mic-permission/App.tsx
+++ b/src/ui/mic-permission/App.tsx
@@ -1,60 +1,13 @@
import { Check, Mic, MicOff } from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';
-import { browser, i18n } from '#imports';
-import {
- VOICE_BACKGROUND_TARGET,
- VoiceMessage,
- type VoicePermissionResultEvent,
- type VoicePermissionState,
- voiceMessage,
-} from '@/lib/voice-messages';
+import { i18n } from '#imports';
+import { MICROPHONE, queryState } from './lib/query-state';
+import { report } from './lib/report';
+import { requestMicrophone } from './lib/request-microphone';
+import { returnToOpener } from './lib/return-to-opener';
type Phase = 'checking' | 'prompting' | 'granted' | 'denied';
-const MICROPHONE: PermissionDescriptor = { name: 'microphone' as PermissionName };
-
-async function queryState(): Promise<VoicePermissionState> {
- try {
- const status = await navigator.permissions.query(MICROPHONE);
- return status.state as VoicePermissionState;
- } catch {
- return 'unknown';
- }
-}
-
-async function requestMicrophone(): Promise<boolean> {
- try {
- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
- for (const track of stream.getTracks()) track.stop();
- return true;
- } catch {
- return false;
- }
-}
-
-function report(state: 'granted' | 'denied'): void {
- const event = voiceMessage<VoicePermissionResultEvent>({
- type: VoiceMessage.VOICE_PERMISSION_RESULT,
- target: VOICE_BACKGROUND_TARGET,
- state,
- });
- browser.runtime.sendMessage(event).catch(() => undefined);
-}
-
-function openerTabId(): number | null {
- const raw = new URLSearchParams(window.location.search).get('tabId');
- const id = raw === null ? Number.NaN : Number(raw);
- return Number.isInteger(id) && id >= 0 ? id : null;
-}
-
-async function returnToOpener(): Promise<void> {
- const tabId = openerTabId();
- if (tabId !== null) await browser.tabs.update(tabId, { active: true }).catch(() => undefined);
- const self = await browser.tabs.getCurrent().catch(() => undefined);
- if (self?.id !== undefined) await browser.tabs.remove(self.id).catch(() => undefined);
- else window.close();
-}
-
export function MicPermissionApp() {
const [phase, setPhase] = useState<Phase>('checking');
const settled = useRef(false);
diff --git a/src/ui/mic-permission/lib/query-state.ts b/src/ui/mic-permission/lib/query-state.ts
new file mode 100644
index 0000000..593187b
--- /dev/null
+++ b/src/ui/mic-permission/lib/query-state.ts
@@ -0,0 +1,12 @@
+import type { VoicePermissionState } from '@/lib/voice/voice-message';
+
+export const MICROPHONE: PermissionDescriptor = { name: 'microphone' as PermissionName };
+
+export async function queryState(): Promise<VoicePermissionState> {
+ try {
+ const status = await navigator.permissions.query(MICROPHONE);
+ return status.state as VoicePermissionState;
+ } catch {
+ return 'unknown';
+ }
+}
diff --git a/src/ui/mic-permission/lib/report.ts b/src/ui/mic-permission/lib/report.ts
new file mode 100644
index 0000000..8ca5a4e
--- /dev/null
+++ b/src/ui/mic-permission/lib/report.ts
@@ -0,0 +1,16 @@
+import { browser } from '#imports';
+import {
+ VOICE_BACKGROUND_TARGET,
+ VoiceMessage,
+ type VoicePermissionResultEvent,
+ voiceMessage,
+} from '@/lib/voice/voice-message';
+
+export function report(state: 'granted' | 'denied'): void {
+ const event = voiceMessage<VoicePermissionResultEvent>({
+ type: VoiceMessage.VOICE_PERMISSION_RESULT,
+ target: VOICE_BACKGROUND_TARGET,
+ state,
+ });
+ browser.runtime.sendMessage(event).catch(() => undefined);
+}
diff --git a/src/ui/mic-permission/lib/request-microphone.ts b/src/ui/mic-permission/lib/request-microphone.ts
new file mode 100644
index 0000000..bd2c615
--- /dev/null
+++ b/src/ui/mic-permission/lib/request-microphone.ts
@@ -0,0 +1,9 @@
+export async function requestMicrophone(): Promise<boolean> {
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ for (const track of stream.getTracks()) track.stop();
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/ui/mic-permission/lib/return-to-opener.ts b/src/ui/mic-permission/lib/return-to-opener.ts
new file mode 100644
index 0000000..6cbfe0d
--- /dev/null
+++ b/src/ui/mic-permission/lib/return-to-opener.ts
@@ -0,0 +1,15 @@
+import { browser } from '#imports';
+
+function openerTabId(): number | null {
+ const raw = new URLSearchParams(window.location.search).get('tabId');
+ const id = raw === null ? Number.NaN : Number(raw);
+ return Number.isInteger(id) && id >= 0 ? id : null;
+}
+
+export async function returnToOpener(): Promise<void> {
+ const tabId = openerTabId();
+ if (tabId !== null) await browser.tabs.update(tabId, { active: true }).catch(() => undefined);
+ const self = await browser.tabs.getCurrent().catch(() => undefined);
+ if (self?.id !== undefined) await browser.tabs.remove(self.id).catch(() => undefined);
+ else window.close();
+}
diff --git a/src/ui/onboarding/App.tsx b/src/ui/onboarding/App.tsx
index eec2b61..e064a4f 100644
--- a/src/ui/onboarding/App.tsx
+++ b/src/ui/onboarding/App.tsx
@@ -1,975 +1,11 @@
-import {
- Input,
- KeyStatusNote,
- KeyWarningNote,
- ModelList,
- SecretInput,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
- useAiSettings,
-} from '@mimik/ui';
-import { Globe, Mic, MousePointerClick, Shield } from 'lucide-react';
-import { useEffect, useState } from 'react';
-import { browser, i18n } from '#imports';
-import { PRESET_LABELS, type PresetKey } from '@/core/blur/regexes';
-import { AI_PROVIDERS, type AIProviderKey, CUSTOM_MODEL_VALUE } from '@/core/capture/ai/models';
-import { AI_LANGUAGES, type AILanguageCode } from '@/core/capture/ai/prompts';
-import type { VoiceProvider } from '@/core/capture/voice/transcribe';
-import { localStorage, openSidebar, requestHostPermissions } from '@/lib/browser-api';
-import { useKeyCheck } from '@/ui/shared/key-check';
-import { MicrophonePicker } from '@/ui/shared/MicrophonePicker';
-
-interface StepProps {
- onNext: () => void;
- onSkip: () => void;
- onBack: () => void;
- index: number;
- total: number;
-}
-
-const REPO_URL = 'https://github.com/westpoint-io/mimik';
-
-const BLUR_PRESET_I18N: Record<PresetKey, string> = {
- email: 'email',
- phone: 'phoneNumbers',
- ssn: 'ssn',
- creditCard: 'creditCard',
- ipAddress: 'ipAddress',
- macAddress: 'macAddress',
-};
-
-function MascotLarge({ size = 280 }: { size?: number }) {
- return (
- <svg viewBox="0 0 200 200" width={size} height={size}>
- <circle cx="40" cy="70" r="4" fill="#818CF8" style={{ animation: 'sparkle 1.5s ease-in-out infinite' }} />
- <circle cx="165" cy="60" r="3.5" fill="#818CF8" style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.3s' }} />
- <circle cx="42" cy="155" r="3" fill="#A5B4FC" style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.6s' }} />
- <circle
- cx="162"
- cy="150"
- r="3.5"
- fill="#818CF8"
- style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.9s' }}
- />
- <circle cx="100" cy="110" r="55" fill="#C7D2FE" />
- <rect x="55" y="110" width="90" height="44" rx="5" fill="#1E1B4B" />
- <path d="M55 110 L55 98 Q55 80 100 80 Q145 80 145 98 L145 110Z" fill="#3730A3" />
- <path d="M55 110 L55 98 Q55 80 100 80 Q145 80 145 98 L145 110Z" fill="#4F46E5" />
- <rect x="55" y="109" width="90" height="2" fill="#C7D2FE" />
- <path d="M80 128 Q86 120 92 128" stroke="#C7D2FE" strokeWidth="3.5" fill="none" strokeLinecap="round" />
- <path d="M108 128 Q114 120 120 128" stroke="#C7D2FE" strokeWidth="3.5" fill="none" strokeLinecap="round" />
- <path d="M90 140 Q100 148 110 140" stroke="#C7D2FE" strokeWidth="2.5" fill="none" strokeLinecap="round" />
- <style>{`@keyframes sparkle{0%,100%{opacity:.3;transform:scale(.8)}50%{opacity:1;transform:scale(1.1)}}@keyframes float{0%,100%{transform:translateY(0)}50%{transform:translateY(-8px)}}`}</style>
- </svg>
- );
-}
-
-function ProgressDots({ current, total }: { current: number; total: number }) {
- return (
- <div className="flex items-center gap-2">
- {Array.from({ length: total }, (_, position) => position + 1).map((i) => (
- <div
- key={i}
- className={`h-2 rounded-full transition-all duration-300 ${
- i === current ? 'w-8 bg-accent' : i < current ? 'w-2 bg-accent/40' : 'w-2 bg-border'
- }`}
- />
- ))}
- </div>
- );
-}
-
-function WelcomeStep({ onNext }: { onNext: () => void }) {
- return (
- <div className="flex h-screen">
- <div className="flex-1 flex flex-col justify-center" style={{ padding: '80px 64px' }}>
- <div className="max-w-lg">
- <span className="inline-flex text-xs font-semibold text-accent bg-secondary px-3.5 py-1.5 rounded-full mb-6">
- {i18n.t('onboarding.welcomeBadge')}
- </span>
- <h1 className="text-4xl font-extrabold text-foreground leading-tight mb-3 tracking-tight">
- {i18n.t('onboarding.welcomeTitle')}
- </h1>
- <p className="text-base text-muted-foreground leading-relaxed mb-10 max-w-md">
- {i18n.t('onboarding.welcomeMessage')}
- </p>
- <button
- onClick={onNext}
- className="inline-flex items-center gap-2 px-7 py-3 bg-primary text-primary-foreground rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors"
- >
- {i18n.t('onboarding.getStarted')}
- <svg
- width="16"
- height="16"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- >
- <path d="M5 12h14M12 5l7 7-7 7" />
- </svg>
- </button>
- </div>
- </div>
- <div className="w-1/2 bg-deep flex items-center justify-center relative overflow-hidden">
- <div className="absolute w-[500px] h-[500px] bg-[radial-gradient(circle,rgba(79,70,229,0.2),transparent_70%)] top-[10%] right-[-10%]" />
- <div className="absolute w-[400px] h-[400px] bg-[radial-gradient(circle,rgba(56,189,248,0.1),transparent_70%)] bottom-[10%] left-[10%]" />
- <div className="animate-[float_3s_ease-in-out_infinite]">
- <MascotLarge size={280} />
- </div>
- </div>
- </div>
- );
-}
-
-function AISetupStep({ onNext, onSkip, onBack, index, total }: StepProps) {
- const aiKeyCheck = useKeyCheck();
- const ai = useAiSettings({ onDirty: aiKeyCheck.reset, reloadOnFocus: true });
- const {
- provider,
- model,
- apiKey,
- baseUrl,
- language: aiLanguage,
- ownServer,
- usingCustomModel,
- providerConfig,
- setProvider: handleProviderChange,
- setModel: handleModelChange,
- setApiKey: handleApiKeyChange,
- setBaseUrl: handleBaseUrlChange,
- setLanguage: handleLanguageChange,
- toggleOwnServer: handleOwnServerToggle,
- } = ai;
-
- return (
- <div className="flex h-screen">
- <div className="flex-1 flex flex-col justify-center" style={{ padding: '80px 64px' }}>
- <div className="max-w-md">
- <p className="text-xs font-semibold text-accent mb-2 tracking-wide uppercase">
- {i18n.t('onboarding.stepOf', [String(index), String(total)])}
- </p>
- <h1 className="text-3xl font-extrabold text-foreground leading-tight mb-2">{i18n.t('onboarding.aiTitle')}</h1>
- <p className="text-sm text-muted-foreground leading-relaxed mb-8">{i18n.t('onboarding.aiMessage')}</p>
-
- <div className="space-y-4 mb-8">
- <div>
- <label className="block text-xs font-semibold text-foreground mb-1.5">
- {i18n.t('settings.provider')}
- </label>
- <Select value={provider} onValueChange={(v) => handleProviderChange(v as AIProviderKey)}>
- <SelectTrigger className="w-full h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {Object.entries(AI_PROVIDERS).map(([key, cfg]) => (
- <SelectItem key={key} value={key}>
- {cfg.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
-
- <div>
- <label className="block text-xs font-semibold text-foreground mb-1.5">{i18n.t('settings.model')}</label>
- <Select value={usingCustomModel ? CUSTOM_MODEL_VALUE : model} onValueChange={handleModelChange}>
- <SelectTrigger className="w-full h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {providerConfig.models.map((m) => (
- <SelectItem key={m.id} value={m.id}>
- {m.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- {usingCustomModel && (
- <Input
- type="text"
- value={model}
- onChange={(e) => handleModelChange(e.target.value)}
- placeholder={providerConfig.defaultModel}
- className="w-full mt-1.5 h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10"
- />
- )}
- </div>
-
- <div>
- <label className="block text-xs font-semibold text-foreground mb-1.5">{i18n.t('settings.apiKey')}</label>
- <SecretInput
- value={apiKey}
- onChange={handleApiKeyChange}
- placeholder="sk-..."
- className="w-full h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10"
- buttonClassName="right-3"
- />
- <div className="flex items-center gap-3 mt-2">
- <button
- type="button"
- disabled={!apiKey || aiKeyCheck.status === 'checking'}
- onClick={() => {
- if (aiKeyCheck.status !== 'checking') void aiKeyCheck.check(provider, apiKey, baseUrl, model);
- }}
- className="px-4 py-2 bg-card text-foreground border border-border rounded-lg font-semibold text-xs hover:border-accent hover:text-accent transition-colors disabled:opacity-50 disabled:pointer-events-none"
- >
- {i18n.t('settings.checkKey')}
- </button>
- <div className="min-w-0">
- <KeyStatusNote status={aiKeyCheck.status} />
- <KeyWarningNote warning={aiKeyCheck.warning} />
- </div>
- </div>
- {aiKeyCheck.models && <ModelList models={aiKeyCheck.models} />}
- </div>
-
- <div>
- <div className="flex items-center justify-between gap-3">
- <span className="text-xs font-semibold text-foreground flex items-center gap-1">
- <Globe size={12} className="-mt-px" />
- {i18n.t('settings.useOwnServer')}
- </span>
- <button
- type="button"
- role="switch"
- aria-checked={ownServer}
- aria-label={i18n.t('settings.useOwnServer')}
- onClick={handleOwnServerToggle}
- className={`w-10 h-6 rounded-full transition-colors relative shrink-0 ${
- ownServer ? 'bg-accent' : 'bg-border'
- }`}
- >
- <span
- className={`absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow-sm transition-transform ${
- ownServer ? 'translate-x-4' : 'translate-x-0'
- }`}
- />
- </button>
- </div>
- {ownServer && (
- <div className="mt-2 space-y-2">
- <Input
- type="text"
- value={baseUrl}
- onChange={(e) => handleBaseUrlChange(e.target.value)}
- placeholder={providerConfig.defaultBaseUrl}
- aria-label={i18n.t('settings.baseUrl')}
- className="w-full h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10"
- />
- <p className="text-[11px] text-muted-foreground leading-relaxed">
- {i18n.t(
- providerConfig.protocol === 'anthropic'
- ? 'settings.ownServerHintAnthropic'
- : 'settings.ownServerHintOpenai',
- )}
- </p>
- </div>
- )}
- </div>
-
- <div>
- <label className="block text-xs font-semibold text-foreground mb-1.5">
- {i18n.t('settings.aiLanguage')}
- </label>
- <Select value={aiLanguage} onValueChange={(v) => handleLanguageChange(v as AILanguageCode)}>
- <SelectTrigger className="w-full h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {AI_LANGUAGES.map((lang) => (
- <SelectItem key={lang.code} value={lang.code}>
- {lang.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- </div>
-
- <div className="flex items-center gap-3">
- <button
- onClick={onBack}
- className="px-8 py-3 bg-card text-foreground border border-border rounded-xl font-semibold text-sm hover:border-accent hover:text-accent transition-colors"
- >
- {i18n.t('common.back')}
- </button>
- <button
- onClick={onNext}
- className="px-8 py-3 bg-primary text-primary-foreground rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors"
- >
- {i18n.t('common.continue')}
- </button>
- <button
- onClick={onSkip}
- className="ml-2 px-6 py-3 text-muted-foreground rounded-xl font-semibold text-sm hover:text-foreground transition-colors"
- >
- {i18n.t('common.skip')}
- </button>
- </div>
-
- <div className="mt-6">
- <ProgressDots current={index} total={total} />
- </div>
- </div>
- </div>
- <div className="w-1/2 bg-secondary flex items-center justify-center relative overflow-hidden">
- <div className="absolute w-[400px] h-[400px] bg-[radial-gradient(circle,rgba(79,70,229,0.06),transparent_70%)] top-[20%] left-[30%]" />
- <div className="animate-[float_4s_ease-in-out_infinite] relative">
- <svg
- className="absolute -top-4 right-6 w-6 h-6 text-violet-light opacity-40"
- style={{ animation: 'sparkle 2s ease-in-out infinite' }}
- viewBox="0 0 24 24"
- fill="currentColor"
- >
- <path d="M12 2L14 10L22 12L14 14L12 22L10 14L2 12L10 10Z" />
- </svg>
- <svg
- className="absolute bottom-3 -left-3 w-4 h-4 text-violet-light opacity-40"
- style={{ animation: 'sparkle 2s ease-in-out infinite 0.5s' }}
- viewBox="0 0 24 24"
- fill="currentColor"
- >
- <path d="M12 2L14 10L22 12L14 14L12 22L10 14L2 12L10 10Z" />
- </svg>
- <div className="bg-white rounded-2xl p-9 shadow-lg max-w-sm">
- <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest mb-4">
- {i18n.t('onboarding.aiGeneratedDescription')}
- </p>
- <div className="flex gap-3 mb-5">
- <div className="w-7 h-7 rounded-full bg-primary text-primary-foreground text-xs font-bold flex items-center justify-center shrink-0">
- 3
- </div>
- <div>
- <p className="text-sm text-foreground leading-relaxed">
- Click on the{' '}
- <span className="bg-accent/10 text-accent font-semibold px-1 rounded">Pull requests</span> tab in the
- repository navigation
- </p>
- <span className="inline-flex items-center gap-1 text-[9px] font-semibold text-accent bg-secondary px-2 py-0.5 rounded mt-2">
- <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor">
- <path d="M12 2L14 10L22 12L14 14L12 22L10 14L2 12L10 10Z" />
- </svg>
- {i18n.t('onboarding.aiGenerated')}
- </span>
- </div>
- </div>
- <div className="border-t border-border my-4" />
- <div className="flex gap-3">
- <div className="w-7 h-7 rounded-full bg-primary text-primary-foreground text-xs font-bold flex items-center justify-center shrink-0">
- 4
- </div>
- <div>
- <p className="text-sm text-foreground leading-relaxed">
- Click on <span className="bg-accent/10 text-accent font-semibold px-1 rounded">Sort</span> dropdown to
- change the ordering
- </p>
- <span className="inline-flex items-center gap-1 text-[9px] font-semibold text-accent bg-secondary px-2 py-0.5 rounded mt-2">
- <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor">
- <path d="M12 2L14 10L22 12L14 14L12 22L10 14L2 12L10 10Z" />
- </svg>
- {i18n.t('onboarding.aiGenerated')}
- </span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- );
-}
-
-function VoiceStep({ onNext, onSkip, onBack, index, total }: StepProps) {
- const [provider, setProvider] = useState<VoiceProvider>('openai');
- const [apiKey, setApiKey] = useState('');
- const [microphoneId, setMicrophoneId] = useState('');
-
- useEffect(() => {
- const load = () =>
- localStorage.get(['voiceProvider', 'voiceApiKey', 'voiceMicrophoneId']).then((stored) => {
- if (stored.voiceProvider === 'openai' || stored.voiceProvider === 'groq') setProvider(stored.voiceProvider);
- if (typeof stored.voiceApiKey === 'string') setApiKey(stored.voiceApiKey);
- if (typeof stored.voiceMicrophoneId === 'string') setMicrophoneId(stored.voiceMicrophoneId);
- });
-
- void load();
- const onVisible = () => {
- if (document.visibilityState === 'visible') void load();
- };
- document.addEventListener('visibilitychange', onVisible);
- return () => document.removeEventListener('visibilitychange', onVisible);
- }, []);
-
- const handleMicrophoneChange = (deviceId: string) => {
- setMicrophoneId(deviceId);
- void localStorage.set({ voiceMicrophoneId: deviceId });
- };
-
- const handleProviderChange = (nextProvider: VoiceProvider) => {
- setProvider(nextProvider);
- void localStorage.set({ voiceProvider: nextProvider });
- };
-
- const handleApiKeyChange = (nextKey: string) => {
- setApiKey(nextKey);
- void localStorage.set({ voiceApiKey: nextKey });
- };
-
- return (
- <div className="flex h-screen">
- <div className="flex-1 flex flex-col justify-center overflow-y-auto" style={{ padding: '64px' }}>
- <div className="max-w-md">
- <p className="text-xs font-semibold text-accent mb-2 tracking-wide uppercase">
- {i18n.t('onboarding.stepOf', [String(index), String(total)])}
- </p>
- <h1 className="text-3xl font-extrabold text-foreground leading-tight mb-2">
- {i18n.t('onboarding.voiceTitle')}
- </h1>
- <p className="text-sm text-muted-foreground leading-relaxed mb-6">{i18n.t('onboarding.voiceMessage')}</p>
-
- <div className="border border-border rounded-2xl p-4 space-y-3 mb-6">
- <div className="flex gap-3">
- <div className="flex-1">
- <label className="block text-xs font-semibold text-foreground mb-1.5">
- {i18n.t('settings.provider')}
- </label>
- <Select value={provider} onValueChange={(v) => handleProviderChange(v as VoiceProvider)}>
- <SelectTrigger className="h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="openai">OpenAI</SelectItem>
- <SelectItem value="groq">Groq</SelectItem>
- </SelectContent>
- </Select>
- </div>
- <div className="flex-1">
- <label className="block text-xs font-semibold text-foreground mb-1.5">
- {i18n.t('settings.apiKey')}
- </label>
- <SecretInput
- value={apiKey}
- onChange={handleApiKeyChange}
- placeholder={provider === 'groq' ? 'gsk_...' : 'sk-...'}
- className="w-full h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10"
- />
- </div>
- </div>
-
- <MicrophonePicker
- value={microphoneId}
- onChange={handleMicrophoneChange}
- triggerClassName="h-11 px-4 text-sm"
- />
-
- <div className="flex items-start gap-2 px-3 py-2.5 rounded-xl bg-secondary text-[11px] text-muted-foreground leading-relaxed">
- <Mic size={12} className="shrink-0 mt-0.5 text-accent" />
- <span>{i18n.t('onboarding.voiceRecordHint')}</span>
- </div>
-
- <div className="flex items-start gap-2 px-3 py-2.5 rounded-xl bg-secondary text-[11px] text-muted-foreground leading-relaxed">
- <Shield size={12} className="shrink-0 mt-0.5 text-accent" />
- <span>{i18n.t('onboarding.voiceDataNotice')}</span>
- </div>
- </div>
-
- <div className="flex items-center gap-3">
- <button
- onClick={onBack}
- className="px-8 py-3 bg-card text-foreground border border-border rounded-xl font-semibold text-sm hover:border-accent hover:text-accent transition-colors"
- >
- {i18n.t('common.back')}
- </button>
- <button
- onClick={onNext}
- className="px-8 py-3 bg-primary text-primary-foreground rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors"
- >
- {i18n.t('common.continue')}
- </button>
- <button
- onClick={onSkip}
- className="ml-2 px-6 py-3 text-muted-foreground rounded-xl font-semibold text-sm hover:text-foreground transition-colors"
- >
- {i18n.t('common.skip')}
- </button>
- </div>
-
- <div className="mt-6">
- <ProgressDots current={index} total={total} />
- </div>
- </div>
- </div>
- <div className="w-1/2 bg-deep flex items-center justify-center relative overflow-hidden">
- <div className="absolute w-[400px] h-[400px] bg-[radial-gradient(circle,rgba(79,70,229,0.22),transparent_70%)] top-[15%] right-[-5%]" />
- <div className="animate-[float_4s_ease-in-out_infinite] relative z-10">
- <div className="bg-white rounded-2xl p-7 shadow-lg" style={{ minWidth: 340 }}>
- <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest mb-4">
- {i18n.t('onboarding.voiceDemoLabel')}
- </p>
-
- <div className="flex items-start gap-3">
- <div className="w-7 h-7 rounded-full bg-accent/10 flex items-center justify-center shrink-0">
- <Mic size={13} className="text-accent" />
- </div>
- <div>
- <p className="text-[9px] font-semibold uppercase tracking-widest text-accent">
- {i18n.t('onboarding.voiceDemoSay')}
- </p>
- <p className="text-sm text-foreground leading-relaxed mt-0.5">{i18n.t('onboarding.voiceDemoQuote')}</p>
- </div>
- </div>
-
- <div className="ml-3.5 my-1.5 h-5 w-px bg-border" />
-
- <div className="flex items-start gap-3">
- <div className="w-7 h-7 rounded-full bg-secondary flex items-center justify-center shrink-0">
- <MousePointerClick size={13} className="text-accent" />
- </div>
- <div>
- <p className="text-[9px] font-semibold uppercase tracking-widest text-muted-foreground">
- {i18n.t('onboarding.voiceDemoAct')}
- </p>
- <p className="text-sm text-foreground leading-relaxed mt-0.5">{i18n.t('onboarding.voiceDemoAction')}</p>
- </div>
- </div>
-
- <div className="border-t border-border my-4" />
-
- <div className="flex gap-3">
- <div className="w-7 h-7 rounded-full bg-primary text-primary-foreground text-xs font-bold flex items-center justify-center shrink-0">
- 3
- </div>
- <div>
- <p className="text-sm text-foreground leading-relaxed">{i18n.t('onboarding.voiceDemoQuote')}</p>
- <span className="inline-flex items-center gap-1 text-[9px] font-semibold text-accent bg-secondary px-2 py-0.5 rounded mt-2">
- <Mic size={9} />
- {i18n.t('onboarding.voiceDemoBadge')}
- </span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- );
-}
-
-function SmartBlurStep({ onNext, onBack, index, total }: StepProps) {
- const [blurPresets, setBlurPresets] = useState<Record<PresetKey, boolean>>({
- email: true,
- phone: true,
- ssn: false,
- creditCard: false,
- ipAddress: false,
- macAddress: false,
- });
-
- useEffect(() => {
- localStorage.get(['blurPresets']).then((stored) => {
- if (stored.blurPresets && typeof stored.blurPresets === 'object') {
- setBlurPresets((prev) => ({ ...prev, ...(stored.blurPresets as Record<PresetKey, boolean>) }));
- }
- });
- }, []);
-
- const handleToggle = (key: PresetKey) => {
- setBlurPresets((prev) => {
- const next = { ...prev, [key]: !prev[key] };
- localStorage.set({ blurPresets: next });
- return next;
- });
- };
-
- return (
- <div className="flex h-screen">
- <div className="flex-1 flex flex-col justify-center" style={{ padding: '80px 64px' }}>
- <div className="max-w-md">
- <p className="text-xs font-semibold text-accent mb-2 tracking-wide uppercase">
- {i18n.t('onboarding.stepOf', [String(index), String(total)])}
- </p>
- <h1 className="text-3xl font-extrabold text-foreground leading-tight mb-2">
- {i18n.t('onboarding.blurTitle')}
- </h1>
- <p className="text-sm text-muted-foreground leading-relaxed mb-8">{i18n.t('onboarding.blurMessage')}</p>
-
- <div className="space-y-1 mb-8 border border-border rounded-2xl p-4">
- {(Object.keys(PRESET_LABELS) as PresetKey[]).map((key, i, arr) => (
- <div
- key={key}
- className={`flex items-center justify-between py-3 ${i < arr.length - 1 ? 'border-b border-secondary' : ''}`}
- >
- <span className="text-sm font-medium text-foreground">
- {i18n.t(`blurPresets.${BLUR_PRESET_I18N[key]}`)}
- </span>
- <button
- onClick={() => handleToggle(key)}
- className={`w-11 h-6 rounded-full transition-colors relative ${
- blurPresets[key] ? 'bg-accent' : 'bg-border'
- }`}
- >
- <span
- className={`absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow-sm transition-transform ${
- blurPresets[key] ? 'translate-x-5' : 'translate-x-0'
- }`}
- />
- </button>
- </div>
- ))}
- </div>
-
- <div className="flex items-center gap-3">
- <button
- onClick={onBack}
- className="px-8 py-3 bg-card text-foreground border border-border rounded-xl font-semibold text-sm hover:border-accent hover:text-accent transition-colors"
- >
- {i18n.t('common.back')}
- </button>
- <button
- onClick={onNext}
- className="px-8 py-3 bg-primary text-primary-foreground rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors"
- >
- {i18n.t('common.continue')}
- </button>
- </div>
-
- <div className="mt-6">
- <ProgressDots current={index} total={total} />
- </div>
- </div>
- </div>
- <div className="w-1/2 bg-deep flex items-center justify-center relative overflow-hidden">
- <div className="absolute w-[350px] h-[350px] bg-[radial-gradient(circle,rgba(79,70,229,0.25),transparent_70%)] bottom-[20%] right-[20%]" />
- <div className="animate-[float_4s_ease-in-out_infinite] relative z-10">
- <div className="bg-white rounded-2xl p-7 shadow-lg" style={{ minWidth: 320 }}>
- <p className="text-xs font-semibold text-foreground mb-4">{i18n.t('onboarding.screenshotPreview')}</p>
- {[
- { icon: '@', label: i18n.t('blurPresets.email'), value: '[email protected]', blurred: true },
- { icon: '#', label: i18n.t('blurPresets.phoneNumbers'), value: '(555) 867-5309', blurred: true },
- { icon: 'ID', label: i18n.t('blurPresets.ssn'), value: i18n.t('onboarding.notEnabled'), blurred: false },
- {
- icon: '$',
- label: i18n.t('blurPresets.creditCard'),
- value: i18n.t('onboarding.notEnabled'),
- blurred: false,
- },
- {
- icon: 'IP',
- label: i18n.t('blurPresets.ipAddress'),
- value: i18n.t('onboarding.notEnabled'),
- blurred: false,
- },
- ].map((row, i, arr) => (
- <div
- key={row.label}
- className={`flex items-center gap-3 py-2.5 ${i < arr.length - 1 ? 'border-b border-border' : ''}`}
- >
- <div className="w-6 h-6 rounded-md bg-secondary flex items-center justify-center text-[10px] font-semibold text-accent">
- {row.icon}
- </div>
- <span className="text-xs text-muted-foreground flex-1">{row.label}</span>
- <span
- className={`text-xs font-semibold ${row.blurred ? 'text-foreground blur-[4px] select-none' : 'text-muted-foreground font-normal'}`}
- >
- {row.value}
- </span>
- </div>
- ))}
- <div className="inline-flex items-center gap-1.5 text-[10px] font-semibold text-success bg-success/10 px-2.5 py-1 rounded mt-3">
- <svg
- width="13"
- height="13"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- >
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
- </svg>
- {i18n.t('onboarding.categoriesProtected', ['2'])}
- </div>
- </div>
- </div>
- </div>
- </div>
- );
-}
-
-function PinExtensionStep({ onNext, onBack, index, total }: StepProps) {
- return (
- <div className="flex h-screen">
- <div className="flex-1 flex flex-col justify-center" style={{ padding: '80px 64px' }}>
- <div className="max-w-md">
- <p className="text-xs font-semibold text-accent mb-2 tracking-wide uppercase">
- {i18n.t('onboarding.stepOf', [String(index), String(total)])}
- </p>
- <h1 className="text-3xl font-extrabold text-foreground leading-tight mb-2">
- {i18n.t('onboarding.pinTitle')}
- </h1>
- <p className="text-sm text-muted-foreground leading-relaxed mb-8">{i18n.t('onboarding.pinMessage')}</p>
-
- <ol className="space-y-4 mb-8">
- <li className="flex items-start gap-3">
- <div className="w-7 h-7 rounded-lg bg-accent/10 flex items-center justify-center shrink-0 mt-0.5">
- <span className="text-accent text-xs font-bold">1</span>
- </div>
- <div>
- <p className="text-sm font-medium text-foreground">{i18n.t('onboarding.pinStep1Title')}</p>
- <p className="text-xs text-muted-foreground">{i18n.t('onboarding.pinStep1Sub')}</p>
- </div>
- </li>
- <li className="flex items-start gap-3">
- <div className="w-7 h-7 rounded-lg bg-accent/10 flex items-center justify-center shrink-0 mt-0.5">
- <span className="text-accent text-xs font-bold">2</span>
- </div>
- <div>
- <p className="text-sm font-medium text-foreground">{i18n.t('onboarding.pinStep2Title')}</p>
- <p className="text-xs text-muted-foreground">{i18n.t('onboarding.pinStep2Sub')}</p>
- </div>
- </li>
- <li className="flex items-start gap-3">
- <div className="w-7 h-7 rounded-lg bg-accent/10 flex items-center justify-center shrink-0 mt-0.5">
- <span className="text-accent text-xs font-bold">3</span>
- </div>
- <div>
- <p className="text-sm font-medium text-foreground">{i18n.t('onboarding.pinStep3Title')}</p>
- <p className="text-xs text-muted-foreground">{i18n.t('onboarding.pinStep3Sub')}</p>
- </div>
- </li>
- </ol>
-
- <div className="flex items-center gap-3">
- <button
- onClick={onBack}
- className="px-8 py-3 bg-card text-foreground border border-border rounded-xl font-semibold text-sm hover:border-accent hover:text-accent transition-colors"
- >
- {i18n.t('common.back')}
- </button>
- <button
- onClick={onNext}
- className="px-8 py-3 bg-primary text-primary-foreground rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors"
- >
- {i18n.t('common.continue')}
- </button>
- </div>
-
- <div className="mt-6">
- <ProgressDots current={index} total={total} />
- </div>
- </div>
- </div>
- <div className="w-1/2 bg-deep flex items-center justify-center relative overflow-hidden">
- <div className="absolute w-[400px] h-[400px] bg-[radial-gradient(circle,rgba(79,70,229,0.2),transparent_70%)] top-[10%] right-[-10%]" />
- <div className="animate-[float_4s_ease-in-out_infinite] relative z-10">
- <img
- src="/pin-screenshot.png"
- alt={i18n.t('onboarding.pinScreenshotAlt')}
- className="rounded-xl shadow-2xl max-w-[400px]"
- />
- </div>
- </div>
- </div>
- );
-}
-
-function MascotWithStar({ size = 300 }: { size?: number }) {
- return (
- <svg viewBox="0 0 200 200" width={size} height={size}>
- <circle cx="34" cy="96" r="4" fill="#818CF8" style={{ animation: 'sparkle 1.5s ease-in-out infinite' }} />
- <circle cx="168" cy="86" r="3.5" fill="#818CF8" style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.5s' }} />
- <circle cx="46" cy="30" r="3" fill="#A5B4FC" style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.9s' }} />
- <g transform="translate(72 2) scale(2.333)">
- <path
- d="m12 2 3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2Z"
- fill="#FACC15"
- />
- </g>
- <circle cx="100" cy="110" r="55" fill="#C7D2FE" />
- <rect x="55" y="110" width="90" height="44" rx="5" fill="#1E1B4B" />
- <path d="M55 110 L55 98 Q55 80 100 80 Q145 80 145 98 L145 110Z" fill="#4F46E5" />
- <rect x="55" y="109" width="90" height="2" fill="#C7D2FE" />
- <path d="M80 128 Q86 120 92 128" stroke="#C7D2FE" strokeWidth="3.5" fill="none" strokeLinecap="round" />
- <path d="M108 128 Q114 120 120 128" stroke="#C7D2FE" strokeWidth="3.5" fill="none" strokeLinecap="round" />
- <path d="M90 140 Q100 149 110 140" stroke="#C7D2FE" strokeWidth="2.5" fill="none" strokeLinecap="round" />
- </svg>
- );
-}
-
-function GitHubStarStep({ onSkip, onBack, index, total }: StepProps) {
- const handleStar = () => {
- browser.tabs.create({ url: REPO_URL, active: true });
- };
-
- return (
- <div className="flex h-screen">
- <div className="flex-1 flex flex-col justify-center" style={{ padding: '80px 64px' }}>
- <div className="max-w-md">
- <p className="text-xs font-semibold text-accent mb-2 tracking-wide uppercase">
- {i18n.t('onboarding.stepOf', [String(index), String(total)])}
- </p>
- <h1 className="text-3xl font-extrabold text-foreground leading-tight mb-2">
- {i18n.t('onboarding.starTitle')}
- </h1>
- <p className="text-sm text-muted-foreground leading-relaxed mb-8">{i18n.t('onboarding.starMessage')}</p>
-
- <div className="flex items-center gap-3">
- <button
- onClick={onBack}
- className="px-8 py-3 bg-card text-foreground border border-border rounded-xl font-semibold text-sm hover:border-accent hover:text-accent transition-colors"
- >
- {i18n.t('common.back')}
- </button>
- <button
- onClick={handleStar}
- className="px-8 py-3 bg-primary text-primary-foreground rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors"
- >
- {i18n.t('onboarding.starAction')}
- </button>
- <button
- onClick={onSkip}
- className="ml-2 px-6 py-3 text-muted-foreground rounded-xl font-semibold text-sm hover:text-foreground transition-colors"
- >
- {i18n.t('onboarding.starLater')}
- </button>
- </div>
-
- <div className="mt-6">
- <ProgressDots current={index} total={total} />
- </div>
- </div>
- </div>
- <div className="w-1/2 bg-deep flex items-center justify-center relative overflow-hidden">
- <div className="absolute w-[500px] h-[500px] bg-[radial-gradient(circle,rgba(79,70,229,0.2),transparent_70%)] top-[10%] right-[-10%]" />
- <div className="absolute w-[400px] h-[400px] bg-[radial-gradient(circle,rgba(250,204,21,0.08),transparent_70%)] bottom-[14%] left-[8%]" />
- <div className="animate-[float_3s_ease-in-out_infinite] relative z-10">
- <MascotWithStar size={300} />
- </div>
- </div>
- </div>
- );
-}
-
-function DoneStep() {
- useEffect(() => {
- localStorage.set({ onboardingCompleted: true });
- }, []);
-
- const handleOpen = async () => {
- openSidebar();
- const permissionsPromise = requestHostPermissions();
- await permissionsPromise;
- browser.tabs.create({ url: browser.runtime.getURL('/fullview.html') });
- };
-
- return (
- <div className="flex h-screen items-center justify-center">
- <div className="text-center max-w-lg">
- <div className="flex justify-center mb-8 animate-[float_3s_ease-in-out_infinite]">
- <MascotLarge size={120} />
- </div>
- <h1 className="text-4xl font-extrabold text-foreground mb-3 tracking-tight">
- {i18n.t('onboarding.doneTitle')}
- </h1>
- <p className="text-base text-muted-foreground mb-8 max-w-md mx-auto leading-relaxed">
- {i18n.t('onboarding.doneMessage')}
- </p>
-
- <div className="grid grid-cols-3 gap-3 mb-8">
- {[
- {
- label: i18n.t('onboarding.featureAutoCapture'),
- icon: (
- <>
- <rect x="2" y="3" width="20" height="14" rx="2" />
- <path d="M8 21h8M12 17v4" />
- </>
- ),
- },
- {
- label: i18n.t('onboarding.featureVoice'),
- icon: (
- <>
- <path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z" />
- <path d="M19 10v2a7 7 0 0 1-14 0v-2M12 19v3" />
- </>
- ),
- },
- {
- label: i18n.t('onboarding.featureAIAssist'),
- icon: <path d="M12 2L14 10L22 12L14 14L12 22L10 14L2 12L10 10Z" />,
- },
- {
- label: i18n.t('onboarding.featureAnnotate'),
- icon: (
- <>
- <path d="M12 20h9" />
- <path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z" />
- </>
- ),
- },
- {
- label: i18n.t('onboarding.featureSmartBlur'),
- icon: (
- <>
- <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
- <circle cx="12" cy="12" r="3" />
- </>
- ),
- },
- {
- label: i18n.t('onboarding.featureExports'),
- icon: (
- <>
- <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
- <path d="M7 10l5 5 5-5M12 15V3" />
- </>
- ),
- },
- ].map((f) => (
- <div key={f.label} className="bg-secondary rounded-xl px-3 py-4 text-center">
- <div className="text-accent flex justify-center mb-2">
- <svg
- width="24"
- height="24"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- >
- {f.icon}
- </svg>
- </div>
- <p className="text-xs font-semibold text-foreground">{f.label}</p>
- </div>
- ))}
- </div>
-
- <button
- onClick={handleOpen}
- className="inline-flex items-center gap-2 px-7 py-3 bg-primary text-primary-foreground rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors"
- >
- {i18n.t('onboarding.openMimik')}
- <svg
- width="16"
- height="16"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- >
- <path d="M5 12h14M12 5l7 7-7 7" />
- </svg>
- </button>
- </div>
- </div>
- );
-}
+import { useState } from 'react';
+import { AISetupStep } from './steps/AISetupStep';
+import { DoneStep } from './steps/DoneStep';
+import { GitHubStarStep } from './steps/GitHubStarStep';
+import { PinExtensionStep } from './steps/PinExtensionStep';
+import { SmartBlurStep } from './steps/SmartBlurStep';
+import { VoiceStep } from './steps/VoiceStep';
+import { WelcomeStep } from './steps/WelcomeStep';
const CONFIG_STEPS =
import.meta.env.BROWSER === 'firefox'
diff --git a/src/ui/onboarding/MascotLarge.tsx b/src/ui/onboarding/MascotLarge.tsx
new file mode 100644
index 0000000..aabca2f
--- /dev/null
+++ b/src/ui/onboarding/MascotLarge.tsx
@@ -0,0 +1,25 @@
+export function MascotLarge({ size = 280 }: { size?: number }) {
+ return (
+ <svg viewBox="0 0 200 200" width={size} height={size}>
+ <circle cx="40" cy="70" r="4" fill="#818CF8" style={{ animation: 'sparkle 1.5s ease-in-out infinite' }} />
+ <circle cx="165" cy="60" r="3.5" fill="#818CF8" style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.3s' }} />
+ <circle cx="42" cy="155" r="3" fill="#A5B4FC" style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.6s' }} />
+ <circle
+ cx="162"
+ cy="150"
+ r="3.5"
+ fill="#818CF8"
+ style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.9s' }}
+ />
+ <circle cx="100" cy="110" r="55" fill="#C7D2FE" />
+ <rect x="55" y="110" width="90" height="44" rx="5" fill="#1E1B4B" />
+ <path d="M55 110 L55 98 Q55 80 100 80 Q145 80 145 98 L145 110Z" fill="#3730A3" />
+ <path d="M55 110 L55 98 Q55 80 100 80 Q145 80 145 98 L145 110Z" fill="#4F46E5" />
+ <rect x="55" y="109" width="90" height="2" fill="#C7D2FE" />
+ <path d="M80 128 Q86 120 92 128" stroke="#C7D2FE" strokeWidth="3.5" fill="none" strokeLinecap="round" />
+ <path d="M108 128 Q114 120 120 128" stroke="#C7D2FE" strokeWidth="3.5" fill="none" strokeLinecap="round" />
+ <path d="M90 140 Q100 148 110 140" stroke="#C7D2FE" strokeWidth="2.5" fill="none" strokeLinecap="round" />
+ <style>{`@keyframes sparkle{0%,100%{opacity:.3;transform:scale(.8)}50%{opacity:1;transform:scale(1.1)}}@keyframes float{0%,100%{transform:translateY(0)}50%{transform:translateY(-8px)}}`}</style>
+ </svg>
+ );
+}
diff --git a/src/ui/onboarding/MascotWithStar.tsx b/src/ui/onboarding/MascotWithStar.tsx
new file mode 100644
index 0000000..8781ed9
--- /dev/null
+++ b/src/ui/onboarding/MascotWithStar.tsx
@@ -0,0 +1,22 @@
+export function MascotWithStar({ size = 300 }: { size?: number }) {
+ return (
+ <svg viewBox="0 0 200 200" width={size} height={size}>
+ <circle cx="34" cy="96" r="4" fill="#818CF8" style={{ animation: 'sparkle 1.5s ease-in-out infinite' }} />
+ <circle cx="168" cy="86" r="3.5" fill="#818CF8" style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.5s' }} />
+ <circle cx="46" cy="30" r="3" fill="#A5B4FC" style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.9s' }} />
+ <g transform="translate(72 2) scale(2.333)">
+ <path
+ d="m12 2 3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2Z"
+ fill="#FACC15"
+ />
+ </g>
+ <circle cx="100" cy="110" r="55" fill="#C7D2FE" />
+ <rect x="55" y="110" width="90" height="44" rx="5" fill="#1E1B4B" />
+ <path d="M55 110 L55 98 Q55 80 100 80 Q145 80 145 98 L145 110Z" fill="#4F46E5" />
+ <rect x="55" y="109" width="90" height="2" fill="#C7D2FE" />
+ <path d="M80 128 Q86 120 92 128" stroke="#C7D2FE" strokeWidth="3.5" fill="none" strokeLinecap="round" />
+ <path d="M108 128 Q114 120 120 128" stroke="#C7D2FE" strokeWidth="3.5" fill="none" strokeLinecap="round" />
+ <path d="M90 140 Q100 149 110 140" stroke="#C7D2FE" strokeWidth="2.5" fill="none" strokeLinecap="round" />
+ </svg>
+ );
+}
diff --git a/src/ui/onboarding/ProgressDots.tsx b/src/ui/onboarding/ProgressDots.tsx
new file mode 100644
index 0000000..d1d7368
--- /dev/null
+++ b/src/ui/onboarding/ProgressDots.tsx
@@ -0,0 +1,14 @@
+export function ProgressDots({ current, total }: { current: number; total: number }) {
+ return (
+ <div className="flex items-center gap-2">
+ {Array.from({ length: total }, (_, position) => position + 1).map((i) => (
+ <div
+ key={i}
+ className={`h-2 rounded-full transition-all duration-300 ${
+ i === current ? 'w-8 bg-accent' : i < current ? 'w-2 bg-accent/40' : 'w-2 bg-border'
+ }`}
+ />
+ ))}
+ </div>
+ );
+}
diff --git a/src/ui/onboarding/__tests__/settings-persist.test.tsx b/src/ui/onboarding/__tests__/settings-persist.test.tsx
index 8da2d29..224731f 100644
--- a/src/ui/onboarding/__tests__/settings-persist.test.tsx
+++ b/src/ui/onboarding/__tests__/settings-persist.test.tsx
@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const store: Record<string, unknown> = {};
-vi.mock('@/lib/browser-api', () => ({
+vi.mock('@/lib/browser-api/local-storage', () => ({
localStorage: {
get: (keys: string[]) =>
Promise.resolve(Object.fromEntries(keys.filter((key) => key in store).map((key) => [key, store[key]]))),
@@ -13,12 +13,15 @@ vi.mock('@/lib/browser-api', () => ({
return Promise.resolve();
},
},
- getActiveTab: vi.fn().mockResolvedValue(undefined),
- openSidebar: vi.fn(),
+}));
+vi.mock('@/lib/browser-api/get-active-tab', () => ({ getActiveTab: vi.fn().mockResolvedValue(undefined) }));
+vi.mock('@/lib/browser-api/open-sidebar', () => ({ openSidebar: vi.fn() }));
+vi.mock('@/lib/browser-api/request-host-permissions', () => ({
requestHostPermissions: vi.fn().mockResolvedValue(true),
}));
-
-vi.mock('@/lib/offscreen', () => ({ openMicPermissionPage: vi.fn().mockResolvedValue(undefined) }));
+vi.mock('@/lib/offscreen/open-mic-permission-page', () => ({
+ openMicPermissionPage: vi.fn().mockResolvedValue(undefined),
+}));
import { fakeBrowser } from 'wxt/testing';
import { OnboardingApp } from '../App';
diff --git a/src/ui/onboarding/steps/AISetupStep.tsx b/src/ui/onboarding/steps/AISetupStep.tsx
new file mode 100644
index 0000000..04fa7ea
--- /dev/null
+++ b/src/ui/onboarding/steps/AISetupStep.tsx
@@ -0,0 +1,277 @@
+import {
+ Input,
+ KeyStatusNote,
+ KeyWarningNote,
+ ModelList,
+ SecretInput,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ useAiSettings,
+} from '@mimik/ui';
+import { Globe } from 'lucide-react';
+import { i18n } from '#imports';
+import { AI_PROVIDERS, type AIProviderKey, CUSTOM_MODEL_VALUE } from '@/core/capture/ai/models';
+import { AI_LANGUAGES, type AILanguageCode } from '@/core/capture/ai/prompts';
+import { useKeyCheck } from '@/ui/shared/hooks/use-key-check';
+import { ProgressDots } from '../ProgressDots';
+import type { StepProps } from '../types';
+
+export function AISetupStep({ onNext, onSkip, onBack, index, total }: StepProps) {
+ const aiKeyCheck = useKeyCheck();
+ const ai = useAiSettings({ onDirty: aiKeyCheck.reset, reloadOnFocus: true });
+ const {
+ provider,
+ model,
+ apiKey,
+ baseUrl,
+ language: aiLanguage,
+ ownServer,
+ usingCustomModel,
+ providerConfig,
+ setProvider: handleProviderChange,
+ setModel: handleModelChange,
+ setApiKey: handleApiKeyChange,
+ setBaseUrl: handleBaseUrlChange,
+ setLanguage: handleLanguageChange,
+ toggleOwnServer: handleOwnServerToggle,
+ } = ai;
+
+ return (
+ <div className="flex h-screen">
+ <div className="flex-1 flex flex-col justify-center" style={{ padding: '80px 64px' }}>
+ <div className="max-w-md">
+ <p className="text-xs font-semibold text-accent mb-2 tracking-wide uppercase">
+ {i18n.t('onboarding.stepOf', [String(index), String(total)])}
+ </p>
+ <h1 className="text-3xl font-extrabold text-foreground leading-tight mb-2">{i18n.t('onboarding.aiTitle')}</h1>
+ <p className="text-sm text-muted-foreground leading-relaxed mb-8">{i18n.t('onboarding.aiMessage')}</p>
+
+ <div className="space-y-4 mb-8">
+ <div>
+ <label className="block text-xs font-semibold text-foreground mb-1.5">
+ {i18n.t('settings.provider')}
+ </label>
+ <Select value={provider} onValueChange={(v) => handleProviderChange(v as AIProviderKey)}>
+ <SelectTrigger className="w-full h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {Object.entries(AI_PROVIDERS).map(([key, cfg]) => (
+ <SelectItem key={key} value={key}>
+ {cfg.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div>
+ <label className="block text-xs font-semibold text-foreground mb-1.5">{i18n.t('settings.model')}</label>
+ <Select value={usingCustomModel ? CUSTOM_MODEL_VALUE : model} onValueChange={handleModelChange}>
+ <SelectTrigger className="w-full h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {providerConfig.models.map((m) => (
+ <SelectItem key={m.id} value={m.id}>
+ {m.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {usingCustomModel && (
+ <Input
+ type="text"
+ value={model}
+ onChange={(e) => handleModelChange(e.target.value)}
+ placeholder={providerConfig.defaultModel}
+ className="w-full mt-1.5 h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10"
+ />
+ )}
+ </div>
+
+ <div>
+ <label className="block text-xs font-semibold text-foreground mb-1.5">{i18n.t('settings.apiKey')}</label>
+ <SecretInput
+ value={apiKey}
+ onChange={handleApiKeyChange}
+ placeholder="sk-..."
+ className="w-full h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10"
+ buttonClassName="right-3"
+ />
+ <div className="flex items-center gap-3 mt-2">
+ <button
+ type="button"
+ disabled={!apiKey || aiKeyCheck.status === 'checking'}
+ onClick={() => {
+ if (aiKeyCheck.status !== 'checking') void aiKeyCheck.check(provider, apiKey, baseUrl, model);
+ }}
+ className="px-4 py-2 bg-card text-foreground border border-border rounded-lg font-semibold text-xs hover:border-accent hover:text-accent transition-colors disabled:opacity-50 disabled:pointer-events-none"
+ >
+ {i18n.t('settings.checkKey')}
+ </button>
+ <div className="min-w-0">
+ <KeyStatusNote status={aiKeyCheck.status} />
+ <KeyWarningNote warning={aiKeyCheck.warning} />
+ </div>
+ </div>
+ {aiKeyCheck.models && <ModelList models={aiKeyCheck.models} />}
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-xs font-semibold text-foreground flex items-center gap-1">
+ <Globe size={12} className="-mt-px" />
+ {i18n.t('settings.useOwnServer')}
+ </span>
+ <button
+ type="button"
+ role="switch"
+ aria-checked={ownServer}
+ aria-label={i18n.t('settings.useOwnServer')}
+ onClick={handleOwnServerToggle}
+ className={`w-10 h-6 rounded-full transition-colors relative shrink-0 ${
+ ownServer ? 'bg-accent' : 'bg-border'
+ }`}
+ >
+ <span
+ className={`absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow-sm transition-transform ${
+ ownServer ? 'translate-x-4' : 'translate-x-0'
+ }`}
+ />
+ </button>
+ </div>
+ {ownServer && (
+ <div className="mt-2 space-y-2">
+ <Input
+ type="text"
+ value={baseUrl}
+ onChange={(e) => handleBaseUrlChange(e.target.value)}
+ placeholder={providerConfig.defaultBaseUrl}
+ aria-label={i18n.t('settings.baseUrl')}
+ className="w-full h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10"
+ />
+ <p className="text-[11px] text-muted-foreground leading-relaxed">
+ {i18n.t(
+ providerConfig.protocol === 'anthropic'
+ ? 'settings.ownServerHintAnthropic'
+ : 'settings.ownServerHintOpenai',
+ )}
+ </p>
+ </div>
+ )}
+ </div>
+
+ <div>
+ <label className="block text-xs font-semibold text-foreground mb-1.5">
+ {i18n.t('settings.aiLanguage')}
+ </label>
+ <Select value={aiLanguage} onValueChange={(v) => handleLanguageChange(v as AILanguageCode)}>
+ <SelectTrigger className="w-full h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {AI_LANGUAGES.map((lang) => (
+ <SelectItem key={lang.code} value={lang.code}>
+ {lang.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-3">
+ <button
+ onClick={onBack}
+ className="px-8 py-3 bg-card text-foreground border border-border rounded-xl font-semibold text-sm hover:border-accent hover:text-accent transition-colors"
+ >
+ {i18n.t('common.back')}
+ </button>
+ <button
+ onClick={onNext}
+ className="px-8 py-3 bg-primary text-primary-foreground rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors"
+ >
+ {i18n.t('common.continue')}
+ </button>
+ <button
+ onClick={onSkip}
+ className="ml-2 px-6 py-3 text-muted-foreground rounded-xl font-semibold text-sm hover:text-foreground transition-colors"
+ >
+ {i18n.t('common.skip')}
+ </button>
+ </div>
+
+ <div className="mt-6">
+ <ProgressDots current={index} total={total} />
+ </div>
+ </div>
+ </div>
+ <div className="w-1/2 bg-secondary flex items-center justify-center relative overflow-hidden">
+ <div className="absolute w-[400px] h-[400px] bg-[radial-gradient(circle,rgba(79,70,229,0.06),transparent_70%)] top-[20%] left-[30%]" />
+ <div className="animate-[float_4s_ease-in-out_infinite] relative">
+ <svg
+ className="absolute -top-4 right-6 w-6 h-6 text-violet-light opacity-40"
+ style={{ animation: 'sparkle 2s ease-in-out infinite' }}
+ viewBox="0 0 24 24"
+ fill="currentColor"
+ >
+ <path d="M12 2L14 10L22 12L14 14L12 22L10 14L2 12L10 10Z" />
+ </svg>
+ <svg
+ className="absolute bottom-3 -left-3 w-4 h-4 text-violet-light opacity-40"
+ style={{ animation: 'sparkle 2s ease-in-out infinite 0.5s' }}
+ viewBox="0 0 24 24"
+ fill="currentColor"
+ >
+ <path d="M12 2L14 10L22 12L14 14L12 22L10 14L2 12L10 10Z" />
+ </svg>
+ <div className="bg-white rounded-2xl p-9 shadow-lg max-w-sm">
+ <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest mb-4">
+ {i18n.t('onboarding.aiGeneratedDescription')}
+ </p>
+ <div className="flex gap-3 mb-5">
+ <div className="w-7 h-7 rounded-full bg-primary text-primary-foreground text-xs font-bold flex items-center justify-center shrink-0">
+ 3
+ </div>
+ <div>
+ <p className="text-sm text-foreground leading-relaxed">
+ Click on the{' '}
+ <span className="bg-accent/10 text-accent font-semibold px-1 rounded">Pull requests</span> tab in the
+ repository navigation
+ </p>
+ <span className="inline-flex items-center gap-1 text-[9px] font-semibold text-accent bg-secondary px-2 py-0.5 rounded mt-2">
+ <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor">
+ <path d="M12 2L14 10L22 12L14 14L12 22L10 14L2 12L10 10Z" />
+ </svg>
+ {i18n.t('onboarding.aiGenerated')}
+ </span>
+ </div>
+ </div>
+ <div className="border-t border-border my-4" />
+ <div className="flex gap-3">
+ <div className="w-7 h-7 rounded-full bg-primary text-primary-foreground text-xs font-bold flex items-center justify-center shrink-0">
+ 4
+ </div>
+ <div>
+ <p className="text-sm text-foreground leading-relaxed">
+ Click on <span className="bg-accent/10 text-accent font-semibold px-1 rounded">Sort</span> dropdown to
+ change the ordering
+ </p>
+ <span className="inline-flex items-center gap-1 text-[9px] font-semibold text-accent bg-secondary px-2 py-0.5 rounded mt-2">
+ <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor">
+ <path d="M12 2L14 10L22 12L14 14L12 22L10 14L2 12L10 10Z" />
+ </svg>
+ {i18n.t('onboarding.aiGenerated')}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/onboarding/steps/DoneStep.tsx b/src/ui/onboarding/steps/DoneStep.tsx
new file mode 100644
index 0000000..7a90a41
--- /dev/null
+++ b/src/ui/onboarding/steps/DoneStep.tsx
@@ -0,0 +1,124 @@
+import { useEffect } from 'react';
+import { browser, i18n } from '#imports';
+import { localStorage } from '@/lib/browser-api/local-storage';
+import { openSidebar } from '@/lib/browser-api/open-sidebar';
+import { requestHostPermissions } from '@/lib/browser-api/request-host-permissions';
+import { MascotLarge } from '../MascotLarge';
+
+export function DoneStep() {
+ useEffect(() => {
+ localStorage.set({ onboardingCompleted: true });
+ }, []);
+
+ const handleOpen = async () => {
+ openSidebar();
+ const permissionsPromise = requestHostPermissions();
+ await permissionsPromise;
+ browser.tabs.create({ url: browser.runtime.getURL('/fullview.html') });
+ };
+
+ return (
+ <div className="flex h-screen items-center justify-center">
+ <div className="text-center max-w-lg">
+ <div className="flex justify-center mb-8 animate-[float_3s_ease-in-out_infinite]">
+ <MascotLarge size={120} />
+ </div>
+ <h1 className="text-4xl font-extrabold text-foreground mb-3 tracking-tight">
+ {i18n.t('onboarding.doneTitle')}
+ </h1>
+ <p className="text-base text-muted-foreground mb-8 max-w-md mx-auto leading-relaxed">
+ {i18n.t('onboarding.doneMessage')}
+ </p>
+
+ <div className="grid grid-cols-3 gap-3 mb-8">
+ {[
+ {
+ label: i18n.t('onboarding.featureAutoCapture'),
+ icon: (
+ <>
+ <rect x="2" y="3" width="20" height="14" rx="2" />
+ <path d="M8 21h8M12 17v4" />
+ </>
+ ),
+ },
+ {
+ label: i18n.t('onboarding.featureVoice'),
+ icon: (
+ <>
+ <path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z" />
+ <path d="M19 10v2a7 7 0 0 1-14 0v-2M12 19v3" />
+ </>
+ ),
+ },
+ {
+ label: i18n.t('onboarding.featureAIAssist'),
+ icon: <path d="M12 2L14 10L22 12L14 14L12 22L10 14L2 12L10 10Z" />,
+ },
+ {
+ label: i18n.t('onboarding.featureAnnotate'),
+ icon: (
+ <>
+ <path d="M12 20h9" />
+ <path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z" />
+ </>
+ ),
+ },
+ {
+ label: i18n.t('onboarding.featureSmartBlur'),
+ icon: (
+ <>
+ <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
+ <circle cx="12" cy="12" r="3" />
+ </>
+ ),
+ },
+ {
+ label: i18n.t('onboarding.featureExports'),
+ icon: (
+ <>
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
+ <path d="M7 10l5 5 5-5M12 15V3" />
+ </>
+ ),
+ },
+ ].map((f) => (
+ <div key={f.label} className="bg-secondary rounded-xl px-3 py-4 text-center">
+ <div className="text-accent flex justify-center mb-2">
+ <svg
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ >
+ {f.icon}
+ </svg>
+ </div>
+ <p className="text-xs font-semibold text-foreground">{f.label}</p>
+ </div>
+ ))}
+ </div>
+
+ <button
+ onClick={handleOpen}
+ className="inline-flex items-center gap-2 px-7 py-3 bg-primary text-primary-foreground rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors"
+ >
+ {i18n.t('onboarding.openMimik')}
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ >
+ <path d="M5 12h14M12 5l7 7-7 7" />
+ </svg>
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/onboarding/steps/GitHubStarStep.tsx b/src/ui/onboarding/steps/GitHubStarStep.tsx
new file mode 100644
index 0000000..4b3038f
--- /dev/null
+++ b/src/ui/onboarding/steps/GitHubStarStep.tsx
@@ -0,0 +1,60 @@
+import { browser, i18n } from '#imports';
+import { MascotWithStar } from '../MascotWithStar';
+import { ProgressDots } from '../ProgressDots';
+import type { StepProps } from '../types';
+
+const REPO_URL = 'https://github.com/westpoint-io/mimik';
+
+export function GitHubStarStep({ onSkip, onBack, index, total }: StepProps) {
+ const handleStar = () => {
+ browser.tabs.create({ url: REPO_URL, active: true });
+ };
+
+ return (
+ <div className="flex h-screen">
+ <div className="flex-1 flex flex-col justify-center" style={{ padding: '80px 64px' }}>
+ <div className="max-w-md">
+ <p className="text-xs font-semibold text-accent mb-2 tracking-wide uppercase">
+ {i18n.t('onboarding.stepOf', [String(index), String(total)])}
+ </p>
+ <h1 className="text-3xl font-extrabold text-foreground leading-tight mb-2">
+ {i18n.t('onboarding.starTitle')}
+ </h1>
+ <p className="text-sm text-muted-foreground leading-relaxed mb-8">{i18n.t('onboarding.starMessage')}</p>
+
+ <div className="flex items-center gap-3">
+ <button
+ onClick={onBack}
+ className="px-8 py-3 bg-card text-foreground border border-border rounded-xl font-semibold text-sm hover:border-accent hover:text-accent transition-colors"
+ >
+ {i18n.t('common.back')}
+ </button>
+ <button
+ onClick={handleStar}
+ className="px-8 py-3 bg-primary text-primary-foreground rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors"
+ >
+ {i18n.t('onboarding.starAction')}
+ </button>
+ <button
+ onClick={onSkip}
+ className="ml-2 px-6 py-3 text-muted-foreground rounded-xl font-semibold text-sm hover:text-foreground transition-colors"
+ >
+ {i18n.t('onboarding.starLater')}
+ </button>
+ </div>
+
+ <div className="mt-6">
+ <ProgressDots current={index} total={total} />
+ </div>
+ </div>
+ </div>
+ <div className="w-1/2 bg-deep flex items-center justify-center relative overflow-hidden">
+ <div className="absolute w-[500px] h-[500px] bg-[radial-gradient(circle,rgba(79,70,229,0.2),transparent_70%)] top-[10%] right-[-10%]" />
+ <div className="absolute w-[400px] h-[400px] bg-[radial-gradient(circle,rgba(250,204,21,0.08),transparent_70%)] bottom-[14%] left-[8%]" />
+ <div className="animate-[float_3s_ease-in-out_infinite] relative z-10">
+ <MascotWithStar size={300} />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/onboarding/steps/PinExtensionStep.tsx b/src/ui/onboarding/steps/PinExtensionStep.tsx
new file mode 100644
index 0000000..597b913
--- /dev/null
+++ b/src/ui/onboarding/steps/PinExtensionStep.tsx
@@ -0,0 +1,80 @@
+import { i18n } from '#imports';
+import { ProgressDots } from '../ProgressDots';
+import type { StepProps } from '../types';
+
+export function PinExtensionStep({ onNext, onBack, index, total }: StepProps) {
+ return (
+ <div className="flex h-screen">
+ <div className="flex-1 flex flex-col justify-center" style={{ padding: '80px 64px' }}>
+ <div className="max-w-md">
+ <p className="text-xs font-semibold text-accent mb-2 tracking-wide uppercase">
+ {i18n.t('onboarding.stepOf', [String(index), String(total)])}
+ </p>
+ <h1 className="text-3xl font-extrabold text-foreground leading-tight mb-2">
+ {i18n.t('onboarding.pinTitle')}
+ </h1>
+ <p className="text-sm text-muted-foreground leading-relaxed mb-8">{i18n.t('onboarding.pinMessage')}</p>
+
+ <ol className="space-y-4 mb-8">
+ <li className="flex items-start gap-3">
+ <div className="w-7 h-7 rounded-lg bg-accent/10 flex items-center justify-center shrink-0 mt-0.5">
+ <span className="text-accent text-xs font-bold">1</span>
+ </div>
+ <div>
+ <p className="text-sm font-medium text-foreground">{i18n.t('onboarding.pinStep1Title')}</p>
+ <p className="text-xs text-muted-foreground">{i18n.t('onboarding.pinStep1Sub')}</p>
+ </div>
+ </li>
+ <li className="flex items-start gap-3">
+ <div className="w-7 h-7 rounded-lg bg-accent/10 flex items-center justify-center shrink-0 mt-0.5">
+ <span className="text-accent text-xs font-bold">2</span>
+ </div>
+ <div>
+ <p className="text-sm font-medium text-foreground">{i18n.t('onboarding.pinStep2Title')}</p>
+ <p className="text-xs text-muted-foreground">{i18n.t('onboarding.pinStep2Sub')}</p>
+ </div>
+ </li>
+ <li className="flex items-start gap-3">
+ <div className="w-7 h-7 rounded-lg bg-accent/10 flex items-center justify-center shrink-0 mt-0.5">
+ <span className="text-accent text-xs font-bold">3</span>
+ </div>
+ <div>
+ <p className="text-sm font-medium text-foreground">{i18n.t('onboarding.pinStep3Title')}</p>
+ <p className="text-xs text-muted-foreground">{i18n.t('onboarding.pinStep3Sub')}</p>
+ </div>
+ </li>
+ </ol>
+
+ <div className="flex items-center gap-3">
+ <button
+ onClick={onBack}
+ className="px-8 py-3 bg-card text-foreground border border-border rounded-xl font-semibold text-sm hover:border-accent hover:text-accent transition-colors"
+ >
+ {i18n.t('common.back')}
+ </button>
+ <button
+ onClick={onNext}
+ className="px-8 py-3 bg-primary text-primary-foreground rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors"
+ >
+ {i18n.t('common.continue')}
+ </button>
+ </div>
+
+ <div className="mt-6">
+ <ProgressDots current={index} total={total} />
+ </div>
+ </div>
+ </div>
+ <div className="w-1/2 bg-deep flex items-center justify-center relative overflow-hidden">
+ <div className="absolute w-[400px] h-[400px] bg-[radial-gradient(circle,rgba(79,70,229,0.2),transparent_70%)] top-[10%] right-[-10%]" />
+ <div className="animate-[float_4s_ease-in-out_infinite] relative z-10">
+ <img
+ src="/pin-screenshot.png"
+ alt={i18n.t('onboarding.pinScreenshotAlt')}
+ className="rounded-xl shadow-2xl max-w-[400px]"
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/onboarding/steps/SmartBlurStep.tsx b/src/ui/onboarding/steps/SmartBlurStep.tsx
new file mode 100644
index 0000000..ad376e0
--- /dev/null
+++ b/src/ui/onboarding/steps/SmartBlurStep.tsx
@@ -0,0 +1,156 @@
+import { useEffect, useState } from 'react';
+import { i18n } from '#imports';
+import { PRESET_LABELS, type PresetKey } from '@/core/blur/regexes';
+import { localStorage } from '@/lib/browser-api/local-storage';
+import { ProgressDots } from '../ProgressDots';
+import type { StepProps } from '../types';
+
+const BLUR_PRESET_I18N: Record<PresetKey, string> = {
+ email: 'email',
+ phone: 'phoneNumbers',
+ ssn: 'ssn',
+ creditCard: 'creditCard',
+ ipAddress: 'ipAddress',
+ macAddress: 'macAddress',
+};
+
+export function SmartBlurStep({ onNext, onBack, index, total }: StepProps) {
+ const [blurPresets, setBlurPresets] = useState<Record<PresetKey, boolean>>({
+ email: true,
+ phone: true,
+ ssn: false,
+ creditCard: false,
+ ipAddress: false,
+ macAddress: false,
+ });
+
+ useEffect(() => {
+ localStorage.get(['blurPresets']).then((stored) => {
+ if (stored.blurPresets && typeof stored.blurPresets === 'object') {
+ setBlurPresets((prev) => ({ ...prev, ...(stored.blurPresets as Record<PresetKey, boolean>) }));
+ }
+ });
+ }, []);
+
+ const handleToggle = (key: PresetKey) => {
+ setBlurPresets((prev) => {
+ const next = { ...prev, [key]: !prev[key] };
+ localStorage.set({ blurPresets: next });
+ return next;
+ });
+ };
+
+ return (
+ <div className="flex h-screen">
+ <div className="flex-1 flex flex-col justify-center" style={{ padding: '80px 64px' }}>
+ <div className="max-w-md">
+ <p className="text-xs font-semibold text-accent mb-2 tracking-wide uppercase">
+ {i18n.t('onboarding.stepOf', [String(index), String(total)])}
+ </p>
+ <h1 className="text-3xl font-extrabold text-foreground leading-tight mb-2">
+ {i18n.t('onboarding.blurTitle')}
+ </h1>
+ <p className="text-sm text-muted-foreground leading-relaxed mb-8">{i18n.t('onboarding.blurMessage')}</p>
+
+ <div className="space-y-1 mb-8 border border-border rounded-2xl p-4">
+ {(Object.keys(PRESET_LABELS) as PresetKey[]).map((key, i, arr) => (
+ <div
+ key={key}
+ className={`flex items-center justify-between py-3 ${i < arr.length - 1 ? 'border-b border-secondary' : ''}`}
+ >
+ <span className="text-sm font-medium text-foreground">
+ {i18n.t(`blurPresets.${BLUR_PRESET_I18N[key]}`)}
+ </span>
+ <button
+ onClick={() => handleToggle(key)}
+ className={`w-11 h-6 rounded-full transition-colors relative ${
+ blurPresets[key] ? 'bg-accent' : 'bg-border'
+ }`}
+ >
+ <span
+ className={`absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow-sm transition-transform ${
+ blurPresets[key] ? 'translate-x-5' : 'translate-x-0'
+ }`}
+ />
+ </button>
+ </div>
+ ))}
+ </div>
+
+ <div className="flex items-center gap-3">
+ <button
+ onClick={onBack}
+ className="px-8 py-3 bg-card text-foreground border border-border rounded-xl font-semibold text-sm hover:border-accent hover:text-accent transition-colors"
+ >
+ {i18n.t('common.back')}
+ </button>
+ <button
+ onClick={onNext}
+ className="px-8 py-3 bg-primary text-primary-foreground rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors"
+ >
+ {i18n.t('common.continue')}
+ </button>
+ </div>
+
+ <div className="mt-6">
+ <ProgressDots current={index} total={total} />
+ </div>
+ </div>
+ </div>
+ <div className="w-1/2 bg-deep flex items-center justify-center relative overflow-hidden">
+ <div className="absolute w-[350px] h-[350px] bg-[radial-gradient(circle,rgba(79,70,229,0.25),transparent_70%)] bottom-[20%] right-[20%]" />
+ <div className="animate-[float_4s_ease-in-out_infinite] relative z-10">
+ <div className="bg-white rounded-2xl p-7 shadow-lg" style={{ minWidth: 320 }}>
+ <p className="text-xs font-semibold text-foreground mb-4">{i18n.t('onboarding.screenshotPreview')}</p>
+ {[
+ { icon: '@', label: i18n.t('blurPresets.email'), value: '[email protected]', blurred: true },
+ { icon: '#', label: i18n.t('blurPresets.phoneNumbers'), value: '(555) 867-5309', blurred: true },
+ { icon: 'ID', label: i18n.t('blurPresets.ssn'), value: i18n.t('onboarding.notEnabled'), blurred: false },
+ {
+ icon: '$',
+ label: i18n.t('blurPresets.creditCard'),
+ value: i18n.t('onboarding.notEnabled'),
+ blurred: false,
+ },
+ {
+ icon: 'IP',
+ label: i18n.t('blurPresets.ipAddress'),
+ value: i18n.t('onboarding.notEnabled'),
+ blurred: false,
+ },
+ ].map((row, i, arr) => (
+ <div
+ key={row.label}
+ className={`flex items-center gap-3 py-2.5 ${i < arr.length - 1 ? 'border-b border-border' : ''}`}
+ >
+ <div className="w-6 h-6 rounded-md bg-secondary flex items-center justify-center text-[10px] font-semibold text-accent">
+ {row.icon}
+ </div>
+ <span className="text-xs text-muted-foreground flex-1">{row.label}</span>
+ <span
+ className={`text-xs font-semibold ${row.blurred ? 'text-foreground blur-[4px] select-none' : 'text-muted-foreground font-normal'}`}
+ >
+ {row.value}
+ </span>
+ </div>
+ ))}
+ <div className="inline-flex items-center gap-1.5 text-[10px] font-semibold text-success bg-success/10 px-2.5 py-1 rounded mt-3">
+ <svg
+ width="13"
+ height="13"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ >
+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
+ </svg>
+ {i18n.t('onboarding.categoriesProtected', ['2'])}
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/onboarding/steps/VoiceStep.tsx b/src/ui/onboarding/steps/VoiceStep.tsx
new file mode 100644
index 0000000..f6c37b5
--- /dev/null
+++ b/src/ui/onboarding/steps/VoiceStep.tsx
@@ -0,0 +1,184 @@
+import { SecretInput, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@mimik/ui';
+import { Mic, MousePointerClick, Shield } from 'lucide-react';
+import { useEffect, useState } from 'react';
+import { i18n } from '#imports';
+import type { VoiceProvider } from '@/core/capture/voice/transcribe';
+import { localStorage } from '@/lib/browser-api/local-storage';
+import { MicrophonePicker } from '@/ui/shared/MicrophonePicker';
+import { ProgressDots } from '../ProgressDots';
+import type { StepProps } from '../types';
+
+export function VoiceStep({ onNext, onSkip, onBack, index, total }: StepProps) {
+ const [provider, setProvider] = useState<VoiceProvider>('openai');
+ const [apiKey, setApiKey] = useState('');
+ const [microphoneId, setMicrophoneId] = useState('');
+
+ useEffect(() => {
+ const load = () =>
+ localStorage.get(['voiceProvider', 'voiceApiKey', 'voiceMicrophoneId']).then((stored) => {
+ if (stored.voiceProvider === 'openai' || stored.voiceProvider === 'groq') setProvider(stored.voiceProvider);
+ if (typeof stored.voiceApiKey === 'string') setApiKey(stored.voiceApiKey);
+ if (typeof stored.voiceMicrophoneId === 'string') setMicrophoneId(stored.voiceMicrophoneId);
+ });
+
+ void load();
+ const onVisible = () => {
+ if (document.visibilityState === 'visible') void load();
+ };
+ document.addEventListener('visibilitychange', onVisible);
+ return () => document.removeEventListener('visibilitychange', onVisible);
+ }, []);
+
+ const handleMicrophoneChange = (deviceId: string) => {
+ setMicrophoneId(deviceId);
+ void localStorage.set({ voiceMicrophoneId: deviceId });
+ };
+
+ const handleProviderChange = (nextProvider: VoiceProvider) => {
+ setProvider(nextProvider);
+ void localStorage.set({ voiceProvider: nextProvider });
+ };
+
+ const handleApiKeyChange = (nextKey: string) => {
+ setApiKey(nextKey);
+ void localStorage.set({ voiceApiKey: nextKey });
+ };
+
+ return (
+ <div className="flex h-screen">
+ <div className="flex-1 flex flex-col justify-center overflow-y-auto" style={{ padding: '64px' }}>
+ <div className="max-w-md">
+ <p className="text-xs font-semibold text-accent mb-2 tracking-wide uppercase">
+ {i18n.t('onboarding.stepOf', [String(index), String(total)])}
+ </p>
+ <h1 className="text-3xl font-extrabold text-foreground leading-tight mb-2">
+ {i18n.t('onboarding.voiceTitle')}
+ </h1>
+ <p className="text-sm text-muted-foreground leading-relaxed mb-6">{i18n.t('onboarding.voiceMessage')}</p>
+
+ <div className="border border-border rounded-2xl p-4 space-y-3 mb-6">
+ <div className="flex gap-3">
+ <div className="flex-1">
+ <label className="block text-xs font-semibold text-foreground mb-1.5">
+ {i18n.t('settings.provider')}
+ </label>
+ <Select value={provider} onValueChange={(v) => handleProviderChange(v as VoiceProvider)}>
+ <SelectTrigger className="h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="openai">OpenAI</SelectItem>
+ <SelectItem value="groq">Groq</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="flex-1">
+ <label className="block text-xs font-semibold text-foreground mb-1.5">
+ {i18n.t('settings.apiKey')}
+ </label>
+ <SecretInput
+ value={apiKey}
+ onChange={handleApiKeyChange}
+ placeholder={provider === 'groq' ? 'gsk_...' : 'sk-...'}
+ className="w-full h-11 rounded-xl px-4 text-sm focus:border-accent focus:ring-accent/10"
+ />
+ </div>
+ </div>
+
+ <MicrophonePicker
+ value={microphoneId}
+ onChange={handleMicrophoneChange}
+ triggerClassName="h-11 px-4 text-sm"
+ />
+
+ <div className="flex items-start gap-2 px-3 py-2.5 rounded-xl bg-secondary text-[11px] text-muted-foreground leading-relaxed">
+ <Mic size={12} className="shrink-0 mt-0.5 text-accent" />
+ <span>{i18n.t('onboarding.voiceRecordHint')}</span>
+ </div>
+
+ <div className="flex items-start gap-2 px-3 py-2.5 rounded-xl bg-secondary text-[11px] text-muted-foreground leading-relaxed">
+ <Shield size={12} className="shrink-0 mt-0.5 text-accent" />
+ <span>{i18n.t('onboarding.voiceDataNotice')}</span>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-3">
+ <button
+ onClick={onBack}
+ className="px-8 py-3 bg-card text-foreground border border-border rounded-xl font-semibold text-sm hover:border-accent hover:text-accent transition-colors"
+ >
+ {i18n.t('common.back')}
+ </button>
+ <button
+ onClick={onNext}
+ className="px-8 py-3 bg-primary text-primary-foreground rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors"
+ >
+ {i18n.t('common.continue')}
+ </button>
+ <button
+ onClick={onSkip}
+ className="ml-2 px-6 py-3 text-muted-foreground rounded-xl font-semibold text-sm hover:text-foreground transition-colors"
+ >
+ {i18n.t('common.skip')}
+ </button>
+ </div>
+
+ <div className="mt-6">
+ <ProgressDots current={index} total={total} />
+ </div>
+ </div>
+ </div>
+ <div className="w-1/2 bg-deep flex items-center justify-center relative overflow-hidden">
+ <div className="absolute w-[400px] h-[400px] bg-[radial-gradient(circle,rgba(79,70,229,0.22),transparent_70%)] top-[15%] right-[-5%]" />
+ <div className="animate-[float_4s_ease-in-out_infinite] relative z-10">
+ <div className="bg-white rounded-2xl p-7 shadow-lg" style={{ minWidth: 340 }}>
+ <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest mb-4">
+ {i18n.t('onboarding.voiceDemoLabel')}
+ </p>
+
+ <div className="flex items-start gap-3">
+ <div className="w-7 h-7 rounded-full bg-accent/10 flex items-center justify-center shrink-0">
+ <Mic size={13} className="text-accent" />
+ </div>
+ <div>
+ <p className="text-[9px] font-semibold uppercase tracking-widest text-accent">
+ {i18n.t('onboarding.voiceDemoSay')}
+ </p>
+ <p className="text-sm text-foreground leading-relaxed mt-0.5">{i18n.t('onboarding.voiceDemoQuote')}</p>
+ </div>
+ </div>
+
+ <div className="ml-3.5 my-1.5 h-5 w-px bg-border" />
+
+ <div className="flex items-start gap-3">
+ <div className="w-7 h-7 rounded-full bg-secondary flex items-center justify-center shrink-0">
+ <MousePointerClick size={13} className="text-accent" />
+ </div>
+ <div>
+ <p className="text-[9px] font-semibold uppercase tracking-widest text-muted-foreground">
+ {i18n.t('onboarding.voiceDemoAct')}
+ </p>
+ <p className="text-sm text-foreground leading-relaxed mt-0.5">{i18n.t('onboarding.voiceDemoAction')}</p>
+ </div>
+ </div>
+
+ <div className="border-t border-border my-4" />
+
+ <div className="flex gap-3">
+ <div className="w-7 h-7 rounded-full bg-primary text-primary-foreground text-xs font-bold flex items-center justify-center shrink-0">
+ 3
+ </div>
+ <div>
+ <p className="text-sm text-foreground leading-relaxed">{i18n.t('onboarding.voiceDemoQuote')}</p>
+ <span className="inline-flex items-center gap-1 text-[9px] font-semibold text-accent bg-secondary px-2 py-0.5 rounded mt-2">
+ <Mic size={9} />
+ {i18n.t('onboarding.voiceDemoBadge')}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/onboarding/steps/WelcomeStep.tsx b/src/ui/onboarding/steps/WelcomeStep.tsx
new file mode 100644
index 0000000..f508242
--- /dev/null
+++ b/src/ui/onboarding/steps/WelcomeStep.tsx
@@ -0,0 +1,46 @@
+import { i18n } from '#imports';
+import { MascotLarge } from '../MascotLarge';
+
+export function WelcomeStep({ onNext }: { onNext: () => void }) {
+ return (
+ <div className="flex h-screen">
+ <div className="flex-1 flex flex-col justify-center" style={{ padding: '80px 64px' }}>
+ <div className="max-w-lg">
+ <span className="inline-flex text-xs font-semibold text-accent bg-secondary px-3.5 py-1.5 rounded-full mb-6">
+ {i18n.t('onboarding.welcomeBadge')}
+ </span>
+ <h1 className="text-4xl font-extrabold text-foreground leading-tight mb-3 tracking-tight">
+ {i18n.t('onboarding.welcomeTitle')}
+ </h1>
+ <p className="text-base text-muted-foreground leading-relaxed mb-10 max-w-md">
+ {i18n.t('onboarding.welcomeMessage')}
+ </p>
+ <button
+ onClick={onNext}
+ className="inline-flex items-center gap-2 px-7 py-3 bg-primary text-primary-foreground rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors"
+ >
+ {i18n.t('onboarding.getStarted')}
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ >
+ <path d="M5 12h14M12 5l7 7-7 7" />
+ </svg>
+ </button>
+ </div>
+ </div>
+ <div className="w-1/2 bg-deep flex items-center justify-center relative overflow-hidden">
+ <div className="absolute w-[500px] h-[500px] bg-[radial-gradient(circle,rgba(79,70,229,0.2),transparent_70%)] top-[10%] right-[-10%]" />
+ <div className="absolute w-[400px] h-[400px] bg-[radial-gradient(circle,rgba(56,189,248,0.1),transparent_70%)] bottom-[10%] left-[10%]" />
+ <div className="animate-[float_3s_ease-in-out_infinite]">
+ <MascotLarge size={280} />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/onboarding/types.ts b/src/ui/onboarding/types.ts
new file mode 100644
index 0000000..6ea9aa1
--- /dev/null
+++ b/src/ui/onboarding/types.ts
@@ -0,0 +1,7 @@
+export interface StepProps {
+ onNext: () => void;
+ onSkip: () => void;
+ onBack: () => void;
+ index: number;
+ total: number;
+}
diff --git a/src/ui/shared/MicrophonePicker.tsx b/src/ui/shared/MicrophonePicker.tsx
index 5f46537..a67c6fc 100644
--- a/src/ui/shared/MicrophonePicker.tsx
+++ b/src/ui/shared/MicrophonePicker.tsx
@@ -1,23 +1,18 @@
import { i18n } from '@mimik/core/env';
import { Button, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@mimik/ui';
-import { Check, ChevronRight, Mic, MicOff, Square, TriangleAlert } from 'lucide-react';
+import { ChevronRight, Mic, Square, TriangleAlert } from 'lucide-react';
import { useCallback, useEffect, useId, useRef, useState } from 'react';
-import { getActiveTab } from '@/lib/browser-api';
-import { openMicPermissionPage } from '@/lib/offscreen';
-import {
- isMicrophoneMissing,
- type MicrophoneDevice,
- type MicrophonePermission,
- type MicrophoneStatus,
- microphoneListState,
- microphoneStatus,
- nextMicLevel,
- SPEAKING_LEVEL,
- SYSTEM_DEFAULT_VALUE,
- toMicrophoneOptions,
- toSelectValue,
- toStoredMicrophoneId,
-} from './microphones';
+import { getActiveTab } from '@/lib/browser-api/get-active-tab';
+import { openMicPermissionPage } from '@/lib/offscreen/open-mic-permission-page';
+import { isMicrophoneMissing } from './lib/is-microphone-missing';
+import { microphoneListState } from './lib/microphone-list-state';
+import { type MicrophonePermission, microphoneStatus } from './lib/microphone-status';
+import { nextMicLevel, SPEAKING_LEVEL } from './lib/next-mic-level';
+import { toMicrophoneOptions } from './lib/to-microphone-options';
+import { SYSTEM_DEFAULT_VALUE, toSelectValue } from './lib/to-select-value';
+import { toStoredMicrophoneId } from './lib/to-stored-microphone-id';
+import { StatusBadge } from './StatusBadge';
+import type { MicrophoneDevice } from './types';
interface MicrophonePickerProps {
triggerClassName?: string;
@@ -35,30 +30,6 @@ const MICROPHONE: PermissionDescriptor = { name: 'microphone' as PermissionName
const ANALYSER_FFT_SIZE = 2048;
const METER_INTERVAL_MS = 80;
-const STATUS_STYLES: Record<MicrophoneStatus, string> = {
- allowed: 'bg-success/10 text-success',
- blocked: 'bg-destructive/10 text-destructive',
- pending: 'bg-secondary text-muted-foreground',
-};
-
-const STATUS_LABELS: Record<MicrophoneStatus, string> = {
- allowed: 'settings.microphoneStatusAllowed',
- blocked: 'settings.microphoneStatusBlocked',
- pending: 'settings.microphoneStatusPending',
-};
-
-function StatusBadge({ status }: { status: MicrophoneStatus }) {
- const Icon = status === 'allowed' ? Check : status === 'blocked' ? MicOff : Mic;
- return (
- <span
- className={`inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-[9px] font-semibold ${STATUS_STYLES[status]}`}
- >
- <Icon size={9} />
- {i18n.t(STATUS_LABELS[status])}
- </span>
- );
-}
-
export function MicrophonePicker({ value, onChange, triggerClassName }: MicrophonePickerProps) {
const [devices, setDevices] = useState<MicrophoneDevice[]>([]);
const [testing, setTesting] = useState(false);
diff --git a/src/ui/shared/SettingsView.tsx b/src/ui/shared/SettingsView.tsx
index a0c4015..6f778d3 100644
--- a/src/ui/shared/SettingsView.tsx
+++ b/src/ui/shared/SettingsView.tsx
@@ -40,21 +40,16 @@ import {
TriangleAlert,
} from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
-import { localStorage } from '@/lib/browser-api';
-import { useKeyCheck } from '@/ui/shared/key-check';
+import { localStorage } from '@/lib/browser-api/local-storage';
+import { useKeyCheck } from '@/ui/shared/hooks/use-key-check';
+import { useSettingsAutosave } from '@/ui/shared/hooks/use-settings-autosave';
import { MicrophonePicker } from '@/ui/shared/MicrophonePicker';
-import { useSettingsAutosave } from '@/ui/shared/use-settings-autosave';
+import { footerPresets } from './lib/footer-presets';
interface SettingsViewProps {
onBack?: () => void;
}
-const FOOTER_PRESETS = () => [
- defaultFooterLine(),
- i18n.t('settings.footerPresetConfidential'),
- i18n.t('settings.footerPresetNoDistribute'),
-];
-
export function SettingsView({ onBack }: SettingsViewProps) {
const [provider, setProvider] = useState<AIProviderKey>('openai');
const [apiKey, setApiKey] = useState('');
@@ -261,7 +256,7 @@ export function SettingsView({ onBack }: SettingsViewProps) {
className="h-8 text-[13px] rounded-lg border-border"
/>
<div className="flex flex-wrap gap-1.5 mt-2">
- {FOOTER_PRESETS().map((preset) => (
+ {footerPresets().map((preset) => (
<button
key={preset}
type="button"
diff --git a/src/ui/shared/StatusBadge.tsx b/src/ui/shared/StatusBadge.tsx
new file mode 100644
index 0000000..f9ec5c6
--- /dev/null
+++ b/src/ui/shared/StatusBadge.tsx
@@ -0,0 +1,27 @@
+import { i18n } from '@mimik/core/env';
+import { Check, Mic, MicOff } from 'lucide-react';
+import type { MicrophoneStatus } from './lib/microphone-status';
+
+const STATUS_STYLES: Record<MicrophoneStatus, string> = {
+ allowed: 'bg-success/10 text-success',
+ blocked: 'bg-destructive/10 text-destructive',
+ pending: 'bg-secondary text-muted-foreground',
+};
+
+const STATUS_LABELS: Record<MicrophoneStatus, string> = {
+ allowed: 'settings.microphoneStatusAllowed',
+ blocked: 'settings.microphoneStatusBlocked',
+ pending: 'settings.microphoneStatusPending',
+};
+
+export function StatusBadge({ status }: { status: MicrophoneStatus }) {
+ const Icon = status === 'allowed' ? Check : status === 'blocked' ? MicOff : Mic;
+ return (
+ <span
+ className={`inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-[9px] font-semibold ${STATUS_STYLES[status]}`}
+ >
+ <Icon size={9} />
+ {i18n.t(STATUS_LABELS[status])}
+ </span>
+ );
+}
diff --git a/src/ui/shared/UpdateNotice.tsx b/src/ui/shared/UpdateNotice.tsx
index b88fa65..ee2e3f0 100644
--- a/src/ui/shared/UpdateNotice.tsx
+++ b/src/ui/shared/UpdateNotice.tsx
@@ -1,7 +1,8 @@
import { i18n } from '@mimik/core/env';
import { Sparkles, X } from 'lucide-react';
import { useEffect, useState } from 'react';
-import { dismissUpdateNotice, readUpdateNotice } from '@/lib/update-notice';
+import { dismissUpdateNotice } from '@/lib/update-notice/dismiss-update-notice';
+import { readUpdateNotice } from '@/lib/update-notice/read-update-notice';
const RELEASES_URL = 'https://github.com/westpoint-io/mimik/releases';
diff --git a/src/ui/shared/__tests__/key-check.test.tsx b/src/ui/shared/__tests__/key-check.test.tsx
index dc06f9c..a70eac7 100644
--- a/src/ui/shared/__tests__/key-check.test.tsx
+++ b/src/ui/shared/__tests__/key-check.test.tsx
@@ -8,7 +8,7 @@ const { sendMessageMock } = vi.hoisted(() => ({ sendMessageMock: vi.fn() }));
vi.mock('@/lib/messaging', () => ({ sendMessage: sendMessageMock }));
import { KeyStatusNote, SecretInput } from '@mimik/ui';
-import { useKeyCheck } from '@/ui/shared/key-check';
+import { useKeyCheck } from '@/ui/shared/hooks/use-key-check';
describe('useKeyCheck', () => {
beforeEach(() => {
diff --git a/src/ui/shared/__tests__/microphones.test.ts b/src/ui/shared/__tests__/microphones.test.ts
index 87d1c23..7a50a8c 100644
--- a/src/ui/shared/__tests__/microphones.test.ts
+++ b/src/ui/shared/__tests__/microphones.test.ts
@@ -1,18 +1,14 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
-import {
- isMicrophoneMissing,
- type MicrophoneOption,
- microphoneListState,
- microphoneStatus,
- nextMicLevel,
- SPEAKING_LEVEL,
- SYSTEM_DEFAULT_VALUE,
- toMicrophoneOptions,
- toSelectValue,
- toStoredMicrophoneId,
-} from '../microphones';
+import { isMicrophoneMissing } from '../lib/is-microphone-missing';
+import { microphoneListState } from '../lib/microphone-list-state';
+import { microphoneStatus } from '../lib/microphone-status';
+import { nextMicLevel, SPEAKING_LEVEL } from '../lib/next-mic-level';
+import { toMicrophoneOptions } from '../lib/to-microphone-options';
+import { SYSTEM_DEFAULT_VALUE, toSelectValue } from '../lib/to-select-value';
+import { toStoredMicrophoneId } from '../lib/to-stored-microphone-id';
+import type { MicrophoneOption } from '../types';
const LOCALES = ['en', 'de', 'es', 'fr', 'pt-BR', 'zh-CN'];
diff --git a/src/ui/shared/__tests__/settings-autosave.test.ts b/src/ui/shared/__tests__/settings-autosave.test.ts
index d91a8c5..c148da4 100644
--- a/src/ui/shared/__tests__/settings-autosave.test.ts
+++ b/src/ui/shared/__tests__/settings-autosave.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { changedSettings } from '../settings-autosave';
+import { changedSettings } from '../lib/changed-settings';
describe('changedSettings', () => {
it('writes nothing when a render changed no value', () => {
diff --git a/src/ui/shared/key-check.tsx b/src/ui/shared/hooks/use-key-check.tsx
similarity index 100%
rename from src/ui/shared/key-check.tsx
rename to src/ui/shared/hooks/use-key-check.tsx
diff --git a/src/ui/shared/use-settings-autosave.ts b/src/ui/shared/hooks/use-settings-autosave.ts
similarity index 98%
rename from src/ui/shared/use-settings-autosave.ts
rename to src/ui/shared/hooks/use-settings-autosave.ts
index fbc4827..2c22f5d 100644
--- a/src/ui/shared/use-settings-autosave.ts
+++ b/src/ui/shared/hooks/use-settings-autosave.ts
@@ -1,7 +1,7 @@
import { localStorage } from '@mimik/core/env';
import { logger } from '@mimik/core/logger';
import { useCallback, useEffect, useRef, useState } from 'react';
-import { changedSettings, type SettingsSnapshot } from '@/ui/shared/settings-autosave';
+import { changedSettings, type SettingsSnapshot } from '@/ui/shared/lib/changed-settings';
const SAVE_DEBOUNCE_MS = 400;
const SAVED_BADGE_MS = 1600;
diff --git a/src/ui/shared/lib/audio-inputs.ts b/src/ui/shared/lib/audio-inputs.ts
new file mode 100644
index 0000000..2fb601b
--- /dev/null
+++ b/src/ui/shared/lib/audio-inputs.ts
@@ -0,0 +1,5 @@
+import type { MicrophoneDevice } from '../types';
+
+export function audioInputs(devices: readonly MicrophoneDevice[]): MicrophoneDevice[] {
+ return devices.filter((device) => device.kind === 'audioinput');
+}
diff --git a/src/ui/shared/settings-autosave.ts b/src/ui/shared/lib/changed-settings.ts
similarity index 100%
rename from src/ui/shared/settings-autosave.ts
rename to src/ui/shared/lib/changed-settings.ts
diff --git a/src/ui/shared/lib/footer-presets.ts b/src/ui/shared/lib/footer-presets.ts
new file mode 100644
index 0000000..db31e31
--- /dev/null
+++ b/src/ui/shared/lib/footer-presets.ts
@@ -0,0 +1,8 @@
+import { i18n } from '@mimik/core/env';
+import { defaultFooterLine } from '@mimik/core/export/branding';
+
+export const footerPresets = () => [
+ defaultFooterLine(),
+ i18n.t('settings.footerPresetConfidential'),
+ i18n.t('settings.footerPresetNoDistribute'),
+];
diff --git a/src/ui/shared/lib/is-microphone-missing.ts b/src/ui/shared/lib/is-microphone-missing.ts
new file mode 100644
index 0000000..f9be3eb
--- /dev/null
+++ b/src/ui/shared/lib/is-microphone-missing.ts
@@ -0,0 +1,7 @@
+import type { MicrophoneOption } from '../types';
+
+export function isMicrophoneMissing(storedId: string, options: readonly MicrophoneOption[]): boolean {
+ const id = storedId.trim();
+ if (!id) return false;
+ return !options.some((option) => option.deviceId === id);
+}
diff --git a/src/ui/shared/lib/microphone-list-state.ts b/src/ui/shared/lib/microphone-list-state.ts
new file mode 100644
index 0000000..b9d2cf6
--- /dev/null
+++ b/src/ui/shared/lib/microphone-list-state.ts
@@ -0,0 +1,11 @@
+import type { MicrophoneDevice } from '../types';
+import { audioInputs } from './audio-inputs';
+
+export type MicrophoneListState = 'no-devices' | 'unlabelled' | 'ready';
+
+export function microphoneListState(devices: readonly MicrophoneDevice[]): MicrophoneListState {
+ const inputs = audioInputs(devices);
+ if (inputs.length === 0) return 'no-devices';
+ const withheld = inputs.some((device) => !device.deviceId.trim() || !device.label.trim());
+ return withheld ? 'unlabelled' : 'ready';
+}
diff --git a/src/ui/shared/lib/microphone-status.ts b/src/ui/shared/lib/microphone-status.ts
new file mode 100644
index 0000000..ad075ec
--- /dev/null
+++ b/src/ui/shared/lib/microphone-status.ts
@@ -0,0 +1,11 @@
+import type { MicrophoneListState } from './microphone-list-state';
+
+export type MicrophonePermission = PermissionState | 'unknown';
+
+export type MicrophoneStatus = 'allowed' | 'blocked' | 'pending';
+
+export function microphoneStatus(permission: MicrophonePermission, list: MicrophoneListState): MicrophoneStatus {
+ if (permission === 'denied') return 'blocked';
+ if (permission === 'granted' || list === 'ready') return 'allowed';
+ return 'pending';
+}
diff --git a/src/ui/shared/lib/next-mic-level.ts b/src/ui/shared/lib/next-mic-level.ts
new file mode 100644
index 0000000..9e2030e
--- /dev/null
+++ b/src/ui/shared/lib/next-mic-level.ts
@@ -0,0 +1,13 @@
+const LEVEL_FLOOR_DB = -60;
+
+const SPEAKING_FLOOR_DB = -45;
+
+export const SPEAKING_LEVEL = (SPEAKING_FLOOR_DB - LEVEL_FLOOR_DB) / -LEVEL_FLOOR_DB;
+
+const LEVEL_SMOOTHING = 0.6;
+
+export function nextMicLevel(rms: number, previous: number): number {
+ const db = rms > 0 ? 20 * Math.log10(rms) : LEVEL_FLOOR_DB;
+ const normalised = Math.min(1, Math.max(0, (db - LEVEL_FLOOR_DB) / -LEVEL_FLOOR_DB));
+ return previous * LEVEL_SMOOTHING + normalised * (1 - LEVEL_SMOOTHING);
+}
diff --git a/src/ui/shared/lib/to-microphone-options.ts b/src/ui/shared/lib/to-microphone-options.ts
new file mode 100644
index 0000000..2b4ed9a
--- /dev/null
+++ b/src/ui/shared/lib/to-microphone-options.ts
@@ -0,0 +1,16 @@
+import type { MicrophoneDevice, MicrophoneOption } from '../types';
+import { audioInputs } from './audio-inputs';
+
+const GENERIC_DEVICE_IDS = new Set(['default', 'communications']);
+
+export function toMicrophoneOptions(devices: readonly MicrophoneDevice[]): MicrophoneOption[] {
+ const seen = new Set<string>();
+ const options: MicrophoneOption[] = [];
+ for (const device of audioInputs(devices)) {
+ const deviceId = device.deviceId.trim();
+ if (!deviceId || GENERIC_DEVICE_IDS.has(deviceId) || seen.has(deviceId)) continue;
+ seen.add(deviceId);
+ options.push({ deviceId, label: device.label.trim() });
+ }
+ return options;
+}
diff --git a/src/ui/shared/lib/to-select-value.ts b/src/ui/shared/lib/to-select-value.ts
new file mode 100644
index 0000000..2272877
--- /dev/null
+++ b/src/ui/shared/lib/to-select-value.ts
@@ -0,0 +1,5 @@
+export const SYSTEM_DEFAULT_VALUE = 'mimik-system-default';
+
+export function toSelectValue(storedId: string): string {
+ return storedId.trim() || SYSTEM_DEFAULT_VALUE;
+}
diff --git a/src/ui/shared/lib/to-stored-microphone-id.ts b/src/ui/shared/lib/to-stored-microphone-id.ts
new file mode 100644
index 0000000..f760687
--- /dev/null
+++ b/src/ui/shared/lib/to-stored-microphone-id.ts
@@ -0,0 +1,5 @@
+import { SYSTEM_DEFAULT_VALUE } from './to-select-value';
+
+export function toStoredMicrophoneId(value: string): string {
+ return value === SYSTEM_DEFAULT_VALUE ? '' : value.trim();
+}
diff --git a/src/ui/shared/microphones.ts b/src/ui/shared/microphones.ts
deleted file mode 100644
index ba3dc18..0000000
--- a/src/ui/shared/microphones.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-export const SYSTEM_DEFAULT_VALUE = 'mimik-system-default';
-
-const GENERIC_DEVICE_IDS = new Set(['default', 'communications']);
-
-export interface MicrophoneOption {
- deviceId: string;
- label: string;
-}
-
-export type MicrophoneListState = 'no-devices' | 'unlabelled' | 'ready';
-
-export type MicrophoneDevice = Pick<MediaDeviceInfo, 'kind' | 'deviceId' | 'label'>;
-
-function audioInputs(devices: readonly MicrophoneDevice[]): MicrophoneDevice[] {
- return devices.filter((device) => device.kind === 'audioinput');
-}
-
-export function toMicrophoneOptions(devices: readonly MicrophoneDevice[]): MicrophoneOption[] {
- const seen = new Set<string>();
- const options: MicrophoneOption[] = [];
- for (const device of audioInputs(devices)) {
- const deviceId = device.deviceId.trim();
- if (!deviceId || GENERIC_DEVICE_IDS.has(deviceId) || seen.has(deviceId)) continue;
- seen.add(deviceId);
- options.push({ deviceId, label: device.label.trim() });
- }
- return options;
-}
-
-export function microphoneListState(devices: readonly MicrophoneDevice[]): MicrophoneListState {
- const inputs = audioInputs(devices);
- if (inputs.length === 0) return 'no-devices';
- const withheld = inputs.some((device) => !device.deviceId.trim() || !device.label.trim());
- return withheld ? 'unlabelled' : 'ready';
-}
-
-export type MicrophonePermission = PermissionState | 'unknown';
-
-export type MicrophoneStatus = 'allowed' | 'blocked' | 'pending';
-
-export function microphoneStatus(permission: MicrophonePermission, list: MicrophoneListState): MicrophoneStatus {
- if (permission === 'denied') return 'blocked';
- if (permission === 'granted' || list === 'ready') return 'allowed';
- return 'pending';
-}
-
-export function toSelectValue(storedId: string): string {
- return storedId.trim() || SYSTEM_DEFAULT_VALUE;
-}
-
-export function toStoredMicrophoneId(value: string): string {
- return value === SYSTEM_DEFAULT_VALUE ? '' : value.trim();
-}
-
-export function isMicrophoneMissing(storedId: string, options: readonly MicrophoneOption[]): boolean {
- const id = storedId.trim();
- if (!id) return false;
- return !options.some((option) => option.deviceId === id);
-}
-
-const LEVEL_FLOOR_DB = -60;
-const SPEAKING_FLOOR_DB = -45;
-const LEVEL_SMOOTHING = 0.6;
-
-export const SPEAKING_LEVEL = (SPEAKING_FLOOR_DB - LEVEL_FLOOR_DB) / -LEVEL_FLOOR_DB;
-
-export function nextMicLevel(rms: number, previous: number): number {
- const db = rms > 0 ? 20 * Math.log10(rms) : LEVEL_FLOOR_DB;
- const normalised = Math.min(1, Math.max(0, (db - LEVEL_FLOOR_DB) / -LEVEL_FLOOR_DB));
- return previous * LEVEL_SMOOTHING + normalised * (1 - LEVEL_SMOOTHING);
-}
diff --git a/src/ui/shared/types.ts b/src/ui/shared/types.ts
new file mode 100644
index 0000000..f06e485
--- /dev/null
+++ b/src/ui/shared/types.ts
@@ -0,0 +1,6 @@
+export interface MicrophoneOption {
+ deviceId: string;
+ label: string;
+}
+
+export type MicrophoneDevice = Pick<MediaDeviceInfo, 'kind' | 'deviceId' | 'label'>;
diff --git a/src/ui/sidepanel/AiStatus.tsx b/src/ui/sidepanel/AiStatus.tsx
index ca85842..42764ca 100644
--- a/src/ui/sidepanel/AiStatus.tsx
+++ b/src/ui/sidepanel/AiStatus.tsx
@@ -1,8 +1,9 @@
import { TriangleAlert } from 'lucide-react';
import { i18n } from '#imports';
import { findProvider } from '@/core/capture/ai/models';
-import type { PanelAiUpdate } from '@/lib/port';
-import { aiActionKey, aiFailureKey } from './ai-status';
+import type { PanelAiUpdate } from '@/lib/port/types';
+import { aiActionKey } from './lib/ai-action-key';
+import { aiFailureKey } from './lib/ai-failure-key';
interface AiStatusProps {
update: PanelAiUpdate | null;
diff --git a/src/ui/sidepanel/App.tsx b/src/ui/sidepanel/App.tsx
index ab02043..8f40a3b 100644
--- a/src/ui/sidepanel/App.tsx
+++ b/src/ui/sidepanel/App.tsx
@@ -7,24 +7,24 @@ import { isRecordableUrl } from '@/capture/recordable-tabs';
import { CaptureState } from '@/core/capture/machine';
import type { GuideMeSession } from '@/core/guideme/session';
import { SESSION_KEY } from '@/core/guideme/session';
-import {
- createTab,
- focusWindow,
- getActiveTab,
- getExtensionURL,
- queryTabs,
- requestHostPermissions,
- updateTab,
-} from '@/lib/browser-api';
+import { createTab } from '@/lib/browser-api/create-tab';
+import { focusWindow } from '@/lib/browser-api/focus-window';
+import { getActiveTab } from '@/lib/browser-api/get-active-tab';
+import { getExtensionURL } from '@/lib/browser-api/get-extension-url';
+import { queryTabs } from '@/lib/browser-api/query-tabs';
+import { requestHostPermissions } from '@/lib/browser-api/request-host-permissions';
+import { updateTab } from '@/lib/browser-api/update-tab';
import { sendMessage } from '@/lib/messaging';
-import { getVoiceStatus } from '@/lib/offscreen';
-import { connectToBackground, type PanelAiUpdate, type PanelVoiceUpdate } from '@/lib/port';
+import { getVoiceStatus } from '@/lib/offscreen/get-voice-status';
+import { connectToBackground } from '@/lib/port/connect-to-background';
+import type { PanelAiUpdate, PanelVoiceUpdate } from '@/lib/port/types';
import { SettingsView } from '@/ui/shared/SettingsView';
import { UpdateNotice } from '@/ui/shared/UpdateNotice';
import { GuideEditor } from './GuideEditor';
import { GuideMeCompletion } from './GuideMeCompletion';
import { GuideMeView } from './GuideMeView';
import { LibraryView } from './LibraryView';
+import { MascotIcon } from './MascotIcon';
import { RecordingView } from './RecordingView';
import { VoiceToast } from './VoiceToast';
@@ -36,55 +36,6 @@ type View =
| { name: 'guideme'; guideId: string }
| { name: 'guideme-done'; guideId: string };
-function MascotIcon({ size = 44 }: { size?: number }) {
- return (
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" width={size} height={size}>
- <defs>
- <clipPath id="cc">
- <circle cx="100" cy="100" r="95" />
- </clipPath>
- <clipPath id="ds">
- <path d="M30 95 L170 60 L170 95 Z" />
- </clipPath>
- </defs>
- <g clipPath="url(#cc)">
- <rect x="-50" y="-50" width="300" height="300" className="fill-lavender" />
- <rect
- x="30"
- y="-80"
- width="50"
- height="400"
- className="fill-accent"
- transform="rotate(45, 100, 100)"
- opacity="0.15"
- />
- <rect x="90" y="-80" width="50" height="400" fill="#818CF8" transform="rotate(45, 100, 100)" opacity="0.12" />
- <rect x="-30" y="-80" width="50" height="400" fill="#93C5FD" transform="rotate(45, 100, 100)" opacity="0.15" />
- <rect x="150" y="-80" width="50" height="400" fill="#A5B4FC" transform="rotate(45, 100, 100)" opacity="0.1" />
- </g>
- <rect x="30" y="95" width="140" height="68" rx="5" className="fill-primary" />
- <path d="M30 95 L30 80 Q30 60, 100 60 Q170 60, 170 80 L170 95 Z" className="fill-violet-mid" />
- <path d="M30 95 L30 80 Q30 60, 100 60 Q170 60, 170 80 L170 95 Z" className="fill-accent" clipPath="url(#ds)" />
- <rect x="30" y="93" width="140" height="3" className="fill-lavender" />
- <path d="M68 122 Q76 112 84 122" className="stroke-lavender" strokeWidth="5" fill="none" strokeLinecap="round" />
- <path
- d="M116 122 Q124 112 132 122"
- className="stroke-lavender"
- strokeWidth="5"
- fill="none"
- strokeLinecap="round"
- />
- <path
- d="M84 138 Q100 148 116 138"
- className="stroke-lavender"
- strokeWidth="3.5"
- fill="none"
- strokeLinecap="round"
- />
- </svg>
- );
-}
-
export function App() {
const [isAlive, setIsAlive] = useState(false);
const [_isRecording, setIsRecording] = useState(false);
diff --git a/src/ui/sidepanel/CheckIcon.tsx b/src/ui/sidepanel/CheckIcon.tsx
new file mode 100644
index 0000000..efbaed7
--- /dev/null
+++ b/src/ui/sidepanel/CheckIcon.tsx
@@ -0,0 +1,7 @@
+export function CheckIcon() {
+ return (
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
+ <path d="M2.5 6L5 8.5L9.5 3.5" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ );
+}
diff --git a/src/ui/sidepanel/CoolMascot.tsx b/src/ui/sidepanel/CoolMascot.tsx
new file mode 100644
index 0000000..ce8b4b0
--- /dev/null
+++ b/src/ui/sidepanel/CoolMascot.tsx
@@ -0,0 +1,15 @@
+export function CoolMascot() {
+ return (
+ <svg width="120" height="100" viewBox="20 50 160 120" className="mb-6">
+ <rect x="30" y="95" width="140" height="68" rx="8" fill="#1E1B4B" />
+ <path d="M30 95 L30 80 Q30 58, 100 58 Q170 58, 170 80 L170 95 Z" fill="#3730A3" />
+ <rect x="30" y="93" width="140" height="3" fill="#C7D2FE" />
+ <rect x="60" y="112" width="28" height="16" rx="4" fill="#0F0E2A" stroke="#C7D2FE" strokeWidth="2" />
+ <rect x="112" y="112" width="28" height="16" rx="4" fill="#0F0E2A" stroke="#C7D2FE" strokeWidth="2" />
+ <line x1="88" y1="120" x2="112" y2="120" stroke="#C7D2FE" strokeWidth="2" />
+ <path d="M88 140 Q100 148 116 142" stroke="#C7D2FE" strokeWidth="3" fill="none" strokeLinecap="round" />
+ <circle cx="50" cy="68" r="4" fill="#4F46E5" />
+ <circle cx="150" cy="68" r="4" fill="#4F46E5" />
+ </svg>
+ );
+}
diff --git a/src/ui/sidepanel/ExitConfirmation.tsx b/src/ui/sidepanel/ExitConfirmation.tsx
new file mode 100644
index 0000000..8116643
--- /dev/null
+++ b/src/ui/sidepanel/ExitConfirmation.tsx
@@ -0,0 +1,28 @@
+import { i18n } from '#imports';
+import { SadMascot } from './SadMascot';
+
+export function ExitConfirmation({ onCancel, onConfirm }: { onCancel: () => void; onConfirm: () => void }) {
+ return (
+ <div className="fixed inset-0 z-20 flex items-center justify-center bg-card/80 backdrop-blur-[2px]">
+ <div className="bg-card rounded-2xl border border-border shadow-lg p-6 w-[280px] text-center flex flex-col items-center">
+ <SadMascot />
+ <h3 className="text-[15px] font-bold text-foreground mt-3 mb-1">{i18n.t('guideme.exitTitle')}</h3>
+ <p className="text-[12px] text-muted-foreground leading-relaxed mb-5">{i18n.t('guideme.exitMessage')}</p>
+ <div className="flex gap-2.5 w-full">
+ <button
+ onClick={onCancel}
+ className="flex-1 py-2.5 rounded-lg font-semibold text-sm bg-secondary text-foreground hover:bg-secondary/80 transition-colors"
+ >
+ {i18n.t('guideme.stay')}
+ </button>
+ <button
+ onClick={onConfirm}
+ className="flex-1 py-2.5 rounded-lg font-semibold text-sm bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
+ >
+ {i18n.t('guideme.exit')}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/sidepanel/GuideEditor.tsx b/src/ui/sidepanel/GuideEditor.tsx
index f9b586d..0e7fda6 100644
--- a/src/ui/sidepanel/GuideEditor.tsx
+++ b/src/ui/sidepanel/GuideEditor.tsx
@@ -8,7 +8,11 @@ import { actionSteps, isBlock, stepNumbers } from '@/core/guides/blocks';
import { getGuide, onGuidesChanged } from '@/core/guides/service';
import type { Guide, Screenshot, Step } from '@/core/guides/types';
import { dominantRatio } from '@/core/screenshot/geometry';
-import { createTab, focusWindow, getExtensionURL, queryTabs, updateTab } from '@/lib/browser-api';
+import { createTab } from '@/lib/browser-api/create-tab';
+import { focusWindow } from '@/lib/browser-api/focus-window';
+import { getExtensionURL } from '@/lib/browser-api/get-extension-url';
+import { queryTabs } from '@/lib/browser-api/query-tabs';
+import { updateTab } from '@/lib/browser-api/update-tab';
import { sendMessage } from '@/lib/messaging';
interface GuideEditorProps {
diff --git a/src/ui/sidepanel/GuideMeCompletion.tsx b/src/ui/sidepanel/GuideMeCompletion.tsx
index e816d61..65f6f4f 100644
--- a/src/ui/sidepanel/GuideMeCompletion.tsx
+++ b/src/ui/sidepanel/GuideMeCompletion.tsx
@@ -2,6 +2,8 @@ import { useEffect, useState } from 'react';
import { i18n } from '#imports';
import { getStepsForGuide } from '@/core/guides/service';
import type { Step } from '@/core/guides/types';
+import { CheckIcon } from './CheckIcon';
+import { CoolMascot } from './CoolMascot';
interface GuideMeCompletionProps {
guideId: string;
@@ -9,30 +11,6 @@ interface GuideMeCompletionProps {
onRunAgain: (guideId: string) => void;
}
-function CoolMascot() {
- return (
- <svg width="120" height="100" viewBox="20 50 160 120" className="mb-6">
- <rect x="30" y="95" width="140" height="68" rx="8" fill="#1E1B4B" />
- <path d="M30 95 L30 80 Q30 58, 100 58 Q170 58, 170 80 L170 95 Z" fill="#3730A3" />
- <rect x="30" y="93" width="140" height="3" fill="#C7D2FE" />
- <rect x="60" y="112" width="28" height="16" rx="4" fill="#0F0E2A" stroke="#C7D2FE" strokeWidth="2" />
- <rect x="112" y="112" width="28" height="16" rx="4" fill="#0F0E2A" stroke="#C7D2FE" strokeWidth="2" />
- <line x1="88" y1="120" x2="112" y2="120" stroke="#C7D2FE" strokeWidth="2" />
- <path d="M88 140 Q100 148 116 142" stroke="#C7D2FE" strokeWidth="3" fill="none" strokeLinecap="round" />
- <circle cx="50" cy="68" r="4" fill="#4F46E5" />
- <circle cx="150" cy="68" r="4" fill="#4F46E5" />
- </svg>
- );
-}
-
-function CheckIcon() {
- return (
- <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
- <path d="M2.5 6L5 8.5L9.5 3.5" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
- </svg>
- );
-}
-
export function GuideMeCompletion({ guideId, onDone, onRunAgain }: GuideMeCompletionProps) {
const [steps, setSteps] = useState<Step[]>([]);
diff --git a/src/ui/sidepanel/GuideMeView.tsx b/src/ui/sidepanel/GuideMeView.tsx
index 03be4a2..2765877 100644
--- a/src/ui/sidepanel/GuideMeView.tsx
+++ b/src/ui/sidepanel/GuideMeView.tsx
@@ -10,6 +10,7 @@ import { actionSteps } from '@/core/guides/blocks';
import { getGuide } from '@/core/guides/service';
import type { Guide, Screenshot, Step } from '@/core/guides/types';
import { sendMessage } from '@/lib/messaging';
+import { ExitConfirmation } from './ExitConfirmation';
interface GuideMeViewProps {
guideId: string;
@@ -23,47 +24,6 @@ interface GuideData {
screenshots: Map<string, Screenshot>;
}
-function SadMascot() {
- return (
- <svg width="64" height="54" viewBox="20 55 160 108">
- <rect x="30" y="95" width="140" height="68" rx="8" fill="#1E1B4B" />
- <path d="M30 95 L30 80 Q30 58, 100 58 Q170 58, 170 80 L170 95 Z" fill="#3730A3" />
- <rect x="30" y="93" width="140" height="3" fill="#C7D2FE" />
- <circle cx="74" cy="118" r="10" fill="#0F0E2A" />
- <circle cx="126" cy="118" r="10" fill="#0F0E2A" />
- <circle cx="74" cy="120" r="6" fill="#C7D2FE" />
- <circle cx="126" cy="120" r="6" fill="#C7D2FE" />
- <path d="M88 146 Q100 138 112 146" stroke="#C7D2FE" strokeWidth="2.5" fill="none" strokeLinecap="round" />
- </svg>
- );
-}
-
-function ExitConfirmation({ onCancel, onConfirm }: { onCancel: () => void; onConfirm: () => void }) {
- return (
- <div className="fixed inset-0 z-20 flex items-center justify-center bg-card/80 backdrop-blur-[2px]">
- <div className="bg-card rounded-2xl border border-border shadow-lg p-6 w-[280px] text-center flex flex-col items-center">
- <SadMascot />
- <h3 className="text-[15px] font-bold text-foreground mt-3 mb-1">{i18n.t('guideme.exitTitle')}</h3>
- <p className="text-[12px] text-muted-foreground leading-relaxed mb-5">{i18n.t('guideme.exitMessage')}</p>
- <div className="flex gap-2.5 w-full">
- <button
- onClick={onCancel}
- className="flex-1 py-2.5 rounded-lg font-semibold text-sm bg-secondary text-foreground hover:bg-secondary/80 transition-colors"
- >
- {i18n.t('guideme.stay')}
- </button>
- <button
- onClick={onConfirm}
- className="flex-1 py-2.5 rounded-lg font-semibold text-sm bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
- >
- {i18n.t('guideme.exit')}
- </button>
- </div>
- </div>
- </div>
- );
-}
-
export function GuideMeView({ guideId, onExit, onComplete }: GuideMeViewProps) {
const [data, setData] = useState<GuideData | null>(null);
const [loading, setLoading] = useState(true);
diff --git a/src/ui/sidepanel/MascotIcon.tsx b/src/ui/sidepanel/MascotIcon.tsx
new file mode 100644
index 0000000..1804696
--- /dev/null
+++ b/src/ui/sidepanel/MascotIcon.tsx
@@ -0,0 +1,48 @@
+export function MascotIcon({ size = 44 }: { size?: number }) {
+ return (
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" width={size} height={size}>
+ <defs>
+ <clipPath id="cc">
+ <circle cx="100" cy="100" r="95" />
+ </clipPath>
+ <clipPath id="ds">
+ <path d="M30 95 L170 60 L170 95 Z" />
+ </clipPath>
+ </defs>
+ <g clipPath="url(#cc)">
+ <rect x="-50" y="-50" width="300" height="300" className="fill-lavender" />
+ <rect
+ x="30"
+ y="-80"
+ width="50"
+ height="400"
+ className="fill-accent"
+ transform="rotate(45, 100, 100)"
+ opacity="0.15"
+ />
+ <rect x="90" y="-80" width="50" height="400" fill="#818CF8" transform="rotate(45, 100, 100)" opacity="0.12" />
+ <rect x="-30" y="-80" width="50" height="400" fill="#93C5FD" transform="rotate(45, 100, 100)" opacity="0.15" />
+ <rect x="150" y="-80" width="50" height="400" fill="#A5B4FC" transform="rotate(45, 100, 100)" opacity="0.1" />
+ </g>
+ <rect x="30" y="95" width="140" height="68" rx="5" className="fill-primary" />
+ <path d="M30 95 L30 80 Q30 60, 100 60 Q170 60, 170 80 L170 95 Z" className="fill-violet-mid" />
+ <path d="M30 95 L30 80 Q30 60, 100 60 Q170 60, 170 80 L170 95 Z" className="fill-accent" clipPath="url(#ds)" />
+ <rect x="30" y="93" width="140" height="3" className="fill-lavender" />
+ <path d="M68 122 Q76 112 84 122" className="stroke-lavender" strokeWidth="5" fill="none" strokeLinecap="round" />
+ <path
+ d="M116 122 Q124 112 132 122"
+ className="stroke-lavender"
+ strokeWidth="5"
+ fill="none"
+ strokeLinecap="round"
+ />
+ <path
+ d="M84 138 Q100 148 116 138"
+ className="stroke-lavender"
+ strokeWidth="3.5"
+ fill="none"
+ strokeLinecap="round"
+ />
+ </svg>
+ );
+}
diff --git a/src/ui/sidepanel/MicMeter.tsx b/src/ui/sidepanel/MicMeter.tsx
index 8bb0830..44622e4 100644
--- a/src/ui/sidepanel/MicMeter.tsx
+++ b/src/ui/sidepanel/MicMeter.tsx
@@ -1,15 +1,10 @@
import { useEffect, useRef, useState } from 'react';
import { browser, i18n } from '#imports';
-import { isVoiceMessageFor, VOICE_SIDEPANEL_TARGET, type VoiceLevelEvent, VoiceMessage } from '@/lib/voice-messages';
-import {
- LEVEL_STALE_MS,
- MIC_BAR_MIN_SCALE,
- MIC_BARS,
- type MicActivity,
- micActivity,
- micActivityKey,
- micBarScale,
-} from './voice-status';
+import { isVoiceMessageFor } from '@/lib/voice/is-voice-message-for';
+import { VOICE_SIDEPANEL_TARGET, type VoiceLevelEvent, VoiceMessage } from '@/lib/voice/voice-message';
+import { LEVEL_STALE_MS, type MicActivity, micActivity } from './lib/mic-activity';
+import { micActivityKey } from './lib/mic-activity-key';
+import { MIC_BAR_MIN_SCALE, MIC_BARS, micBarScale } from './lib/mic-bar-scale';
const SWEEP_MS = 300;
diff --git a/src/ui/sidepanel/MicToggle.tsx b/src/ui/sidepanel/MicToggle.tsx
index c204ce8..fc37b55 100644
--- a/src/ui/sidepanel/MicToggle.tsx
+++ b/src/ui/sidepanel/MicToggle.tsx
@@ -4,9 +4,12 @@ import { Mic, MicOff } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { browser, i18n } from '#imports';
import { hasVoiceApiKey, VOICE_KEY_SETTINGS } from '@/core/capture/voice/api-key';
-import { getActiveTab, localStorage } from '@/lib/browser-api';
+import { getActiveTab } from '@/lib/browser-api/get-active-tab';
+import { localStorage } from '@/lib/browser-api/local-storage';
import { sendMessage } from '@/lib/messaging';
-import { abortVoiceCapture, openMicPermissionPage } from '@/lib/offscreen';
+import { abortVoiceCapture } from '@/lib/offscreen/abort-voice-capture';
+import { openMicPermissionPage } from '@/lib/offscreen/open-mic-permission-page';
+import { microphoneGranted } from './lib/microphone-granted';
interface MicToggleProps {
enabled: boolean;
@@ -14,17 +17,6 @@ interface MicToggleProps {
onChange: (enabled: boolean) => void;
}
-const MICROPHONE: PermissionDescriptor = { name: 'microphone' as PermissionName };
-
-async function microphoneGranted(): Promise<boolean> {
- try {
- const status = await navigator.permissions.query(MICROPHONE);
- return status.state === 'granted';
- } catch {
- return false;
- }
-}
-
export function MicToggle({ enabled, live, onChange }: MicToggleProps) {
const [keyed, setKeyed] = useState(false);
diff --git a/src/ui/sidepanel/RecordingView.tsx b/src/ui/sidepanel/RecordingView.tsx
index 8ca48d7..552e921 100644
--- a/src/ui/sidepanel/RecordingView.tsx
+++ b/src/ui/sidepanel/RecordingView.tsx
@@ -5,10 +5,12 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { browser, i18n } from '#imports';
import { deleteStep, getScreenshotsForSteps, getStepsForGuide } from '@/core/guides/service';
import type { Screenshot, Step } from '@/core/guides/types';
-import { getActiveTab, localStorage } from '@/lib/browser-api';
+import { getActiveTab } from '@/lib/browser-api/get-active-tab';
+import { localStorage } from '@/lib/browser-api/local-storage';
import { sendMessage } from '@/lib/messaging';
-import type { PanelAiUpdate, PanelVoiceUpdate } from '@/lib/port';
+import type { PanelAiUpdate, PanelVoiceUpdate } from '@/lib/port/types';
import { AiStatus } from './AiStatus';
+import { timeAgo } from './lib/time-ago';
import { MicToggle } from './MicToggle';
import { VoiceStatus } from './VoiceStatus';
@@ -19,13 +21,6 @@ interface RecordingViewProps {
aiFailure: PanelAiUpdate | null;
}
-function timeAgo(createdAt: number): string {
- const diff = Math.floor((Date.now() - createdAt) / 1000);
- if (diff < 3) return i18n.t('recording.justNow');
- if (diff < 60) return i18n.t('recording.secondsAgo', [String(diff)]);
- return i18n.t('recording.minutesAgo', [String(Math.floor(diff / 60))]);
-}
-
interface LiveStep {
step: Step;
screenshot?: Screenshot;
diff --git a/src/ui/sidepanel/SadMascot.tsx b/src/ui/sidepanel/SadMascot.tsx
new file mode 100644
index 0000000..11afa97
--- /dev/null
+++ b/src/ui/sidepanel/SadMascot.tsx
@@ -0,0 +1,14 @@
+export function SadMascot() {
+ return (
+ <svg width="64" height="54" viewBox="20 55 160 108">
+ <rect x="30" y="95" width="140" height="68" rx="8" fill="#1E1B4B" />
+ <path d="M30 95 L30 80 Q30 58, 100 58 Q170 58, 170 80 L170 95 Z" fill="#3730A3" />
+ <rect x="30" y="93" width="140" height="3" fill="#C7D2FE" />
+ <circle cx="74" cy="118" r="10" fill="#0F0E2A" />
+ <circle cx="126" cy="118" r="10" fill="#0F0E2A" />
+ <circle cx="74" cy="120" r="6" fill="#C7D2FE" />
+ <circle cx="126" cy="120" r="6" fill="#C7D2FE" />
+ <path d="M88 146 Q100 138 112 146" stroke="#C7D2FE" strokeWidth="2.5" fill="none" strokeLinecap="round" />
+ </svg>
+ );
+}
diff --git a/src/ui/sidepanel/VoiceStatus.tsx b/src/ui/sidepanel/VoiceStatus.tsx
index b869fd8..3df0561 100644
--- a/src/ui/sidepanel/VoiceStatus.tsx
+++ b/src/ui/sidepanel/VoiceStatus.tsx
@@ -1,8 +1,8 @@
import { TriangleAlert } from 'lucide-react';
import { i18n } from '#imports';
-import type { PanelVoiceUpdate } from '@/lib/port';
+import type { PanelVoiceUpdate } from '@/lib/port/types';
+import { voiceErrorKey } from './lib/voice-error-key';
import { MicMeter } from './MicMeter';
-import { voiceErrorKey } from './voice-status';
interface VoiceStatusProps {
update: PanelVoiceUpdate;
diff --git a/src/ui/sidepanel/VoiceToast.tsx b/src/ui/sidepanel/VoiceToast.tsx
index cee2118..81b1fce 100644
--- a/src/ui/sidepanel/VoiceToast.tsx
+++ b/src/ui/sidepanel/VoiceToast.tsx
@@ -2,8 +2,10 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@mimik/ui';
import { Check, Loader2, TriangleAlert, X } from 'lucide-react';
import { useEffect, useState } from 'react';
import { i18n } from '#imports';
-import type { PanelVoiceUpdate } from '@/lib/port';
-import { narratedKey, voiceErrorKey } from './voice-status';
+import type { PanelVoiceUpdate } from '@/lib/port/types';
+import { voiceSignature } from '@/ui/fullview/lib/voice-signature';
+import { narratedKey } from './lib/narrated-key';
+import { voiceErrorKey } from './lib/voice-error-key';
const CONFIRM_MS = 7000;
@@ -13,13 +15,9 @@ interface VoiceToastProps {
onOpenSettings: () => void;
}
-function signatureOf(update: PanelVoiceUpdate): string {
- return `${update.phase}:${update.reason ?? ''}:${update.narrated ?? ''}`;
-}
-
export function VoiceToast({ update, confirmable, onOpenSettings }: VoiceToastProps) {
const [dismissed, setDismissed] = useState<string | null>(null);
- const signature = signatureOf(update);
+ const signature = voiceSignature(update);
const confirming = update.phase === 'idle' && update.narrated !== undefined && confirmable;
useEffect(() => {
diff --git a/src/ui/sidepanel/__tests__/voice-status.test.ts b/src/ui/sidepanel/__tests__/voice-status.test.ts
index efb12ee..69523a6 100644
--- a/src/ui/sidepanel/__tests__/voice-status.test.ts
+++ b/src/ui/sidepanel/__tests__/voice-status.test.ts
@@ -1,19 +1,12 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
-import type { VoiceErrorReason } from '@/lib/voice-messages';
-import {
- LEVEL_STALE_MS,
- MIC_ACTIVITIES,
- MIC_BAR_MIN_SCALE,
- MIC_BARS,
- micActivity,
- micActivityKey,
- micBarScale,
- narratedKey,
- SPEAKING_HOLD_MS,
- voiceErrorKey,
-} from '../voice-status';
+import type { VoiceErrorReason } from '@/lib/voice/voice-message';
+import { LEVEL_STALE_MS, MIC_ACTIVITIES, micActivity, SPEAKING_HOLD_MS } from '../lib/mic-activity';
+import { micActivityKey } from '../lib/mic-activity-key';
+import { MIC_BAR_MIN_SCALE, MIC_BARS, micBarScale } from '../lib/mic-bar-scale';
+import { narratedKey } from '../lib/narrated-key';
+import { voiceErrorKey } from '../lib/voice-error-key';
const LOCALES = ['en', 'es', 'fr', 'pt-BR', 'zh-CN'];
diff --git a/src/ui/sidepanel/ai-status.ts b/src/ui/sidepanel/lib/ai-action-key.ts
similarity index 54%
rename from src/ui/sidepanel/ai-status.ts
rename to src/ui/sidepanel/lib/ai-action-key.ts
index 6cedc5f..33c2440 100644
--- a/src/ui/sidepanel/ai-status.ts
+++ b/src/ui/sidepanel/lib/ai-action-key.ts
@@ -1,15 +1,5 @@
import type { AiFailureReason } from '@/core/capture/ai/errors';
-const AI_FAILURE_KEYS: Record<AiFailureReason, string> = {
- rejected: 'aiStatus.rejected',
- 'no-credits': 'aiStatus.noCredits',
- 'rate-limited': 'aiStatus.rateLimited',
- 'model-invalid': 'aiStatus.modelInvalid',
- quota: 'aiStatus.quota',
- network: 'aiStatus.network',
- unknown: 'aiStatus.unknown',
-};
-
const AI_ACTION_KEYS: Record<AiFailureReason, string> = {
rejected: 'aiStatus.actionCheckKey',
'no-credits': 'aiStatus.actionAddCredits',
@@ -20,11 +10,6 @@ const AI_ACTION_KEYS: Record<AiFailureReason, string> = {
unknown: 'aiStatus.actionCheckKey',
};
-export function aiFailureKey(reason: AiFailureReason | undefined): string {
- const key = reason === undefined ? undefined : AI_FAILURE_KEYS[reason];
- return key ?? AI_FAILURE_KEYS.unknown;
-}
-
export function aiActionKey(reason: AiFailureReason | undefined): string {
const key = reason === undefined ? undefined : AI_ACTION_KEYS[reason];
return key ?? AI_ACTION_KEYS.unknown;
diff --git a/src/ui/sidepanel/lib/ai-failure-key.ts b/src/ui/sidepanel/lib/ai-failure-key.ts
new file mode 100644
index 0000000..71a3a18
--- /dev/null
+++ b/src/ui/sidepanel/lib/ai-failure-key.ts
@@ -0,0 +1,16 @@
+import type { AiFailureReason } from '@/core/capture/ai/errors';
+
+const AI_FAILURE_KEYS: Record<AiFailureReason, string> = {
+ rejected: 'aiStatus.rejected',
+ 'no-credits': 'aiStatus.noCredits',
+ 'rate-limited': 'aiStatus.rateLimited',
+ 'model-invalid': 'aiStatus.modelInvalid',
+ quota: 'aiStatus.quota',
+ network: 'aiStatus.network',
+ unknown: 'aiStatus.unknown',
+};
+
+export function aiFailureKey(reason: AiFailureReason | undefined): string {
+ const key = reason === undefined ? undefined : AI_FAILURE_KEYS[reason];
+ return key ?? AI_FAILURE_KEYS.unknown;
+}
diff --git a/src/ui/sidepanel/lib/mic-activity-key.ts b/src/ui/sidepanel/lib/mic-activity-key.ts
new file mode 100644
index 0000000..4ec1871
--- /dev/null
+++ b/src/ui/sidepanel/lib/mic-activity-key.ts
@@ -0,0 +1,11 @@
+import type { MicActivity } from './mic-activity';
+
+const MIC_ACTIVITY_KEYS: Record<MicActivity, string> = {
+ waiting: 'voice.micStarting',
+ speaking: 'voice.micHearing',
+ quiet: 'voice.micQuiet',
+};
+
+export function micActivityKey(activity: MicActivity): string {
+ return MIC_ACTIVITY_KEYS[activity];
+}
diff --git a/src/ui/sidepanel/lib/mic-activity.ts b/src/ui/sidepanel/lib/mic-activity.ts
new file mode 100644
index 0000000..3f7f4c2
--- /dev/null
+++ b/src/ui/sidepanel/lib/mic-activity.ts
@@ -0,0 +1,12 @@
+export const SPEAKING_HOLD_MS = 1200;
+export const LEVEL_STALE_MS = 1500;
+
+export type MicActivity = 'waiting' | 'speaking' | 'quiet';
+
+export const MIC_ACTIVITIES: MicActivity[] = ['waiting', 'speaking', 'quiet'];
+
+export function micActivity(levelAt: number | null, speakingAt: number | null, now: number): MicActivity {
+ if (levelAt === null) return 'waiting';
+ if (speakingAt !== null && now - speakingAt <= SPEAKING_HOLD_MS) return 'speaking';
+ return 'quiet';
+}
diff --git a/src/ui/sidepanel/lib/mic-bar-scale.ts b/src/ui/sidepanel/lib/mic-bar-scale.ts
new file mode 100644
index 0000000..92357bf
--- /dev/null
+++ b/src/ui/sidepanel/lib/mic-bar-scale.ts
@@ -0,0 +1,19 @@
+export const MIC_BAR_MIN_SCALE = 0.14;
+
+export interface MicBar {
+ id: string;
+ weight: number;
+}
+
+export const MIC_BARS: MicBar[] = [
+ { id: 'far-left', weight: 0.45 },
+ { id: 'left', weight: 0.75 },
+ { id: 'center', weight: 1 },
+ { id: 'right', weight: 0.75 },
+ { id: 'far-right', weight: 0.45 },
+];
+
+export function micBarScale(level: number, weight: number): number {
+ const bounded = Number.isFinite(level) ? Math.min(1, Math.max(0, level)) : 0;
+ return MIC_BAR_MIN_SCALE + (1 - MIC_BAR_MIN_SCALE) * bounded * weight;
+}
diff --git a/src/ui/sidepanel/lib/microphone-granted.ts b/src/ui/sidepanel/lib/microphone-granted.ts
new file mode 100644
index 0000000..376764a
--- /dev/null
+++ b/src/ui/sidepanel/lib/microphone-granted.ts
@@ -0,0 +1,10 @@
+const MICROPHONE: PermissionDescriptor = { name: 'microphone' as PermissionName };
+
+export async function microphoneGranted(): Promise<boolean> {
+ try {
+ const status = await navigator.permissions.query(MICROPHONE);
+ return status.state === 'granted';
+ } catch {
+ return false;
+ }
+}
diff --git a/src/ui/sidepanel/lib/narrated-key.ts b/src/ui/sidepanel/lib/narrated-key.ts
new file mode 100644
index 0000000..62941d6
--- /dev/null
+++ b/src/ui/sidepanel/lib/narrated-key.ts
@@ -0,0 +1,4 @@
+export function narratedKey(narrated: number): string {
+ if (narrated <= 0) return 'voice.narratedNone';
+ return narrated === 1 ? 'voice.narrated' : 'voice.narratedPlural';
+}
diff --git a/src/ui/sidepanel/lib/time-ago.ts b/src/ui/sidepanel/lib/time-ago.ts
new file mode 100644
index 0000000..2a66612
--- /dev/null
+++ b/src/ui/sidepanel/lib/time-ago.ts
@@ -0,0 +1,8 @@
+import { i18n } from '#imports';
+
+export function timeAgo(createdAt: number): string {
+ const diff = Math.floor((Date.now() - createdAt) / 1000);
+ if (diff < 3) return i18n.t('recording.justNow');
+ if (diff < 60) return i18n.t('recording.secondsAgo', [String(diff)]);
+ return i18n.t('recording.minutesAgo', [String(Math.floor(diff / 60))]);
+}
diff --git a/src/ui/sidepanel/lib/voice-error-key.ts b/src/ui/sidepanel/lib/voice-error-key.ts
new file mode 100644
index 0000000..4384afa
--- /dev/null
+++ b/src/ui/sidepanel/lib/voice-error-key.ts
@@ -0,0 +1,18 @@
+import type { VoiceErrorReason } from '@/lib/voice/voice-message';
+
+const VOICE_ERROR_KEYS: Record<VoiceErrorReason, string> = {
+ 'permission-denied': 'voice.errorPermissionDenied',
+ 'no-device': 'voice.errorNoDevice',
+ 'no-audio': 'voice.errorNoAudio',
+ 'missing-api-key': 'voice.errorMissingApiKey',
+ 'stream-ended': 'voice.errorStreamEnded',
+ 'not-recording': 'voice.errorNotRecording',
+ 'already-recording': 'voice.errorAlreadyRecording',
+ unsupported: 'voice.errorUnsupported',
+ unknown: 'voice.errorUnknown',
+};
+
+export function voiceErrorKey(reason: VoiceErrorReason | undefined): string {
+ const key = reason === undefined ? undefined : VOICE_ERROR_KEYS[reason];
+ return key ?? VOICE_ERROR_KEYS.unknown;
+}
diff --git a/src/ui/sidepanel/voice-status.ts b/src/ui/sidepanel/voice-status.ts
deleted file mode 100644
index 2974e37..0000000
--- a/src/ui/sidepanel/voice-status.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import type { VoiceErrorReason } from '@/lib/voice-messages';
-
-export const SPEAKING_HOLD_MS = 1200;
-export const LEVEL_STALE_MS = 1500;
-export const MIC_BAR_MIN_SCALE = 0.14;
-
-export interface MicBar {
- id: string;
- weight: number;
-}
-
-export const MIC_BARS: MicBar[] = [
- { id: 'far-left', weight: 0.45 },
- { id: 'left', weight: 0.75 },
- { id: 'center', weight: 1 },
- { id: 'right', weight: 0.75 },
- { id: 'far-right', weight: 0.45 },
-];
-
-export type MicActivity = 'waiting' | 'speaking' | 'quiet';
-
-export const MIC_ACTIVITIES: MicActivity[] = ['waiting', 'speaking', 'quiet'];
-
-const MIC_ACTIVITY_KEYS: Record<MicActivity, string> = {
- waiting: 'voice.micStarting',
- speaking: 'voice.micHearing',
- quiet: 'voice.micQuiet',
-};
-
-export function micActivityKey(activity: MicActivity): string {
- return MIC_ACTIVITY_KEYS[activity];
-}
-
-export function micActivity(levelAt: number | null, speakingAt: number | null, now: number): MicActivity {
- if (levelAt === null) return 'waiting';
- if (speakingAt !== null && now - speakingAt <= SPEAKING_HOLD_MS) return 'speaking';
- return 'quiet';
-}
-
-export function micBarScale(level: number, weight: number): number {
- const bounded = Number.isFinite(level) ? Math.min(1, Math.max(0, level)) : 0;
- return MIC_BAR_MIN_SCALE + (1 - MIC_BAR_MIN_SCALE) * bounded * weight;
-}
-
-const VOICE_ERROR_KEYS: Record<VoiceErrorReason, string> = {
- 'permission-denied': 'voice.errorPermissionDenied',
- 'no-device': 'voice.errorNoDevice',
- 'no-audio': 'voice.errorNoAudio',
- 'missing-api-key': 'voice.errorMissingApiKey',
- 'stream-ended': 'voice.errorStreamEnded',
- 'not-recording': 'voice.errorNotRecording',
- 'already-recording': 'voice.errorAlreadyRecording',
- unsupported: 'voice.errorUnsupported',
- unknown: 'voice.errorUnknown',
-};
-
-export function voiceErrorKey(reason: VoiceErrorReason | undefined): string {
- const key = reason === undefined ? undefined : VOICE_ERROR_KEYS[reason];
- return key ?? VOICE_ERROR_KEYS.unknown;
-}
-
-export function narratedKey(narrated: number): string {
- if (narrated <= 0) return 'voice.narratedNone';
- return narrated === 1 ? 'voice.narrated' : 'voice.narratedPlural';
-}