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

feat(fullview): explain narration updates while transcription runs

Luis Ortiz1565d86e842d
diff --git a/src/lib/__tests__/port.test.ts b/src/lib/__tests__/port.test.ts
new file mode 100644
index 0000000..e17518e
--- /dev/null
+++ b/src/lib/__tests__/port.test.ts
@@ -0,0 +1,149 @@
+import { beforeEach, describe, expect, it, type Mock, vi } from 'vitest';
+import type { PanelStateUpdate, PanelVoiceUpdate } from '../port';
+
+type PanelMessage = PanelStateUpdate | PanelVoiceUpdate;
+
+class FakePort {
+ received: PanelMessage[] = [];
+ broken = false;
+ private disconnectHandlers: Array<() => void> = [];
+
+ constructor(public name: string) {}
+
+ onMessage = { addListener: () => {} };
+
+ onDisconnect = {
+ addListener: (handler: () => void) => {
+ this.disconnectHandlers.push(handler);
+ },
+ };
+
+ postMessage(message: PanelMessage) {
+ if (this.broken) throw new Error('port is gone');
+ this.received.push(message);
+ }
+
+ disconnect() {
+ for (const handler of this.disconnectHandlers) handler();
+ }
+}
+
+const STATE: PanelStateUpdate = { type: 'STATE_UPDATE', state: 'IDLE', stepCount: 0, currentGuideId: null };
+const TRANSCRIBING: PanelVoiceUpdate = { type: 'VOICE_UPDATE', phase: 'transcribing' };
+const DONE: PanelVoiceUpdate = { type: 'VOICE_UPDATE', phase: 'idle', narrated: 3 };
+
+const connectListeners: Array<(port: FakePort) => void> = [];
+
+let port: typeof import('../port');
+let onPanelConnect: Mock<(port: unknown) => void>;
+
+async function loadBackground() {
+ connectListeners.length = 0;
+ vi.resetModules();
+
+ const { fakeBrowser } = await import('wxt/testing');
+ const onConnect = fakeBrowser.runtime.onConnect as unknown as {
+ addListener: (handler: (port: FakePort) => void) => void;
+ };
+ onConnect.addListener = (handler) => {
+ connectListeners.push(handler);
+ };
+
+ port = await import('../port');
+ onPanelConnect = vi.fn<(port: unknown) => void>();
+ port.setupPortListener(onPanelConnect);
+}
+
+function connect(name: string): FakePort {
+ const fake = new FakePort(name);
+ for (const listener of connectListeners) listener(fake);
+ return fake;
+}
+
+beforeEach(loadBackground);
+
+describe('observer ports', () => {
+ it('follow narration without being handed the capture state feed', () => {
+ const observer = connect('mimik-panel-observer');
+
+ port.broadcastStateToPanel(STATE);
+ port.broadcastVoiceToPanel(TRANSCRIBING);
+
+ expect(observer.received).toEqual([TRANSCRIBING]);
+ });
+
+ it('stay out of the side panel lifecycle that cancels a Guide Me run', () => {
+ connect('mimik-panel-observer');
+ expect(onPanelConnect).not.toHaveBeenCalled();
+
+ connect('mimik-panel');
+ expect(onPanelConnect).toHaveBeenCalledTimes(1);
+ });
+
+ it('are caught up on the narration already in flight when they arrive late', () => {
+ port.broadcastVoiceToPanel(TRANSCRIBING);
+ const observer = connect('mimik-panel-observer');
+
+ expect(observer.received).toEqual([TRANSCRIBING]);
+ });
+
+ it('hear nothing on arrival when no narration has been reported yet', () => {
+ expect(connect('mimik-panel-observer').received).toEqual([]);
+ });
+
+ it('are replayed only the latest phase, not the whole history', () => {
+ port.broadcastVoiceToPanel(TRANSCRIBING);
+ port.broadcastVoiceToPanel(DONE);
+
+ expect(connect('mimik-panel-observer').received).toEqual([DONE]);
+ });
+
+ it('stop receiving once they disconnect', () => {
+ const observer = connect('mimik-panel-observer');
+ observer.disconnect();
+
+ port.broadcastVoiceToPanel(TRANSCRIBING);
+
+ expect(observer.received).toEqual([]);
+ });
+
+ it('are dropped when posting to them throws', () => {
+ const observer = connect('mimik-panel-observer');
+ observer.broken = true;
+ port.broadcastVoiceToPanel(TRANSCRIBING);
+
+ observer.broken = false;
+ port.broadcastVoiceToPanel(DONE);
+
+ expect(observer.received).toEqual([]);
+ });
+});
+
+describe('panel ports', () => {
+ it('keep receiving both feeds', () => {
+ const panel = connect('mimik-panel');
+
+ port.broadcastStateToPanel(STATE);
+ port.broadcastVoiceToPanel(TRANSCRIBING);
+
+ expect(panel.received).toEqual([STATE, TRANSCRIBING]);
+ });
+
+ it('are not replayed to on connect, since the background greets them itself', () => {
+ port.broadcastVoiceToPanel(TRANSCRIBING);
+
+ expect(connect('mimik-panel').received).toEqual([]);
+ });
+});
+
+describe('unknown ports', () => {
+ it('are ignored entirely', () => {
+ const stranger = connect('something-else');
+
+ port.broadcastStateToPanel(STATE);
+ port.broadcastVoiceToPanel(TRANSCRIBING);
+
+ expect(stranger.received).toEqual([]);
+ expect(onPanelConnect).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/lib/port.ts b/src/lib/port.ts
index a5e8460..2c2c57a 100644
--- a/src/lib/port.ts
+++ b/src/lib/port.ts
@@ -4,6 +4,7 @@ import { logger } from '@/lib/logger';
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';
@@ -23,37 +24,32 @@ export interface PanelVoiceUpdate {
}
type PortMessage = PanelStateUpdate | PanelVoiceUpdate;
-
-export function connectToBackground(callbacks: {
- onStateUpdate: (update: PanelStateUpdate) => void;
- onConnect: () => void;
- onDisconnect: () => void;
- onVoiceUpdate?: (update: PanelVoiceUpdate) => void;
-}): () => void {
- let port: ReturnType<typeof browser.runtime.connect> | null = null;
+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: PORT_NAME });
- logger.debug('Port connected to background');
- callbacks.onConnect();
-
- port.onMessage.addListener((msg: PortMessage) => {
- if (msg.type === 'STATE_UPDATE') {
- callbacks.onStateUpdate(msg);
- } else if (msg.type === 'VOICE_UPDATE') {
- callbacks.onVoiceUpdate?.(msg);
- }
- });
+ 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...');
- callbacks.onDisconnect();
+ onDisconnect?.();
setTimeout(connect, 1000);
}
});
@@ -74,35 +70,86 @@ export function connectToBackground(callbacks: {
};
}
-const connectedPorts = new Set<ReturnType<typeof browser.runtime.connect>>();
+export function connectToBackground(callbacks: {
+ onStateUpdate: (update: PanelStateUpdate) => void;
+ onConnect: () => void;
+ onDisconnect: () => void;
+ onVoiceUpdate?: (update: PanelVoiceUpdate) => void;
+}): () => void {
+ return openPort(
+ PORT_NAME,
+ (msg) => {
+ if (msg.type === 'STATE_UPDATE') {
+ callbacks.onStateUpdate(msg);
+ } else if (msg.type === 'VOICE_UPDATE') {
+ callbacks.onVoiceUpdate?.(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,
+ );
+}
-export function setupPortListener(onPanelConnect?: (port: ReturnType<typeof browser.runtime.connect>) => void) {
+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;
- connectedPorts.add(port);
+ panelPorts.add(port);
onPanelConnect?.(port);
port.onDisconnect.addListener(() => {
- connectedPorts.delete(port);
+ panelPorts.delete(port);
});
});
}
-function broadcastToPanel(message: PortMessage): void {
- for (const port of connectedPorts) {
- try {
- port.postMessage(message);
- } catch {
- connectedPorts.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 {
- broadcastToPanel(update);
+ broadcastTo(panelPorts, update);
}
export function broadcastVoiceToPanel(update: PanelVoiceUpdate): void {
- broadcastToPanel(update);
+ lastVoiceUpdate = update;
+ broadcastTo(panelPorts, update);
+ broadcastTo(observerPorts, update);
}
diff --git a/src/ui/fullview/App.tsx b/src/ui/fullview/App.tsx
index 787cfca..76093e3 100644
--- a/src/ui/fullview/App.tsx
+++ b/src/ui/fullview/App.tsx
@@ -1,5 +1,6 @@
import { useEffect } from 'react';
import { useFullview } from '@/stores/fullview';
+import VoiceNotice from './components/VoiceNotice';
import GuideContent from './GuideContent';
import LibraryContent from './LibraryContent';
import { useRoute } from './router';
@@ -39,6 +40,8 @@ export default function FullViewApp() {
</div>
</main>
)}
+
+ {import.meta.env.BROWSER !== 'firefox' && <VoiceNotice />}
</div>
);
}
diff --git a/src/ui/fullview/__tests__/voice-notice.test.ts b/src/ui/fullview/__tests__/voice-notice.test.ts
new file mode 100644
index 0000000..a5879ee
--- /dev/null
+++ b/src/ui/fullview/__tests__/voice-notice.test.ts
@@ -0,0 +1,135 @@
+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';
+
+const LOCALES = ['en', 'es', 'fr', 'pt-BR'];
+
+function update(phase: VoicePhase, extra: Partial<PanelVoiceUpdate> = {}): PanelVoiceUpdate {
+ return { type: 'VOICE_UPDATE', phase, ...extra };
+}
+
+function localeKeys(locale: string): Set<string> {
+ const keys = new Set<string>();
+ let section = '';
+ for (const line of readFileSync(join(process.cwd(), 'src/locales', `${locale}.yml`), 'utf8').split('\n')) {
+ const top = /^([\w-]+):/.exec(line);
+ if (top) {
+ section = top[1];
+ continue;
+ }
+ const nested = /^ {2}([\w-]+):/.exec(line);
+ if (nested && section) keys.add(`${section}.${nested[1]}`);
+ }
+ return keys;
+}
+
+describe('voiceNotice', () => {
+ it('explains that descriptions are still being written while transcription runs', () => {
+ const notice = voiceNotice(update('transcribing'), true);
+ expect(notice).toMatchObject({
+ tone: 'progress',
+ titleKey: 'voice.transcribing',
+ bodyKey: 'voice.transcribingHint',
+ autoDismissMs: null,
+ });
+ });
+
+ it('announces transcription even before any live phase has been seen', () => {
+ expect(voiceNotice(update('transcribing'), false)?.tone).toBe('progress');
+ });
+
+ it('says nothing while a recording is in progress', () => {
+ expect(voiceNotice(update('recording'), true)).toBeNull();
+ });
+
+ it('reassures that the guide survived a narration failure', () => {
+ const notice = voiceNotice(update('error', { reason: 'no-audio' }), true);
+ expect(notice).toMatchObject({
+ tone: 'failed',
+ titleKey: 'voice.errorNoAudio',
+ bodyKey: 'voice.guideSafe',
+ showSettings: false,
+ autoDismissMs: null,
+ });
+ });
+
+ it('offers settings only when the key is the thing that is missing', () => {
+ expect(voiceNotice(update('error', { reason: 'missing-api-key' }), true)?.showSettings).toBe(true);
+ expect(voiceNotice(update('error', { reason: 'permission-denied' }), true)?.showSettings).toBe(false);
+ });
+
+ it('falls back to the unknown failure message when no reason came through', () => {
+ expect(voiceNotice(update('error'), true)?.titleKey).toBe('voice.errorUnknown');
+ });
+
+ it('attributes the rewritten descriptions to a step count and then gets out of the way', () => {
+ const notice = voiceNotice(update('idle', { narrated: 4 }), true);
+ expect(notice).toMatchObject({
+ tone: 'done',
+ titleKey: 'voice.narratedPlural',
+ titleSubstitutions: ['4'],
+ autoDismissMs: VOICE_CONFIRM_MS,
+ });
+ });
+
+ it('counts a single narrated step without pluralising', () => {
+ expect(voiceNotice(update('idle', { narrated: 1 }), true)?.titleKey).toBe('voice.narrated');
+ });
+
+ it('states plainly when nothing matched, with no count to substitute', () => {
+ const notice = voiceNotice(update('idle', { narrated: 0 }), true);
+ expect(notice?.titleKey).toBe('voice.narratedNone');
+ expect(notice?.titleSubstitutions).toBeUndefined();
+ });
+
+ it('withholds a result the user never watched arrive', () => {
+ expect(voiceNotice(update('idle', { narrated: 4 }), false)).toBeNull();
+ });
+
+ it('stays silent on a plain idle phase', () => {
+ expect(voiceNotice(update('idle'), true)).toBeNull();
+ });
+});
+
+describe('voiceSignature', () => {
+ it('is stable for repeats of the same update so a dismissal sticks', () => {
+ expect(voiceSignature(update('idle', { narrated: 2 }))).toBe(voiceSignature(update('idle', { narrated: 2 })));
+ });
+
+ it('changes when the phase, the reason or the count changes', () => {
+ const signatures = new Set([
+ voiceSignature(update('transcribing')),
+ voiceSignature(update('error', { reason: 'no-audio' })),
+ voiceSignature(update('error', { reason: 'missing-api-key' })),
+ voiceSignature(update('idle', { narrated: 2 })),
+ voiceSignature(update('idle', { narrated: 3 })),
+ ]);
+ expect(signatures.size).toBe(5);
+ });
+});
+
+describe('locale coverage', () => {
+ const emitted = [
+ ...(['transcribing', 'recording', 'idle'] as VoicePhase[]).flatMap((phase) => [
+ voiceNotice(update(phase), true),
+ voiceNotice(update(phase, { narrated: 0 }), true),
+ voiceNotice(update(phase, { narrated: 2 }), true),
+ ]),
+ voiceNotice(update('error'), true),
+ voiceNotice(update('error', { reason: 'missing-api-key' }), true),
+ ]
+ .filter((notice) => notice !== null)
+ .flatMap((notice) => [notice.titleKey, notice.bodyKey, notice.showSettings ? 'voice.openSettings' : undefined])
+ .filter((key) => key !== undefined);
+
+ it('renders more than one message', () => {
+ expect(emitted.length).toBeGreaterThan(3);
+ });
+
+ it.each(LOCALES)('%s defines every message the notice can show', (locale) => {
+ const keys = localeKeys(locale);
+ for (const key of [...emitted, 'common.close']) expect([...keys]).toContain(key);
+ });
+});
diff --git a/src/ui/fullview/components/VoiceNotice.tsx b/src/ui/fullview/components/VoiceNotice.tsx
new file mode 100644
index 0000000..f3db8fc
--- /dev/null
+++ b/src/ui/fullview/components/VoiceNotice.tsx
@@ -0,0 +1,110 @@
+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';
+
+const IDLE: PanelVoiceUpdate = { type: 'VOICE_UPDATE', phase: 'idle' };
+
+const TONE_ICONS = {
+ progress: Loader2,
+ done: Check,
+ failed: TriangleAlert,
+};
+
+const TONE_CLASSES = {
+ progress: 'text-accent animate-spin motion-reduce:animate-none',
+ done: 'text-success',
+ failed: 'text-destructive',
+};
+
+export default function VoiceNotice() {
+ const [update, setUpdate] = useState<PanelVoiceUpdate>(IDLE);
+ const [seenLive, setSeenLive] = useState(false);
+ const [dismissed, setDismissed] = useState<string | null>(null);
+
+ useEffect(() => {
+ let stop: (() => void) | null = null;
+
+ const receive = (next: PanelVoiceUpdate) => {
+ if (next.phase !== 'idle') setSeenLive(true);
+ setUpdate(next);
+ };
+
+ const resync = () => {
+ getVoiceStatus()
+ .then((status) => {
+ if (!status?.transcribing) return;
+ setSeenLive(true);
+ setUpdate({ type: 'VOICE_UPDATE', phase: 'transcribing' });
+ })
+ .catch(() => undefined);
+ };
+
+ const follow = () => {
+ if (document.visibilityState === 'visible') {
+ stop ??= observeVoiceFromBackground(receive, resync);
+ return;
+ }
+ stop?.();
+ stop = null;
+ };
+
+ follow();
+ document.addEventListener('visibilitychange', follow);
+
+ return () => {
+ document.removeEventListener('visibilitychange', follow);
+ stop?.();
+ };
+ }, []);
+
+ const notice = voiceNotice(update, seenLive);
+ const signature = notice?.signature;
+ const autoDismissMs = notice?.autoDismissMs;
+
+ useEffect(() => {
+ if (!autoDismissMs || signature === undefined) return;
+ const timer = setTimeout(() => setDismissed(signature), autoDismissMs);
+ return () => clearTimeout(timer);
+ }, [autoDismissMs, signature]);
+
+ const shown = notice && dismissed !== notice.signature ? notice : null;
+ const Icon = shown ? TONE_ICONS[shown.tone] : null;
+
+ return (
+ <div role="status" className="fixed bottom-5 right-5 z-50 w-[min(23rem,calc(100vw-2.5rem))] pointer-events-none">
+ {shown && Icon && (
+ <div className="pointer-events-auto rounded-xl border border-border bg-card shadow-lg px-3.5 py-3 flex items-start gap-2.5">
+ <Icon size={15} className={`shrink-0 mt-0.5 ${TONE_CLASSES[shown.tone]}`} />
+
+ <div className="flex-1 min-w-0">
+ <p className="text-[12px] font-semibold text-foreground leading-relaxed">
+ {i18n.t(shown.titleKey, shown.titleSubstitutions)}
+ </p>
+ {shown.bodyKey && (
+ <p className="text-[11px] text-muted-foreground leading-relaxed mt-0.5">{i18n.t(shown.bodyKey)}</p>
+ )}
+ {shown.showSettings && (
+ <button
+ onClick={() => browser.runtime.openOptionsPage()}
+ className="mt-1.5 text-[11px] font-semibold text-accent hover:underline"
+ >
+ {i18n.t('voice.openSettings')}
+ </button>
+ )}
+ </div>
+
+ <button
+ onClick={() => setDismissed(shown.signature)}
+ title={i18n.t('common.close')}
+ className="shrink-0 p-0.5 rounded text-muted-foreground hover:text-foreground transition-colors"
+ >
+ <X size={14} />
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/ui/fullview/voice-notice.ts b/src/ui/fullview/voice-notice.ts
new file mode 100644
index 0000000..a46f9fa
--- /dev/null
+++ b/src/ui/fullview/voice-notice.ts
@@ -0,0 +1,57 @@
+import type { PanelVoiceUpdate } from '@/lib/port';
+import { narratedKey, voiceErrorKey } from '@/ui/sidepanel/voice-status';
+
+export const VOICE_CONFIRM_MS = 7000;
+
+export type VoiceNoticeTone = 'progress' | 'done' | 'failed';
+
+export interface VoiceNotice {
+ tone: VoiceNoticeTone;
+ signature: string;
+ titleKey: string;
+ titleSubstitutions?: string[];
+ bodyKey?: string;
+ showSettings: boolean;
+ 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);
+
+ if (update.phase === 'transcribing') {
+ return {
+ tone: 'progress',
+ signature,
+ titleKey: 'voice.transcribing',
+ bodyKey: 'voice.transcribingHint',
+ showSettings: false,
+ autoDismissMs: null,
+ };
+ }
+
+ if (update.phase === 'error') {
+ return {
+ tone: 'failed',
+ signature,
+ titleKey: voiceErrorKey(update.reason),
+ bodyKey: 'voice.guideSafe',
+ showSettings: update.reason === 'missing-api-key',
+ autoDismissMs: null,
+ };
+ }
+
+ if (update.phase !== 'idle' || update.narrated === undefined || !seenLive) return null;
+
+ return {
+ tone: 'done',
+ signature,
+ titleKey: narratedKey(update.narrated),
+ titleSubstitutions: update.narrated > 0 ? [String(update.narrated)] : undefined,
+ showSettings: false,
+ autoDismissMs: VOICE_CONFIRM_MS,
+ };
+}