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

fix(capture): draw the target outline where a subframe element sits in the tab

davbio18f3ce1e558b
diff --git a/src/core/capture/__tests__/session-sync.test.ts b/src/core/capture/__tests__/session-sync.test.ts
index 8aac914..2b882ae 100644
--- a/src/core/capture/__tests__/session-sync.test.ts
+++ b/src/core/capture/__tests__/session-sync.test.ts
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { GetStateResponse } from '@/lib/messaging';
import { CaptureState } from '../machine';
@@ -10,6 +10,9 @@ vi.mock('@/lib/messaging', () => ({ sendMessage: (...args: unknown[]) => sendMes
vi.mock('../events/handlers', () => ({
startCapture: (guideId: string, isTopFrame: boolean) => startCapture(guideId, isTopFrame),
}));
+const stopAnswering = vi.fn();
+const answerChildFrames = vi.fn(() => stopAnswering);
+vi.mock('../dom/frame-placement', () => ({ answerChildFrames: () => answerChildFrames() }));
vi.mock('@/lib/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
async function bootFrame(state: GetStateResponse, onSynced?: (s: GetStateResponse) => void) {
@@ -73,3 +76,72 @@ describe('CaptureSession boot sync', () => {
expect(session.isActive).toBe(false);
});
});
+
+describe('CaptureSession answering child frames', () => {
+ async function idleSession() {
+ vi.useFakeTimers();
+ sendMessage.mockReturnValue(new Promise(() => {}));
+ const { CaptureSession } = await import('../session');
+ return new CaptureSession();
+ }
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('answers nobody before a recording starts', async () => {
+ await idleSession();
+
+ expect(answerChildFrames).not.toHaveBeenCalled();
+ });
+
+ it('keeps answering past a stop, so a child can still place its last typing step', async () => {
+ const session = await idleSession();
+ session.start('guide-1');
+ session.stop();
+
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(stopAnswering).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(stopAnswering).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps a single responder across a pause and resume', async () => {
+ const session = await idleSession();
+ session.start('guide-1');
+ session.stop();
+ await vi.advanceTimersByTimeAsync(500);
+ session.start('guide-1');
+
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(answerChildFrames).toHaveBeenCalledTimes(1);
+ expect(stopAnswering).not.toHaveBeenCalled();
+ });
+
+ it('counts the grace from the last stop, not an earlier one', async () => {
+ const session = await idleSession();
+ session.start('guide-1');
+ session.stop();
+ await vi.advanceTimersByTimeAsync(500);
+ session.start('guide-1');
+ await vi.advanceTimersByTimeAsync(500);
+ session.stop();
+
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(stopAnswering).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(600);
+ expect(stopAnswering).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops answering at once when disposed', async () => {
+ const session = await idleSession();
+ session.start('guide-1');
+ session.dispose();
+ expect(stopAnswering).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(stopAnswering).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/core/capture/dom/__tests__/frame-placement.test.ts b/src/core/capture/dom/__tests__/frame-placement.test.ts
new file mode 100644
index 0000000..240bd86
--- /dev/null
+++ b/src/core/capture/dom/__tests__/frame-placement.test.ts
@@ -0,0 +1,296 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { answerChildFrames, contentBox, IDENTITY, locateFrame, placeInTab } from '@/core/capture/dom/frame-placement';
+import type { ElementMeta } from '@/core/guides/types';
+
+type Listener = (event: MessageEvent) => void;
+interface FakeWindow {
+ document: Document;
+ parent: Pick<Window, 'postMessage'> | FakeWindow;
+ listeners: Set<Listener>;
+ addEventListener: (type: string, fn: Listener) => void;
+ removeEventListener: (type: string, fn: Listener) => void;
+ postMessage: (data: unknown) => void;
+}
+
+function deliver(to: FakeWindow, data: unknown, source: unknown) {
+ const copy = structuredClone(data);
+ setTimeout(() => {
+ for (const fn of [...to.listeners]) fn({ data: copy, source } as MessageEvent);
+ }, 0);
+}
+
+function fakeWindow(document: Document): FakeWindow {
+ const listeners = new Set<Listener>();
+ const win: FakeWindow = {
+ document,
+ parent: undefined as unknown as FakeWindow,
+ listeners,
+ addEventListener: (_type, fn) => listeners.add(fn),
+ removeEventListener: (_type, fn) => listeners.delete(fn),
+ postMessage: (data) => deliver(win, data, win.parent),
+ };
+ win.parent = win;
+ return win;
+}
+
+interface Box {
+ left: number;
+ top: number;
+ width?: number;
+ offsetWidth?: number;
+ style?: Partial<CSSStyleDeclaration>;
+ root?: Document | ShadowRoot;
+}
+
+function embed(parent: FakeWindow, box: Box): { child: FakeWindow; frame: HTMLIFrameElement } {
+ const frame = parent.document.createElement('iframe');
+ ((box.root ?? parent.document.body) as ParentNode).appendChild(frame);
+ const width = box.width ?? 300;
+ frame.getBoundingClientRect = () =>
+ ({ left: box.left, top: box.top, x: box.left, y: box.top, width, height: 150 }) as DOMRect;
+ Object.defineProperty(frame, 'offsetWidth', { value: box.offsetWidth ?? width });
+ Object.assign(frame.style, { border: '0' }, box.style ?? {});
+
+ const child = fakeWindow(document.implementation.createHTMLDocument());
+ const childAsParentSeesIt = { parent, postMessage: (data: unknown) => deliver(child, data, child.parent) };
+ child.parent = { postMessage: (data: unknown) => deliver(parent, data, childAsParentSeesIt) } as Pick<
+ Window,
+ 'postMessage'
+ >;
+ Object.defineProperty(frame, 'contentWindow', { value: childAsParentSeesIt });
+ return { child, frame };
+}
+
+const asWindow = (win: FakeWindow) => win as unknown as Window;
+
+function meta(over: Partial<ElementMeta> = {}): ElementMeta {
+ return {
+ tag: 'input',
+ cssSelector: '#vehicle1',
+ textContent: null,
+ ariaLabel: null,
+ placeholder: null,
+ altText: null,
+ name: 'vehicle1',
+ role: 'input',
+ href: null,
+ inputType: 'checkbox',
+ dataTestId: null,
+ rect: { x: 8, y: 10, width: 13, height: 13 },
+ devicePixelRatio: 2,
+ ...over,
+ };
+}
+
+const teardowns: Array<() => void> = [];
+
+function answering(win: FakeWindow) {
+ teardowns.push(answerChildFrames(asWindow(win)));
+}
+
+afterEach(() => {
+ for (const stop of teardowns.splice(0)) stop();
+ vi.useRealTimers();
+ document.body.innerHTML = '';
+});
+
+describe('locateFrame', () => {
+ it('asks nobody from the top frame, which is the tab', async () => {
+ const top = fakeWindow(document);
+ const post = vi.spyOn(top, 'postMessage');
+
+ await expect(locateFrame(asWindow(top))).resolves.toEqual(IDENTITY);
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it('takes the position its parent measures, even across origins', async () => {
+ const top = fakeWindow(document);
+ answering(top);
+ const { child } = embed(top, { left: 981, top: 527 });
+
+ await expect(locateFrame(asWindow(child))).resolves.toEqual({ x: 981, y: 527, scale: 1 });
+ });
+
+ it('starts inside the frame border and padding, where the child coordinates begin', async () => {
+ const top = fakeWindow(document);
+ answering(top);
+ const { child } = embed(top, { left: 100, top: 50, style: { border: '2px solid', padding: '3px' } });
+
+ await expect(locateFrame(asWindow(child))).resolves.toEqual({ x: 105, y: 55, scale: 1 });
+ });
+
+ it('adds up every frame between it and the tab', async () => {
+ const top = fakeWindow(document);
+ answering(top);
+ const { child: middle } = embed(top, { left: 100, top: 50 });
+ answering(middle);
+ const { child: inner } = embed(middle, { left: 10, top: 20 });
+
+ await expect(locateFrame(asWindow(inner))).resolves.toEqual({ x: 110, y: 70, scale: 1 });
+ });
+
+ it('carries a scaled frame through to the frames inside it', async () => {
+ const top = fakeWindow(document);
+ answering(top);
+ const { child: middle } = embed(top, { left: 100, top: 50, width: 400, offsetWidth: 800 });
+ answering(middle);
+ const { child: inner } = embed(middle, { left: 10, top: 20 });
+
+ await expect(locateFrame(asWindow(inner))).resolves.toEqual({ x: 105, y: 60, scale: 0.5 });
+ });
+
+ it('finds a frame a web component keeps in its shadow root', async () => {
+ const top = fakeWindow(document);
+ answering(top);
+ const host = document.createElement('video-embed');
+ document.body.appendChild(host);
+ const { child } = embed(top, { left: 40, top: 60, root: host.attachShadow({ mode: 'open' }) });
+
+ await expect(locateFrame(asWindow(child))).resolves.toEqual({ x: 40, y: 60, scale: 1 });
+ });
+
+ it('measures the frame that asked, not the first frame on the page', async () => {
+ const top = fakeWindow(document);
+ answering(top);
+ embed(top, { left: 10, top: 10 });
+ const { child } = embed(top, { left: 400, top: 250 });
+
+ await expect(locateFrame(asWindow(child))).resolves.toEqual({ x: 400, y: 250, scale: 1 });
+ });
+
+ it.each([
+ ['an offset', { x: 2e6, y: 0, scale: 1 }],
+ ['a vertical offset', { x: 0, y: -2e6, scale: 1 }],
+ ['a collapsed scale', { x: 0, y: 0, scale: 0 }],
+ ['a runaway scale', { x: 0, y: 0, scale: 1e4 }],
+ ])('refuses %s too large to be a real placement', async (_what, forged) => {
+ vi.useFakeTimers();
+ const top = fakeWindow(document);
+ const { child } = embed(top, { left: 981, top: 527 });
+ const parent = child.parent;
+ parent.postMessage = (data: unknown) => {
+ const { id } = data as { id: string };
+ deliver(child, { mimikFramePlacement: 'answer', id, ...forged }, parent);
+ };
+
+ const placement = locateFrame(asWindow(child));
+ await vi.advanceTimersByTimeAsync(1000);
+
+ await expect(placement).resolves.toEqual(IDENTITY);
+ });
+
+ it('gives up and leaves the rect where it was when the parent never answers', async () => {
+ vi.useFakeTimers();
+ const top = fakeWindow(document);
+ const { child } = embed(top, { left: 981, top: 527 });
+
+ const placement = locateFrame(asWindow(child));
+ await vi.advanceTimersByTimeAsync(1000);
+
+ await expect(placement).resolves.toEqual(IDENTITY);
+ });
+
+ it('ignores an answer from a window other than its parent', async () => {
+ vi.useFakeTimers();
+ const top = fakeWindow(document);
+ const { child } = embed(top, { left: 981, top: 527 });
+ const stranger = fakeWindow(document.implementation.createHTMLDocument());
+ const toParent = child.parent.postMessage;
+ child.parent.postMessage = (data: unknown) => {
+ const { id } = data as { id: string };
+ deliver(child, { mimikFramePlacement: 'answer', id, x: 5, y: 5, scale: 1 }, stranger);
+ toParent(data, '*');
+ };
+
+ const placement = locateFrame(asWindow(child));
+ await vi.advanceTimersByTimeAsync(1000);
+
+ await expect(placement).resolves.toEqual(IDENTITY);
+ });
+});
+
+describe('answerChildFrames', () => {
+ it('does not answer a window that is not one of its frames', async () => {
+ const top = fakeWindow(document);
+ answering(top);
+ const stranger = fakeWindow(document.implementation.createHTMLDocument());
+ const reply = vi.spyOn(stranger, 'postMessage');
+
+ deliver(top, { mimikFramePlacement: 'ask', id: 'x' }, stranger);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ expect(reply).not.toHaveBeenCalled();
+ });
+
+ it('turns a stranger away without searching the page for it', async () => {
+ const top = fakeWindow(document);
+ answering(top);
+ embed(top, { left: 10, top: 10 });
+ const search = vi.spyOn(document, 'querySelectorAll');
+
+ deliver(top, { mimikFramePlacement: 'ask', id: 'x' }, fakeWindow(document.implementation.createHTMLDocument()));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ expect(search).not.toHaveBeenCalled();
+ search.mockRestore();
+ });
+
+ it('stops answering once torn down', async () => {
+ vi.useFakeTimers();
+ const top = fakeWindow(document);
+ const stop = answerChildFrames(asWindow(top));
+ const { child } = embed(top, { left: 981, top: 527 });
+ stop();
+
+ const placement = locateFrame(asWindow(child));
+ await vi.advanceTimersByTimeAsync(1000);
+
+ await expect(placement).resolves.toEqual(IDENTITY);
+ });
+});
+
+describe('contentBox', () => {
+ it('scales the border inset with a transformed frame', () => {
+ const frame = document.createElement('iframe');
+ document.body.appendChild(frame);
+ frame.getBoundingClientRect = () => ({ left: 0, top: 0, width: 400 }) as DOMRect;
+ Object.defineProperty(frame, 'offsetWidth', { value: 800 });
+ frame.style.border = '4px solid';
+
+ expect(contentBox(frame)).toEqual({ x: 2, y: 2, scale: 0.5 });
+ });
+
+ it('treats a frame with no layout as unscaled rather than dividing by zero', () => {
+ const frame = document.createElement('iframe');
+ document.body.appendChild(frame);
+ frame.getBoundingClientRect = () => ({ left: 7, top: 9, width: 0 }) as DOMRect;
+ frame.style.border = '0';
+
+ expect(contentBox(frame)).toEqual({ x: 7, y: 9, scale: 1 });
+ });
+});
+
+describe('placeInTab', () => {
+ it('moves the rect and the click point by the same placement', () => {
+ const placed = placeInTab(meta({ clickPoint: { x: 14, y: 16 } }), { x: 981, y: 527, scale: 1 });
+ expect(placed.rect).toEqual({ x: 989, y: 537, width: 13, height: 13 });
+ expect(placed.clickPoint).toEqual({ x: 995, y: 543 });
+ });
+
+ it('shrinks the rect with a scaled frame', () => {
+ const placed = placeInTab(meta(), { x: 100, y: 50, scale: 0.5 });
+ expect(placed.rect).toEqual({ x: 104, y: 55, width: 6.5, height: 6.5 });
+ });
+
+ it('keeps the rest of the meta, pixel ratio included', () => {
+ const placed = placeInTab(meta(), { x: 1, y: 1, scale: 1 });
+ expect(placed).toMatchObject({ cssSelector: '#vehicle1', inputType: 'checkbox', devicePixelRatio: 2 });
+ expect(placed).not.toHaveProperty('clickPoint');
+ });
+
+ it('returns a top-frame meta untouched', () => {
+ const original = meta();
+ expect(placeInTab(original, IDENTITY)).toBe(original);
+ });
+});
diff --git a/src/core/capture/dom/frame-placement.ts b/src/core/capture/dom/frame-placement.ts
new file mode 100644
index 0000000..873f831
--- /dev/null
+++ b/src/core/capture/dom/frame-placement.ts
@@ -0,0 +1,128 @@
+import type { ElementMeta } from '@/core/guides/types';
+
+export interface FramePlacement {
+ x: number;
+ y: number;
+ scale: number;
+}
+
+export const IDENTITY: FramePlacement = { x: 0, y: 0, scale: 1 };
+
+const KEY = 'mimikFramePlacement';
+const ANSWER_TIMEOUT_MS = 250;
+const FRAME_SELECTOR = 'iframe, frame, object';
+const MAX_OFFSET_PX = 1e6;
+const MIN_SCALE = 1e-3;
+const MAX_SCALE = 1e3;
+
+interface Ask {
+ [KEY]: 'ask';
+ id: string;
+}
+
+let asked = 0;
+
+function isAsk(data: unknown): data is Ask {
+ const msg = data as Partial<Ask> | null;
+ return typeof msg === 'object' && msg !== null && msg[KEY] === 'ask' && typeof msg.id === 'string';
+}
+
+function isPlausibleOffset(value: unknown): value is number {
+ return typeof value === 'number' && Math.abs(value) <= MAX_OFFSET_PX;
+}
+
+function isPlausibleScale(value: unknown): value is number {
+ return typeof value === 'number' && value >= MIN_SCALE && value <= MAX_SCALE;
+}
+
+function readAnswer(data: unknown, id: string): FramePlacement | null {
+ const msg = data as Record<string, unknown> | null;
+ if (typeof msg !== 'object' || msg === null || msg[KEY] !== 'answer' || msg.id !== id) return null;
+ const { x, y, scale } = msg;
+ if (!isPlausibleOffset(x) || !isPlausibleOffset(y) || !isPlausibleScale(scale)) return null;
+ return { x, y, scale };
+}
+
+function within(outer: FramePlacement, inner: FramePlacement): FramePlacement {
+ return {
+ x: outer.x + inner.x * outer.scale,
+ y: outer.y + inner.y * outer.scale,
+ scale: outer.scale * inner.scale,
+ };
+}
+
+function isChildOf(win: Window, source: MessageEventSource | null): source is Window {
+ return !!source && 'parent' in source && source.parent === win && source !== win;
+}
+
+function frameElementFor(root: Document | ShadowRoot, source: Window): HTMLElement | null {
+ for (const el of root.querySelectorAll<HTMLIFrameElement>(FRAME_SELECTOR)) {
+ if (el.contentWindow === source) return el;
+ }
+ for (const host of root.querySelectorAll('*')) {
+ const hit = host.shadowRoot && frameElementFor(host.shadowRoot, source);
+ if (hit) return hit;
+ }
+ return null;
+}
+
+export function contentBox(frame: HTMLElement): FramePlacement {
+ const box = frame.getBoundingClientRect();
+ const scale = frame.offsetWidth > 0 && box.width > 0 ? box.width / frame.offsetWidth : 1;
+ const style = frame.ownerDocument.defaultView?.getComputedStyle(frame);
+ const inset = (border?: string, padding?: string) =>
+ ((Number.parseFloat(border ?? '') || 0) + (Number.parseFloat(padding ?? '') || 0)) * scale;
+ return {
+ x: box.left + inset(style?.borderLeftWidth, style?.paddingLeft),
+ y: box.top + inset(style?.borderTopWidth, style?.paddingTop),
+ scale,
+ };
+}
+
+export function locateFrame(win: Window = window): Promise<FramePlacement> {
+ const parent = win.parent;
+ if (!parent || parent === win) return Promise.resolve(IDENTITY);
+
+ const id = `${Date.now().toString(36)}.${++asked}.${Math.random().toString(36).slice(2)}`;
+ return new Promise((resolve) => {
+ const settle = (placement: FramePlacement) => {
+ clearTimeout(timer);
+ win.removeEventListener('message', onMessage);
+ resolve(placement);
+ };
+ const onMessage = (event: MessageEvent) => {
+ if (event.source !== parent) return;
+ const placement = readAnswer(event.data, id);
+ if (placement) settle(placement);
+ };
+ const timer = setTimeout(() => settle(IDENTITY), ANSWER_TIMEOUT_MS);
+ win.addEventListener('message', onMessage);
+ parent.postMessage({ [KEY]: 'ask', id } satisfies Ask, '*');
+ });
+}
+
+export function answerChildFrames(win: Window = window): () => void {
+ const onMessage = (event: MessageEvent) => {
+ const ask = event.data;
+ const child = event.source;
+ if (!isAsk(ask) || !isChildOf(win, child)) return;
+ const frame = frameElementFor(win.document, child);
+ if (!frame) return;
+ const local = contentBox(frame);
+ void locateFrame(win).then((own) => {
+ child.postMessage({ [KEY]: 'answer', id: ask.id, ...within(own, local) }, '*');
+ });
+ };
+ win.addEventListener('message', onMessage);
+ return () => win.removeEventListener('message', onMessage);
+}
+
+export function placeInTab(meta: ElementMeta, at: FramePlacement): ElementMeta {
+ if (at.x === 0 && at.y === 0 && at.scale === 1) return meta;
+ const point = (p: { x: number; y: number }) => ({ x: at.x + p.x * at.scale, y: at.y + p.y * at.scale });
+ return {
+ ...meta,
+ rect: { ...point(meta.rect), width: meta.rect.width * at.scale, height: meta.rect.height * at.scale },
+ ...(meta.clickPoint ? { clickPoint: point(meta.clickPoint) } : {}),
+ };
+}
diff --git a/src/core/capture/events/handlers.ts b/src/core/capture/events/handlers.ts
index 33d5552..5b54d74 100644
--- a/src/core/capture/events/handlers.ts
+++ b/src/core/capture/events/handlers.ts
@@ -15,6 +15,7 @@ import {
isTextField,
isTooLarge,
} from '../dom/element-utils';
+import { locateFrame, placeInTab } from '../dom/frame-placement';
import { isReplayedClick, replayClick, replayInit, shouldInterceptClick } from './click-intercept';
import { InputSession } from './input-session';
@@ -105,11 +106,12 @@ class CaptureController {
private capture(action: string, target: HTMLElement, point?: { x: number; y: number }) {
const atEvent = freezeRect(target);
return async () => {
+ const placement = locateFrame();
const elementMeta = extractElementMeta(target, atEvent);
await sendMessage('captureStep', {
guideId: this.guideId,
action,
- elementMeta: point ? { ...elementMeta, clickPoint: point } : elementMeta,
+ elementMeta: placeInTab(point ? { ...elementMeta, clickPoint: point } : elementMeta, await placement),
domContext: extractDOMContext(target, action),
});
};
diff --git a/src/core/capture/events/input-session.ts b/src/core/capture/events/input-session.ts
index fd74764..59b9bff 100644
--- a/src/core/capture/events/input-session.ts
+++ b/src/core/capture/events/input-session.ts
@@ -4,6 +4,7 @@ import { sendMessage } from '@/lib/messaging';
import { extractDOMContext } from '../dom/context';
import { extractElementMeta, type FrozenRect, freezeRect } from '../dom/element-meta';
import { getFieldLabel, getFieldValue, isRedactedField, isSensitiveField } from '../dom/element-utils';
+import { locateFrame, placeInTab } from '../dom/frame-placement';
export class InputSession {
stepId: string | null = null;
@@ -22,10 +23,12 @@ export class InputSession {
async start(target: HTMLElement, atEvent?: FrozenRect) {
this.atEvent = atEvent;
+ const placement = locateFrame();
+ const elementMeta = extractElementMeta(target, atEvent);
const res = await sendMessage('captureStep', {
guideId: this.guideId,
action: 'input',
- elementMeta: extractElementMeta(target, atEvent),
+ elementMeta: placeInTab(elementMeta, await placement),
domContext: extractDOMContext(target, 'input'),
});
if ('stepId' in res) {
@@ -60,9 +63,11 @@ export class InputSession {
this.stepId = null;
this.target = null;
this.atEvent = undefined;
+ const placement = locateFrame();
+ const elementMeta = extractElementMeta(target, atEvent);
await sendMessage('finalizeInputStep', {
stepId,
- elementMeta: extractElementMeta(target, atEvent),
+ elementMeta: placeInTab(elementMeta, await placement),
domContext: extractDOMContext(target, 'input'),
});
}
diff --git a/src/core/capture/session.ts b/src/core/capture/session.ts
index 4e20ff9..bcd0fa3 100644
--- a/src/core/capture/session.ts
+++ b/src/core/capture/session.ts
@@ -1,12 +1,17 @@
import { logger } from '@/lib/logger';
import { type GetStateResponse, sendMessage } from '@/lib/messaging';
+import { answerChildFrames } from './dom/frame-placement';
import { type CaptureHandle, startCapture } from './events/handlers';
import { CaptureState } from './machine';
+const FRAME_ANSWER_GRACE_MS = 2000;
+
export class CaptureSession {
private capture: CaptureHandle | null = null;
private activeGuideId: string | null = null;
private disabled = false;
+ private frameAnswersTeardown: (() => void) | null = null;
+ private frameAnswerGrace: ReturnType<typeof setTimeout> | undefined;
constructor(private readonly onSynced?: (state: GetStateResponse) => void) {
this.syncWithBackground();
@@ -32,6 +37,8 @@ export class CaptureSession {
logger.info('Capture started β†’ guideId:', guideId);
this.activeGuideId = guideId;
+ clearTimeout(this.frameAnswerGrace);
+ this.frameAnswersTeardown ??= answerChildFrames();
const isTopFrame = window.self === window.top;
this.capture = startCapture(guideId, isTopFrame);
}
@@ -43,6 +50,7 @@ export class CaptureSession {
const draining = this.capture?.stop() ?? Promise.resolve();
this.capture = null;
this.activeGuideId = null;
+ this.frameAnswerGrace = setTimeout(() => this.stopAnsweringFrames(), FRAME_ANSWER_GRACE_MS);
return draining;
}
@@ -58,8 +66,15 @@ export class CaptureSession {
.catch(() => {});
}
+ private stopAnsweringFrames(): void {
+ this.frameAnswersTeardown?.();
+ this.frameAnswersTeardown = null;
+ }
+
dispose(): void {
this.stop();
+ clearTimeout(this.frameAnswerGrace);
+ this.stopAnsweringFrames();
this.disabled = true;
logger.debug('Capture session disposed');
}