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(desktop): read clicks and typing when they happen, not after

Luis Ortiz9a0012c708ac
diff --git a/apps/desktop/scripts/check-pipeline.ts b/apps/desktop/scripts/check-pipeline.ts
index 1a6b469..5d02555 100644
--- a/apps/desktop/scripts/check-pipeline.ts
+++ b/apps/desktop/scripts/check-pipeline.ts
@@ -83,7 +83,7 @@ app.whenReady().then(async () => {
() => region,
(fn) => fn(),
(request) => ask(win.webContents, 'mimik:capture:step', { ...request, guideId: activeGuide }),
- { grab: syntheticDisplay, settings: () => settings },
+ { grab: async () => syntheticDisplay, settings: () => settings },
);
activeGuide = await ask<string>(win.webContents, 'mimik:capture:startGuide');
@@ -221,7 +221,7 @@ app.whenReady().then(async () => {
return Promise.resolve(null);
},
{
- grab: syntheticDisplay,
+ grab: async () => syntheticDisplay,
settings: () => ({
...REGION_MODE,
showCursor: true,
@@ -402,6 +402,95 @@ app.whenReady().then(async () => {
detail: 'a document far longer than the buffer yields the buffer, a short one yields the field, markers are stripped, a button yields nothing',
});
+ const typedThenClicked = async (keysAfterSnapshot: number) => {
+ const sent: CaptureRequest[] = [];
+ let focus: ScreenElement | null = { ...editor('whats is my ip'), role: 'textbox', ariaLabel: 'Address' };
+ const typist = new DesktopRecorder(
+ () => region,
+ (fn) => fn(),
+ (request) => {
+ sent.push(request);
+ return Promise.resolve(null);
+ },
+ {
+ grab: async () => syntheticDisplay,
+ settings: () => REGION_MODE,
+ lookup: () => Promise.resolve(control),
+ focused: () => Promise.resolve(focus),
+ resolve: () => Promise.resolve('x'),
+ reset: () => Promise.resolve(),
+ },
+ );
+ const key = () => typist.onAction(pressed(30));
+ for (let i = 0; i < 3; i++) key();
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ for (let i = 0; i < keysAfterSnapshot; i++) key();
+ focus = { ...control };
+ typist.onAction({ kind: 'click', button: 1, x: region.x + 60, y: region.y + 40, clicks: 1, at: Date.now() });
+ await typist.drain();
+ return sent.find((request) => request.action === 'input');
+ };
+ const settledTyping = await typedThenClicked(0);
+ const hurriedTyping = await typedThenClicked(1);
+ results.push({
+ name: 'typing survives a click that moves the focus',
+ ok:
+ settledTyping?.inputValue === 'whats is my ip' &&
+ settledTyping.elementMeta.ariaLabel === 'Address' &&
+ hurriedTyping?.inputValue === 'xxxx' &&
+ hurriedTyping.elementMeta.ariaLabel === 'Address',
+ detail: `a settled field gave "${settledTyping?.inputValue ?? ''}", a key after the snapshot gave "${hurriedTyping?.inputValue ?? ''}"`,
+ });
+
+ const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+ const calls: string[] = [];
+ let release = () => {};
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const busy = new DesktopRecorder(
+ () => region,
+ (fn) => fn(),
+ async () => {
+ await gate;
+ return null;
+ },
+ {
+ grab: async () => {
+ calls.push('grab');
+ return syntheticDisplay;
+ },
+ settings: () => REGION_MODE,
+ lookup: () => {
+ calls.push('lookup');
+ return Promise.resolve(control);
+ },
+ focused: () => {
+ calls.push('focused');
+ return Promise.resolve(field);
+ },
+ resolve: () => Promise.resolve('x'),
+ reset: () => Promise.resolve(),
+ },
+ );
+ const tap = (x: number) =>
+ busy.onAction({ kind: 'click', button: 1, x: region.x + x, y: region.y + 40, clicks: 1, at: Date.now() });
+ tap(60);
+ await wait(600);
+ tap(200);
+ for (let i = 0; i < 3; i++) busy.onAction(pressed(30));
+ busy.onAction(pressed(28));
+ await wait(50);
+ const early = [...calls];
+ release();
+ await busy.drain();
+ const count = (name: string) => early.filter((call) => call === name).length;
+ results.push({
+ name: 'a press is read when it happens, not when the queue gets to it',
+ ok: count('lookup') === 2 && count('grab') === 3 && count('focused') === 1,
+ detail: `with the first step still being written: ${count('lookup')} lookups, ${count('grab')} grabs, ${count('focused')} field reads`,
+ });
+
const page = { x: 0, y: 0, width: 800, height: 600 };
const click = { x: 160, y: 66 };
const boxed = (rect: ScreenElement['rect']) => targetRect({ ...control, rect }, page, click).width;
diff --git a/apps/desktop/src/main/capture/input-hook.ts b/apps/desktop/src/main/capture/input-hook.ts
index 703e426..7990a78 100644
--- a/apps/desktop/src/main/capture/input-hook.ts
+++ b/apps/desktop/src/main/capture/input-hook.ts
@@ -46,7 +46,7 @@ export class InputHook {
const { uIOhook } = await import('uiohook-napi');
this.hook = uIOhook;
- uIOhook.on('click', (event) => {
+ uIOhook.on('mousedown', (event) => {
onAction({
kind: 'click',
button: Number(event.button ?? 1),
diff --git a/apps/desktop/src/main/capture/recorder.ts b/apps/desktop/src/main/capture/recorder.ts
index 2c074d1..f84db55 100644
--- a/apps/desktop/src/main/capture/recorder.ts
+++ b/apps/desktop/src/main/capture/recorder.ts
@@ -16,12 +16,13 @@ import {
import { focusedWindow } from './focused-window';
import { type InputAction, InputHook, type KeyAction, type PointerAction } from './input-hook';
import type { Region } from './region';
-import { type Capture, captureArea, type Rect } from './screenshot';
+import { type Frame, grabDisplay, type Rect } from './screenshot';
import { writeScreenshot } from './screenshot-store';
import { type CaptureMode, type CaptureSettings, DEFAULT_CAPTURE_SETTINGS } from './settings';
const TARGET_SIZE = 28;
const SETTLE_MS = 60;
+const SNAPSHOT_MS = 400;
const REPEAT_CLICK_MS = 500;
const MARKER_CODE_POINTS = new Set([0x200b, 0xfeff, 0xfff9, 0xfffa, 0xfffb, 0xfffc, 0xfffd]);
const FIELD_SLACK: Record<string, number> = { document: 24 };
@@ -73,7 +74,7 @@ export interface CaptureRequest {
}
export interface RecorderHooks {
- grab?: (area: Rect) => Promise<Capture>;
+ grab?: (point: Point) => Promise<Frame>;
settings?: () => CaptureSettings;
ignores?: (point: Point) => boolean;
lookup?: (point: Point) => Promise<ScreenElement | null>;
@@ -200,9 +201,12 @@ export class DesktopRecorder {
private lastKey: { keycode: number; at: number } | null = null;
private typing = false;
private buffer = '';
+ private keys = 0;
+ private snapshot: { field: Promise<ScreenElement | null>; keys: number } | null = null;
+ private snapshotTimer: NodeJS.Timeout | null = null;
private appending: Promise<unknown> = Promise.resolve();
private idle: NodeJS.Timeout | null = null;
- private readonly grab: (area: Rect) => Promise<Capture>;
+ private readonly grab: (point: Point) => Promise<Frame>;
private readonly settings: () => CaptureSettings;
private readonly ignores: (point: Point) => boolean;
private readonly lookup: (point: Point) => Promise<ScreenElement | null>;
@@ -217,7 +221,7 @@ export class DesktopRecorder {
private readonly send: (request: CaptureRequest) => Promise<unknown>,
hooks: RecorderHooks = {},
) {
- this.grab = hooks.grab ?? captureArea;
+ this.grab = hooks.grab ?? grabDisplay;
this.settings = hooks.settings ?? (() => DEFAULT_CAPTURE_SETTINGS);
this.ignores = hooks.ignores ?? (() => false);
this.lookup = hooks.lookup ?? elementAt;
@@ -229,7 +233,9 @@ export class DesktopRecorder {
async start(): Promise<RecorderStart> {
if (this.running) return { ok: true };
- const started = await this.hook.start((action) => this.onAction(action));
+ const started = await this.hook.start((action) => {
+ if (this.isRecording) this.onAction(action);
+ });
if (!started.ok) return { ok: false, reason: started.reason, detail: started.detail };
this.running = true;
this.paused = false;
@@ -257,8 +263,7 @@ export class DesktopRecorder {
return this.running && !this.paused;
}
- private onAction(action: InputAction): void {
- if (!this.isRecording) return;
+ onAction(action: InputAction): void {
if (action.kind === 'click') this.onClick(action);
else this.onKey(action);
}
@@ -271,9 +276,14 @@ export class DesktopRecorder {
const repeat = isRepeatClick(this.lastClickAt, at);
this.lastClickAt = at;
if (repeat) return;
+ this.clickAt(clickAction(action.button), point);
+ }
+
+ private clickAt(action: string, point: Point): void {
this.commitTyping();
- const named = clickAction(action.button);
- this.enqueue(() => this.write(named, point, this.lookup(point)));
+ const element = this.lookup(point);
+ const frame = this.shoot(point);
+ this.enqueue(() => this.write(action, point, element, frame));
}
private onKey(action: KeyAction): void {
@@ -282,15 +292,21 @@ export class DesktopRecorder {
if (isTextKey(action)) {
if (!settings.recordTyping) return;
this.typing = true;
+ this.keys += 1;
this.buffered(action);
if (this.idle) clearTimeout(this.idle);
- this.idle = setTimeout(() => this.commitTyping(), settings.typingDebounceMs);
+ this.idle = setTimeout(() => this.commitTyping(true), settings.typingDebounceMs);
this.idle.unref?.();
+ if (this.snapshotTimer) clearTimeout(this.snapshotTimer);
+ this.snapshotTimer = setTimeout(() => {
+ this.snapshot = { field: this.focused().catch(() => null), keys: this.keys };
+ }, SNAPSHOT_MS);
+ this.snapshotTimer.unref?.();
return;
}
const submitted = this.typing;
- this.commitTyping();
+ this.commitTyping(true);
const at = Date.now();
const repeat = isRepeatKey(this.lastKey, action.keycode, at);
@@ -307,7 +323,8 @@ export class DesktopRecorder {
const { shortcuts } = this.settings();
if (Object.values(shortcuts).some((accelerator) => isBoundShortcut(accelerator, action, key))) return;
const field = await this.focused();
- await this.write(`keydown:${comboLabel(action, key)}`, centreOf(field) ?? cursorPoint(), Promise.resolve(field));
+ const where = centreOf(field) ?? cursorPoint();
+ await this.write(`keydown:${comboLabel(action, key)}`, where, Promise.resolve(field), this.shoot(where));
}
private buffered(action: KeyAction): void {
@@ -321,22 +338,39 @@ export class DesktopRecorder {
});
}
- private commitTyping(): void {
- if (this.idle) {
- clearTimeout(this.idle);
- this.idle = null;
- }
+ private commitTyping(live = false): void {
+ if (this.idle) clearTimeout(this.idle);
+ if (this.snapshotTimer) clearTimeout(this.snapshotTimer);
+ this.idle = null;
+ this.snapshotTimer = null;
+ const snapshot = live ? null : this.snapshot;
+ this.snapshot = null;
if (!this.typing) return;
this.typing = false;
+ const fresh = !snapshot || snapshot.keys === this.keys;
+ const field = snapshot ? snapshot.field : this.focused().catch(() => null);
+ const frame = field.then((found) => this.shoot(centreOf(found) ?? cursorPoint()));
+ frame.catch(() => undefined);
this.enqueue(async () => {
await this.appending;
const buffer = this.buffer;
this.buffer = '';
await this.reset();
- await this.writeTyping(buffer);
+ await this.writeTyping(buffer, { field: await field, fresh }, frame);
});
}
+ private shoot(point: Point): Promise<Frame> {
+ const { screenshotDelayMs } = this.settings();
+ const grabbed = this.withHidden(async () => {
+ await delay(screenshotDelayMs);
+ return this.grab(point);
+ });
+ const frame = Promise.all([grabbed, delay(SETTLE_MS + screenshotDelayMs)]).then(([taken]) => taken);
+ frame.catch(() => undefined);
+ return frame;
+ }
+
private enqueue(job: () => Promise<void>): void {
this.queue = this.queue.then(job).catch((error) => {
process.stderr.write(`mimik: capture failed: ${error instanceof Error ? error.message : String(error)}\n`);
@@ -345,42 +379,44 @@ export class DesktopRecorder {
captureNow(point: Point): void {
if (!this.isRecording) return;
- this.commitTyping();
- this.enqueue(() => this.write('click', point, this.lookup(point)));
+ this.clickAt('click', point);
}
async capture(point: Point): Promise<void> {
- await this.write('click', point, this.lookup(point));
+ await this.write('click', point, this.lookup(point), this.shoot(point));
}
- async writeTyping(buffer = ''): Promise<void> {
- const field = await this.focused();
+ async writeTyping(
+ buffer = '',
+ seen: { field: ScreenElement | null; fresh: boolean } | null = null,
+ frame?: Promise<Frame>,
+ ): Promise<void> {
+ const field = seen ? seen.field : await this.focused();
const where = centreOf(field) ?? cursorPoint();
+ const shot = frame ?? this.shoot(where);
if (field?.password) {
- await this.write('input', where, Promise.resolve(field));
+ await this.write('input', where, Promise.resolve(field), shot);
return;
}
- const typed = typedTextFor(field, buffer, this.settings().readFieldText);
+ const typed = typedTextFor(field, buffer, this.settings().readFieldText && (seen?.fresh ?? true));
if (!typed) return;
- await this.write('input', where, Promise.resolve(field), typed);
+ await this.write('input', where, Promise.resolve(field), shot, typed);
}
private async write(
action: string,
point: Point,
element: Promise<ScreenElement | null>,
+ taken: Promise<Frame>,
inputValue?: string,
): Promise<void> {
const settings = this.settings();
const region = this.region();
- const taken = await this.withHidden(async () => {
- await delay(SETTLE_MS + settings.screenshotDelayMs);
- const focused = await focusedWindow();
- const rect = frameFor(settings.captureMode, point, region, focused.ok ? focused.window.bounds : null);
- return { found: focused, framed: rect, shot: await this.grab(rect) };
- });
- const { found, framed, shot } = taken;
+ const frame = await taken;
+ const found = await focusedWindow();
+ const framed = frameFor(settings.captureMode, point, region, found.ok ? found.window.bounds : null);
+ const shot = await frame(framed);
const scale = shot.scaleFactor;
const screenshotId = randomUUID();
diff --git a/apps/desktop/src/main/capture/screenshot.ts b/apps/desktop/src/main/capture/screenshot.ts
index a645e98..a8908de 100644
--- a/apps/desktop/src/main/capture/screenshot.ts
+++ b/apps/desktop/src/main/capture/screenshot.ts
@@ -28,38 +28,46 @@ function monitorAt(x: number, y: number): Monitor {
return all[0];
}
-export async function captureArea(area: Rect): Promise<Capture> {
- const display = screen.getDisplayMatching(area);
- const monitor = monitorAt(area.x + area.width / 2, area.y + area.height / 2);
+export type Frame = (area: Rect) => Promise<Capture>;
+
+export async function grabDisplay(point: { x: number; y: number }): Promise<Frame> {
+ const { bounds: display, scaleFactor } = screen.getDisplayNearestPoint(point);
+ const monitor = monitorAt(point.x, point.y);
const frame = await monitor.captureImage();
- const scale = display.bounds.width > 0 ? frame.width / display.bounds.width : display.scaleFactor;
- const x = clamp(Math.round((area.x - display.bounds.x) * scale), 0, Math.max(0, frame.width - 1));
- const y = clamp(Math.round((area.y - display.bounds.y) * scale), 0, Math.max(0, frame.height - 1));
- const width = clamp(Math.round(area.width * scale), 1, frame.width - x);
- const height = clamp(Math.round(area.height * scale), 1, frame.height - y);
+ return async (area) => {
+ const scale = display.width > 0 ? frame.width / display.width : scaleFactor;
+ const x = clamp(Math.round((area.x - display.x) * scale), 0, Math.max(0, frame.width - 1));
+ const y = clamp(Math.round((area.y - display.y) * scale), 0, Math.max(0, frame.height - 1));
+ const width = clamp(Math.round(area.width * scale), 1, frame.width - x);
+ const height = clamp(Math.round(area.height * scale), 1, frame.height - y);
- const cropped = width === frame.width && height === frame.height ? frame : await frame.crop(x, y, width, height);
- const png = await cropped.toPng(true);
- if (png.length === 0 || cropped.width === 0 || cropped.height === 0) {
- throw new Error(
- `capture produced an empty image: frame ${frame.width}x${frame.height}, area ${area.width}x${area.height} at ${scale}x`,
- );
- }
+ const cropped = width === frame.width && height === frame.height ? frame : await frame.crop(x, y, width, height);
+ const png = await cropped.toPng(true);
+ if (png.length === 0 || cropped.width === 0 || cropped.height === 0) {
+ throw new Error(
+ `capture produced an empty image: frame ${frame.width}x${frame.height}, area ${area.width}x${area.height} at ${scale}x`,
+ );
+ }
- return {
- png,
- width: cropped.width,
- height: cropped.height,
- scaleFactor: area.width > 0 ? cropped.width / area.width : 1,
- displayId: monitor.id(),
+ return {
+ png,
+ width: cropped.width,
+ height: cropped.height,
+ scaleFactor: area.width > 0 ? cropped.width / area.width : 1,
+ displayId: monitor.id(),
+ };
};
}
export async function captureDisplay(displayId: number): Promise<Capture> {
const display = screen.getAllDisplays().find((d) => d.id === displayId);
if (!display) throw new Error(`no display with id ${displayId}`);
- return captureArea(display.bounds);
+ const frame = await grabDisplay({
+ x: display.bounds.x + display.bounds.width / 2,
+ y: display.bounds.y + display.bounds.height / 2,
+ });
+ return frame(display.bounds);
}
export async function captureCursorDisplay(): Promise<Capture> {
diff --git a/apps/desktop/src/main/overlay/index.ts b/apps/desktop/src/main/overlay/index.ts
index 1a70e3d..1509665 100644
--- a/apps/desktop/src/main/overlay/index.ts
+++ b/apps/desktop/src/main/overlay/index.ts
@@ -51,6 +51,7 @@ export interface OverlayOptions {
const BORDER = 3;
const CONTROLS = { width: 300, height: 190, margin: 24 };
const INTRO_LIMIT_MS = 6000;
+const HIDE_SETTLE_MS = 60;
const NO_SHORTCUTS: OverlayShortcuts = { startStop: null, capture: null };
function rendererFile(): string {
@@ -111,6 +112,7 @@ export class CaptureOverlay {
private step: OverlayStep | null = null;
private size = { width: CONTROLS.width, height: CONTROLS.height };
private busy = false;
+ private hiding: { shown: BrowserWindow[]; ready: Promise<unknown>; users: number } | null = null;
private starting = false;
constructor(
@@ -374,15 +376,26 @@ export class CaptureOverlay {
async withHidden<T>(fn: () => Promise<T>): Promise<T> {
if (process.platform !== 'linux') return fn();
- const shown = this.windows().filter((win) => win.isVisible());
- for (const win of shown) win.hide();
+ if (!this.hiding) {
+ const shown = this.windows().filter((win) => win.isVisible());
+ for (const win of shown) win.hide();
+ const ready = new Promise((resolve) => setTimeout(resolve, shown.length > 0 ? HIDE_SETTLE_MS : 0));
+ this.hiding = { shown, ready, users: 0 };
+ }
+ const hiding = this.hiding;
+ hiding.users += 1;
try {
+ await hiding.ready;
return await fn();
} finally {
- for (const win of shown) {
- if (win.isDestroyed()) continue;
- win.showInactive();
- protect(win);
+ hiding.users -= 1;
+ if (hiding.users === 0) {
+ this.hiding = null;
+ for (const win of hiding.shown) {
+ if (win.isDestroyed()) continue;
+ win.showInactive();
+ protect(win);
+ }
}
}
}