π¬ A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots π
TypeScript browser-extensionchrome-extensiondocumentationfirefox-extensionguide-generatorlocal-firstmanifest-v3privacy-firstproductivityreactscreenshotstep-by-step-guidetutorialtypescriptworkflowwxt
feat(desktop): fall back to the keystroke buffer where a field has no usable value
Luis Ortiza7321ad2c58a
diff --git a/AGENTS.md b/AGENTS.mdindex fd732cc..48d0899 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -307,9 +307,9 @@ the way in and the rectangle with `screenToDipRect` on the way out, the same con`UIA_CheckBoxControlTypeId`. An unmapped control type yields a null role rather than an inventedname.-`focusedElement()` is the second call, and it is what makes typing capture possible without reading-keystrokes. `keyLabel()` is the third, and unlike the other two it is synchronous, because resolving-a scancode against a keyboard layout is a local call with nothing to wait on. It reports `isPassword` alongside the usual fields, and the value is discarded at the+`focusedElement()` is the second call. The remaining three β `keyLabel`, `resolveKey` and+`resetDeadKeyState` β are the keyboard, and unlike the first two they are synchronous, because+resolving a scancode against a keyboard layout is a local call with nothing to wait on. It reports `isPassword` alongside the usual fields, and the value is discarded at theaddon boundary when that flag is set, so a password never reaches our data even though UIAutomationalready withholds it.@@ -520,15 +520,14 @@ keycode table, no layout handling, no dead-key state and no IME composition traccodebase β the machinery those need exists to answer a question we do not ask.A session opens on any key that is not a modifier, not `Enter`, `Tab` or `Escape`, and not held with-`Ctrl`, `Alt` or `Meta`. It closes on any of those, on a click, on pause, on stop, or after 1200 ms+`Ctrl`, `Alt` or `Meta`, and every such key also appends to a buffer of what was typed. It closes on any of those, on a click, on pause, on stop, or after 1200 mswith no keys. `Shift` plus a letter still counts as typing, which is why modifiers are testedindividually rather than as a set.Closing a session does not guarantee a step. The focused element is read first, and nothing is-written unless it is a text field with something in it β so pressing `n` in a file manager, or-typing into a surface that exposes no value, costs nothing. The exception is a password field, which-by design reports no value at all: there the step is written anyway, with no `inputValue`, and-`buildFallbackDescription` words it as "Type password" rather than naming the field's contents.+written unless it is a text field with something to show for it. A password field is the exception+in the other direction: it reports no value by design, and the step is written anyway with no+`inputValue`, worded "Type password" rather than naming any contents.Keys that are not typing get their own step. A shortcut always does; `Enter`, `Tab` and `Escape` doonly when no typing session was open, because the `Enter` that submits a field is part of that@@ -542,9 +541,26 @@ as `Q` on QWERTY and `A` on AZERTY, which is what the application being recordeddead-key state as a side effect, and a shortcut only needs the letter, digit or named key. A key thatmaps to none of those yields no label and therefore no step, rather than a step nobody can follow.-Rich text is the gap. `ValuePattern` is what the value is read through, and a word processor or a-browser's `contenteditable` exposes `TextPattern` instead, so typing there closes a session and-writes nothing. Clicks in those applications still capture normally.+Two sources compete for the text and `chooseTypedText` picks between them. The field's value wins+by default, because it is what is actually on screen and it survives caret movement, selection and+autocomplete. The keystroke buffer wins in three cases: the focused element reports no value, the+value is empty, or the value runs more than twice the buffer and past 80 characters. That last rule+is what makes rich text work β in a word processor the "field" is the whole document, so its value+is the entire text rather than the sentence just typed, and the buffer is the only thing that knows+which part is new. A non-text role yields nothing at all, so a keypress in a file manager is not a+step.++Building that buffer is the only place a keystroke becomes a character. `resolveKey` runs+`ToUnicodeEx` against the foreground layout with the modifier state the hook reported and the real+caps-lock state, and appends what comes back; `Backspace` removes one. Dead keys fall out of this+for free: `ToUnicodeEx` returns nothing for the accent itself and the composed character for the key+after it, because it keeps that state per thread and every keystroke goes through the same one. The+cost is that the state is real and can be left armed, so `resetDeadKeyState` flushes it whenever a+session ends.++Values are stripped of `\uFFF9`β`\uFFFD`, `\uFEFF` and `\u200B` before use. Accessibility+implementations use those to mark annotations and inline objects, and they arrive as invisible+garbage in the middle of otherwise ordinary text.`DesktopRecorder` takes its region, its overlay hiding and its sink positionally, and everythingelse β the display grab, the settings, the overlay hit test, the element lookup and the focuseddiff --git a/apps/desktop/scripts/check-capture.ts b/apps/desktop/scripts/check-capture.tsindex 0b7197f..6911361 100644--- a/apps/desktop/scripts/check-capture.ts+++ b/apps/desktop/scripts/check-capture.ts@@ -6,6 +6,7 @@ import {elementLookupAvailable,focusedWindow,keyLabel,+ resolveKey,InputHook,listDisplays,} from '../src/main/capture';@@ -89,11 +90,15 @@ app.whenReady().then(async () => {);const named = lookup ? await keyLabel(28) : null;- if (lookup && named !== 'Enter') failures++;+ const typed = lookup ? await resolveKey(30, false, false, false) : null;+ const keysOk = named === 'Enter' && typed?.length === 1;+ if (lookup && !keysOk) failures++;line('key names',- lookup ? (named === 'Enter' ? 'ok' : 'fail') : 'n/a',- lookup ? `scancode 28 resolved to ${named ?? 'nothing'} on the foreground layout` : 'no addon on this platform',+ lookup ? (keysOk ? 'ok' : 'fail') : 'n/a',+ lookup+ ? `scancode 28 names ${named ?? 'nothing'}, scancode 30 types ${typed ?? 'nothing'} on the foreground layout`+ : 'no addon on this platform',);const hook = new InputHook();diff --git a/apps/desktop/scripts/check-pipeline.ts b/apps/desktop/scripts/check-pipeline.tsindex 0e26cbf..e887f89 100644--- a/apps/desktop/scripts/check-pipeline.ts+++ b/apps/desktop/scripts/check-pipeline.ts@@ -6,9 +6,10 @@ import type { ScreenElement } from '../src/main/capture/element';import type { KeyAction } from '../src/main/capture/input-hook';import {type CaptureRequest,+ chooseTypedText,+ comboLabel,DesktopRecorder,frameFor,- comboLabel,isRepeatClick,isRepeatKey,isTypingKey,@@ -293,6 +294,32 @@ app.whenReady().then(async () => {detail: `wrote ${shortcut?.action ?? 'nothing'}; an unnameable key wrote nothing, auto-repeat collapses, a different key does not`,});+ const editor = (value: string | null): ScreenElement => ({+ role: 'document',+ name: null,+ textContent: value,+ ariaLabel: 'Document',+ altText: null,+ password: false,+ rect: { x: region.x + 10, y: region.y + 10, width: 400, height: 300 },+ });++ seen = null;+ field = editor('x'.repeat(500));+ await metaRecorder.captureTyping('hello');+ const rich = seen as CaptureRequest | null;++ results.push({+ name: 'rich text falls back to the keystrokes',+ ok:+ rich?.inputValue === 'hello' &&+ chooseTypedText(editor('a short note'), 'a sho') === 'a short note' &&+ chooseTypedText(editor(null), 'typed') === 'typed' &&+ chooseTypedText({ ...editor('\uFEFFhi\u200B'), role: 'textbox' }, '') === 'hi' &&+ chooseTypedText(control, 'typed') === null,+ 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 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/element.ts b/apps/desktop/src/main/capture/element.tsindex 196e463..86c886a 100644--- a/apps/desktop/src/main/capture/element.ts+++ b/apps/desktop/src/main/capture/element.ts@@ -14,12 +14,14 @@ export interface ScreenElement {rect: { x: number; y: number; width: number; height: number } | null;}-const TEXT_ROLES = new Set(['textbox', 'combobox']);+const TEXT_ROLES = new Set(['textbox', 'combobox', 'document']);type Addon = {elementAtPoint(x: number, y: number): Promise<UiElement | null>;focusedElement(): Promise<UiElement | null>;keyLabel(keycode: number): string | null;+ resolveKey(keycode: number, shift: boolean, ctrl: boolean, alt: boolean): string | null;+ resetDeadKeyState(): void;isSupported(): boolean;};@@ -94,6 +96,16 @@ export async function keyLabel(keycode: number): Promise<string | null> {return native?.keyLabel(keycode) ?? null;}+export async function resolveKey(keycode: number, shift: boolean, ctrl: boolean, alt: boolean): Promise<string | null> {+ const native = await load();+ return native?.resolveKey(keycode, shift, ctrl, alt) ?? null;+}++export async function resetDeadKeyState(): Promise<void> {+ const native = await load();+ native?.resetDeadKeyState();+}+export async function elementLookupAvailable(): Promise<boolean> {const native = await load();return native?.isSupported() ?? false;diff --git a/apps/desktop/src/main/capture/index.ts b/apps/desktop/src/main/capture/index.tsindex e4c9754..e3acc7d 100644--- a/apps/desktop/src/main/capture/index.ts+++ b/apps/desktop/src/main/capture/index.ts@@ -1,5 +1,14 @@export { cursorPoint, type DisplayInfo, displayAt, listDisplays } from './displays';-export { elementAt, elementLookupAvailable, focusedField, isTextField, keyLabel, type ScreenElement } from './element';+export {+ elementAt,+ elementLookupAvailable,+ focusedField,+ isTextField,+ keyLabel,+ resetDeadKeyState,+ resolveKey,+ type ScreenElement,+} from './element';export { type FocusedWindow, type FocusedWindowResult, focusedWindow } from './focused-window';export { type InputAction, InputHook, type InputHookStart, type KeyAction, type PointerAction } from './input-hook';export { type Capture, captureCursorDisplay, captureDisplay } from './screenshot';diff --git a/apps/desktop/src/main/capture/recorder.ts b/apps/desktop/src/main/capture/recorder.tsindex 15d3e54..11a207d 100644--- a/apps/desktop/src/main/capture/recorder.ts+++ b/apps/desktop/src/main/capture/recorder.ts@@ -3,7 +3,15 @@ import type { CaptureImage } from '@mimik/core/capture/sink';import type { ElementMeta } from '@mimik/core/guides/types';import { screen } from 'electron';import { cursorPoint } from './displays';-import { elementAt, focusedField, isTextField, keyLabel, type ScreenElement } from './element';+import {+ elementAt,+ focusedField,+ isTextField,+ keyLabel,+ resetDeadKeyState,+ resolveKey,+ type ScreenElement,+} from './element';import { focusedWindow } from './focused-window';import { type InputAction, InputHook, type KeyAction, type PointerAction } from './input-hook';import type { Region } from './region';@@ -15,9 +23,12 @@ const TARGET_SIZE = 28;const SETTLE_MS = 60;const REPEAT_CLICK_MS = 500;const TYPING_IDLE_MS = 1200;+const TEXT_MARKERS = /[\uFFF9-\uFFFD\uFEFF\u200B]/g;+const LONG_FIELD_CHARS = 80;const KEY = {escape: 1,+ backspace: 14,tab: 15,enter: 28,ctrl: 29,@@ -71,6 +82,8 @@ export interface RecorderHooks {lookup?: (point: Point) => Promise<ScreenElement | null>;focused?: () => Promise<ScreenElement | null>;label?: (keycode: number) => Promise<string | null>;+ resolve?: (keycode: number, shift: boolean, ctrl: boolean, alt: boolean) => Promise<string | null>;+ reset?: () => Promise<void>;}export type RecorderStart = { ok: true } | { ok: false; reason: string; detail: string };@@ -117,6 +130,15 @@ export function comboLabel(action: KeyAction, key: string): string {return [...held, key].join('+');}+export function chooseTypedText(field: ScreenElement | null, buffer: string): string | null {+ if (!isTextField(field)) return null;+ const value = (field?.textContent ?? '').replace(TEXT_MARKERS, '');+ if (!value.trim()) return buffer || null;+ const typed = [...buffer].length;+ if (typed > 0 && [...value].length > Math.max(2 * typed, LONG_FIELD_CHARS)) return buffer;+ return value;+}+export function isTypingKey(action: KeyAction): boolean {if (MODIFIER_KEYS.has(action.keycode)) return false;if (action.ctrl || action.alt || action.meta) return false;@@ -154,6 +176,8 @@ export class DesktopRecorder {private lastClickAt: number | null = null;private lastKey: { keycode: number; at: number } | null = null;private typing = false;+ private buffer = '';+ private appending: Promise<unknown> = Promise.resolve();private idle: NodeJS.Timeout | null = null;private readonly grab: (area: Rect) => Promise<Capture>;private readonly settings: () => CaptureSettings;@@ -161,6 +185,8 @@ export class DesktopRecorder {private readonly lookup: (point: Point) => Promise<ScreenElement | null>;private readonly focused: () => Promise<ScreenElement | null>;private readonly label: (keycode: number) => Promise<string | null>;+ private readonly resolve: (keycode: number, shift: boolean, ctrl: boolean, alt: boolean) => Promise<string | null>;+ private readonly reset: () => Promise<void>;constructor(private readonly region: () => Region,@@ -174,6 +200,8 @@ export class DesktopRecorder {this.lookup = hooks.lookup ?? elementAt;this.focused = hooks.focused ?? focusedField;this.label = hooks.label ?? keyLabel;+ this.resolve = hooks.resolve ?? resolveKey;+ this.reset = hooks.reset ?? resetDeadKeyState;}async start(): Promise<RecorderStart> {@@ -228,6 +256,7 @@ export class DesktopRecorder {if (MODIFIER_KEYS.has(action.keycode)) return;if (isTypingKey(action)) {this.typing = true;+ this.buffered(action);if (this.idle) clearTimeout(this.idle);this.idle = setTimeout(() => this.commitTyping(), TYPING_IDLE_MS);this.idle.unref?.();@@ -252,6 +281,17 @@ export class DesktopRecorder {await this.write(`keydown:${comboLabel(action, key)}`, centreOf(field) ?? cursorPoint(), Promise.resolve(field));}+ private buffered(action: KeyAction): void {+ this.appending = this.appending.then(async () => {+ if (action.keycode === KEY.backspace) {+ this.buffer = [...this.buffer].slice(0, -1).join('');+ return;+ }+ const typed = await this.resolve(action.keycode, action.shift, action.ctrl, action.alt);+ if (typed) this.buffer += typed;+ });+ }+private commitTyping(): void {if (this.idle) {clearTimeout(this.idle);@@ -259,7 +299,13 @@ export class DesktopRecorder {}if (!this.typing) return;this.typing = false;- this.enqueue(() => this.captureTyping());+ this.enqueue(async () => {+ await this.appending;+ const buffer = this.buffer;+ this.buffer = '';+ await this.reset();+ await this.captureTyping(buffer);+ });}private enqueue(job: () => Promise<void>): void {@@ -272,12 +318,16 @@ export class DesktopRecorder {await this.write('click', point, this.lookup(point));}- async captureTyping(): Promise<void> {+ async captureTyping(buffer = ''): Promise<void> {const field = await this.focused();- if (!isTextField(field) || !field) return;- if (!field.password && !field.textContent) return;- const typed = field.password ? undefined : (field.textContent ?? undefined);- await this.write('input', centreOf(field) ?? cursorPoint(), Promise.resolve(field), typed);+ const where = centreOf(field) ?? cursorPoint();+ if (field?.password) {+ await this.write('input', where, Promise.resolve(field));+ return;+ }+ const typed = chooseTypedText(field, buffer);+ if (!typed) return;+ await this.write('input', where, Promise.resolve(field), typed);}private async write(diff --git a/packages/capture-native/index.d.ts b/packages/capture-native/index.d.tsindex 214232a..190d3f1 100644--- a/packages/capture-native/index.d.ts+++ b/packages/capture-native/index.d.ts@@ -24,6 +24,10 @@ export declare function isSupported(): booleanexport declare function keyLabel(keycode: number): string | null+export declare function resetDeadKeyState(): void++export declare function resolveKey(keycode: number, shift: boolean, ctrl: boolean, alt: boolean): string | null+export interface UiElement {role?: stringname?: stringdiff --git a/packages/capture-native/index.js b/packages/capture-native/index.jsindex 530f7dd..6082b7e 100644--- a/packages/capture-native/index.js+++ b/packages/capture-native/index.js@@ -782,3 +782,5 @@ module.exports.elementAtPoint = nativeBinding.elementAtPointmodule.exports.focusedElement = nativeBinding.focusedElementmodule.exports.isSupported = nativeBinding.isSupportedmodule.exports.keyLabel = nativeBinding.keyLabel+module.exports.resetDeadKeyState = nativeBinding.resetDeadKeyState+module.exports.resolveKey = nativeBinding.resolveKeydiff --git a/packages/capture-native/src/lib.rs b/packages/capture-native/src/lib.rsindex d5327b0..1ede4b8 100644--- a/packages/capture-native/src/lib.rs+++ b/packages/capture-native/src/lib.rs@@ -73,6 +73,23 @@ pub fn key_label(keycode: u32) -> Option<String> {}}+#[napi]+pub fn resolve_key(keycode: u32, shift: bool, ctrl: bool, alt: bool) -> Option<String> {+ #[cfg(windows)]+ return win::resolve_key(keycode, shift, ctrl, alt);+ #[cfg(not(windows))]+ {+ let _ = (keycode, shift, ctrl, alt);+ None+ }+}++#[napi]+pub fn reset_dead_key_state() {+ #[cfg(windows)]+ win::reset_dead_key_state();+}+#[napi]pub fn is_supported() -> bool {cfg!(windows)diff --git a/packages/capture-native/src/win.rs b/packages/capture-native/src/win.rsindex b601717..4117e3b 100644--- a/packages/capture-native/src/win.rs+++ b/packages/capture-native/src/win.rs@@ -8,9 +8,9 @@ use windows::Win32::System::Com::{};use windows::Win32::UI::Accessibility::*;use windows::Win32::UI::Input::KeyboardAndMouse::{- GetKeyboardLayout, MapVirtualKeyExW, HKL, MAPVK_VSC_TO_VK_EX, VK_BACK, VK_DELETE, VK_DOWN, VK_END,- VK_ESCAPE, VK_F1, VK_F24, VK_HOME, VK_INSERT, VK_LEFT, VK_NEXT, VK_PRIOR, VK_RETURN, VK_RIGHT, VK_SPACE,- VK_TAB, VK_UP,+ GetKeyState, GetKeyboardLayout, MapVirtualKeyExW, ToUnicodeEx, HKL, MAPVK_VK_TO_VSC, MAPVK_VSC_TO_VK_EX,+ VK_BACK, VK_CAPITAL, VK_CONTROL, VK_DELETE, VK_DOWN, VK_END, VK_ESCAPE, VK_F1, VK_F24, VK_HOME, VK_INSERT,+ VK_LEFT, VK_MENU, VK_NEXT, VK_PRIOR, VK_RETURN, VK_RIGHT, VK_SHIFT, VK_SPACE, VK_TAB, VK_UP,};use windows::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId};@@ -193,3 +193,56 @@ pub fn key_label(keycode: u32) -> Option<String> {}None}++fn virtual_key(keycode: u32, layout: HKL) -> u16 {+ let extended = keycode >= EXTENDED;+ let scancode = if extended {+ 0xe000 | (keycode - EXTENDED)+ } else {+ keycode+ };+ unsafe { MapVirtualKeyExW(scancode, MAPVK_VSC_TO_VK_EX, Some(layout)) as u16 }+}++pub fn resolve_key(keycode: u32, shift: bool, ctrl: bool, alt: bool) -> Option<String> {+ let layout = foreground_layout();+ let vk = virtual_key(keycode, layout);+ if vk == 0 {+ return None;+ }+ let mut state = [0u8; 256];+ if shift {+ state[VK_SHIFT.0 as usize] = 0x80;+ }+ if ctrl {+ state[VK_CONTROL.0 as usize] = 0x80;+ }+ if alt {+ state[VK_MENU.0 as usize] = 0x80;+ }+ if unsafe { GetKeyState(VK_CAPITAL.0 as i32) } & 1 == 1 {+ state[VK_CAPITAL.0 as usize] = 0x01;+ }+ let scancode = unsafe { MapVirtualKeyExW(vk as u32, MAPVK_VK_TO_VSC, Some(layout)) };+ let mut buffer = [0u16; 8];+ let written = unsafe { ToUnicodeEx(vk as u32, scancode, &state, &mut buffer, 0, Some(layout)) };+ if written <= 0 {+ return None;+ }+ String::from_utf16(&buffer[..written as usize])+ .ok()+ .filter(|found| !found.is_empty())+}++pub fn reset_dead_key_state() {+ let layout = foreground_layout();+ let vk = VK_SPACE.0 as u32;+ let scancode = unsafe { MapVirtualKeyExW(vk, MAPVK_VK_TO_VSC, Some(layout)) };+ let state = [0u8; 256];+ let mut buffer = [0u16; 8];+ for _ in 0..4 {+ if unsafe { ToUnicodeEx(vk, scancode, &state, &mut buffer, 0, Some(layout)) } >= 0 {+ break;+ }+ }+}