Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion crates/compositor/src/audio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3118,7 +3118,11 @@ mod tests {
// crests back over full scale), raised by the loudness gain: the export read +0.5 dBTP.
let mut recording = through_aac(&voice(8.0, 1.0, 2.0), "clipped-recording");
let gain = loudness_gain_for(loudness_of(&recording));
assert!(gain > 1.0, "the fixture needs raising, like #1157's +1.6 dB: {gain}");
// The AAC round-trip's integrated loudness shifts by a few tenths of a dB
// between platform encoders (arm64 measured 0.95 here, Intel ~1.6). This
// guard only needs to prove the fixture asks for a boost; keep it well
// below 1 dB so the cross-encoder drift cannot turn it into a flaky failure.
assert!(gain > 0.5, "the fixture needs raising, like #1157's +1.6 dB: {gain}");
apply_gain_db(&mut recording, gain);
assert_lufs(loudness_of(&recording), -16.0);
let hot = true_peak_dbtp(&recording);
Expand Down
25 changes: 25 additions & 0 deletions electron/app-settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,31 @@ describe("app settings store", () => {
);
});

// The keystroke overlay installs a keyboard hook that observes every key of a
// take. It must default off (including for settings files written before the
// preference existed) and be persisted and validated like other toggles.
it("keeps the keystroke overlay off by default and persists the opt-in", () => {
const dir = temp();
const file = path.join(dir, "recording-settings.json");
const store = new AppSettingsStore(dir);
expect(store.getSnapshot().recording.keystrokeOverlayEnabled).toBe(false);

expect(
store.setRecordingPreferences({ keystrokeOverlayEnabled: true }).recording
.keystrokeOverlayEnabled,
).toBe(true);
expect(JSON.parse(readFileSync(file, "utf8"))).toMatchObject({
keystrokeOverlayEnabled: true,
});
expect(new AppSettingsStore(dir).getSnapshot().recording.keystrokeOverlayEnabled).toBe(true);

writeFileSync(file, JSON.stringify({ micEnabled: true }), "utf8");
expect(store.getSnapshot().recording.keystrokeOverlayEnabled).toBe(false);
expect(() =>
store.setRecordingPreferences({ keystrokeOverlayEnabled: "yes" as never }),
).toThrow(TypeError);
});

it("stores the last source beside the recording preferences", () => {
const dir = temp();
const store = new AppSettingsStore(dir);
Expand Down
10 changes: 10 additions & 0 deletions electron/app-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ export interface RecordingPreferences {
* behaviour it gates has been on for every such installation.
*/
autoZoomEnabled: boolean;
/**
* Live on-screen keystroke badges during a take (Windows only). Off by default:
* the hook observes every key typed while recording, so it must be opt-in.
*/
keystrokeOverlayEnabled: boolean;
}

export const DEFAULT_RECORDING_PREFERENCES: RecordingPreferences = {
Expand All @@ -44,6 +49,7 @@ export const DEFAULT_RECORDING_PREFERENCES: RecordingPreferences = {
cursorCaptureMode: "editable-overlay",
hideDesktopIcons: false,
autoZoomEnabled: true,
keystrokeOverlayEnabled: false,
};

export interface RecordingSourceDescriptor {
Expand Down Expand Up @@ -123,6 +129,10 @@ function parseRecording(raw: RawSettings): RecordingPreferences {
: DEFAULT_RECORDING_PREFERENCES.cursorCaptureMode,
hideDesktopIcons: bool(raw.hideDesktopIcons, DEFAULT_RECORDING_PREFERENCES.hideDesktopIcons),
autoZoomEnabled: bool(raw.autoZoomEnabled, DEFAULT_RECORDING_PREFERENCES.autoZoomEnabled),
keystrokeOverlayEnabled: bool(
raw.keystrokeOverlayEnabled,
DEFAULT_RECORDING_PREFERENCES.keystrokeOverlayEnabled,
),
};
}

Expand Down
2 changes: 2 additions & 0 deletions electron/electron-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,8 @@ interface Window {
) => () => void;
/** The overlay painted a frame without the digit; a Linux hide waits for this. */
notifyCountdownOverlayCleared: (runId: number) => void;
/** A live keydown while a take is running (`KeystrokeOverlay`). */
onKeystrokeKey: (callback: (vk: number, modifiers?: number) => void) => () => void;
setMicrophoneExpanded: (expanded: boolean) => void;
setHasUnsavedChanges: (hasChanges: boolean) => void;
onRequestSaveBeforeClose: (callback: () => Promise<boolean> | boolean) => () => void;
Expand Down
150 changes: 150 additions & 0 deletions electron/ipc/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@ import { isDiagnosticModeEnabled, mainLogFile } from "../diagnostics/main-log-fi
import { createZip } from "../diagnostics/zip";
import { mainT } from "../i18n";
import { getInstallChannel } from "../install-channel";
import {
broadcastKeystroke,
hideKeystrokeOverlay,
showKeystrokeOverlay,
} from "../keystrokeOverlay";
import {
DEFAULT_RECORDINGS_DIR,
getRecordingsDirInfo,
Expand Down Expand Up @@ -759,6 +764,8 @@ export interface RecordingPrefs {
hideDesktopIcons: boolean;
/** Whether a fresh take gets automatic zooms on import. Persisted; defaults on. */
autoZoomEnabled: boolean;
/** Live keystroke badges on the recorded display (win32). Opt-in: the hook sees every key. */
keystrokeOverlayEnabled: boolean;
}
const defaultRecordingPrefs: RecordingPrefs = {
micEnabled: false,
Expand All @@ -772,6 +779,7 @@ const defaultRecordingPrefs: RecordingPrefs = {
cursorCaptureMode: "editable-overlay",
hideDesktopIcons: false,
autoZoomEnabled: true,
keystrokeOverlayEnabled: false,
};

// Cached source from the user's pick. Used by setDisplayMediaRequestHandler in main.ts for cursor-free capture.
Expand Down Expand Up @@ -816,6 +824,29 @@ const CURSOR_SAMPLE_INTERVAL_MS = 33;
const MAX_CURSOR_SAMPLES = 60 * 60 * 30; // 1 hour @ 30Hz

let cursorRecordingSession: CursorRecordingSession | null = null;
/**
* Module-level mirror of the `keystrokeOverlayEnabled` preference. The cursor
* session is created by module-level helpers that cannot reach the handler-local
* `recordingPrefs`; this is kept in sync from its initializer and onChange so
* those helpers can decide whether to install the low-level keyboard hook.
*/
let keystrokeKeysEnabled = false;
/**
* Keyboard-only capture for takes that do not run a cursor telemetry session
* (Windows system-cursor mode). The keystroke overlay needs the native helper's
* low-level keyboard hook even when no editable cursor overlay is drawn; reusing
* the telemetry session would tie key capture to `editable-overlay` and leave
* system-cursor takes with an overlay that never shows a key (#1633 review).
*/
let keystrokeKeySession: CursorRecordingSession | null = null;
/**
* A keyboard-only session whose `start()` is still pending. Tracking it before
* the await lets Stop tear it down and blocks a second Start from racing in
* while the slot still looks empty.
*/
let pendingKeystrokeKeySession: CursorRecordingSession | null = null;
/** Monotonic token so a Stop can invalidate an in-flight start's completion. */
let keystrokeKeyGeneration = 0;
let pendingCursorRecordingData: CursorRecordingData | null = null;
let nativeWindowsCaptureProcess: ChildProcessWithoutNullStreams | null = null;
let nativeWindowsCaptureOutput = "";
Expand Down Expand Up @@ -1417,6 +1448,13 @@ async function startCursorRecording(recordingId?: number) {
sourceId: getSelectedSourceId(),
startTimeMs:
typeof recordingId === "number" && Number.isFinite(recordingId) ? recordingId : undefined,
// Only ask the helper for the keyboard hook when the overlay is enabled.
// The helper installs WH_KEYBOARD_LL unconditionally otherwise, which would
// observe every key typed during a take even with the overlay switched off.
onKeyEvent: keystrokeKeysEnabled
? (event) => broadcastKeystroke(event.vk, event.modifiers)
: undefined,
captureKeys: keystrokeKeysEnabled,
});

try {
Expand All @@ -1442,6 +1480,77 @@ async function stopCursorRecording() {
}
}

/**
* Start a keyboard-only native session for a Windows take that has no cursor
* telemetry session. The helper's low-level keyboard hook is what drives the
* keystroke overlay; it is independent of the selected cursor mode. No-op when
* a cursor session already exists (it carries the same hook) or off Windows.
*/
async function startKeystrokeKeyCapture(): Promise<void> {
if (
process.platform !== "win32" ||
cursorRecordingSession ||
keystrokeKeySession ||
pendingKeystrokeKeySession
)
return;
const generation = ++keystrokeKeyGeneration;
const session = createCursorRecordingSession({
getDisplayBounds: getSelectedSourceBounds,
maxSamples: MAX_CURSOR_SAMPLES,
platform: "win32",
sampleIntervalMs: CURSOR_SAMPLE_INTERVAL_MS,
sourceId: getSelectedSourceId(),
captureKeys: true,
onKeyEvent: (event) => {
// A session Stop already tore down can still have queued key lines. Drop
// them so no key paints on the overlay after the take ends.
if (generation !== keystrokeKeyGeneration) return;
broadcastKeystroke(event.vk, event.modifiers);
},
});
// Publish before awaiting `start()` so Stop sees the session and a second
// Start is rejected by the pending-slot guard above.
pendingKeystrokeKeySession = session;
try {
await session.start();
} catch (error) {
// A Stop that tore this session down mid-start rejects `start()` on helper
// exit. That is expected teardown, not a startup failure worth logging.
if (generation === keystrokeKeyGeneration) {
console.error("Failed to start keystroke key capture:", error);
}
if (pendingKeystrokeKeySession === session) pendingKeystrokeKeySession = null;
return;
}
if (pendingKeystrokeKeySession === session) pendingKeystrokeKeySession = null;
// Stop invalidated this start while it was pending. Stop owns the teardown of
// that session, so do not publish it and do not stop it a second time here.
if (generation !== keystrokeKeyGeneration) return;
keystrokeKeySession = session;
}

/**
* Stop the keyboard-only session; its cursor samples are never written out.
* Also tears down a session whose `start()` is still pending: the generation
* bump makes that start's continuation discard its result, so Stop is the sole
* owner of teardown.
*/
async function stopKeystrokeKeyCapture(): Promise<void> {
// Invalidate any in-flight start before touching the slots so its eventual
// completion cannot republish the session as live.
keystrokeKeyGeneration += 1;
const session = keystrokeKeySession ?? pendingKeystrokeKeySession;
keystrokeKeySession = null;
pendingKeystrokeKeySession = null;
if (!session) return;
try {
await session.stop();
} catch (error) {
console.error("Failed to stop keystroke key capture:", error);
}
}

async function writePendingCursorTelemetry(videoPath: string) {
const telemetryPath = `${videoPath}.cursor.json`;
if (pendingCursorRecordingData && pendingCursorRecordingData.samples.length > 0) {
Expand Down Expand Up @@ -2056,6 +2165,13 @@ export function registerIpcHandlers(
) {
/** The HUD is recording a take, the user's or an MCP client's. Set by `setAppRecording` only. */
let appRecording = false;
/**
* Resolved capture bounds of the current take, when the start path knows them
* explicitly (native Windows request can target a display other than the
* mutable selection). The keystroke overlay is positioned from these; the
* selection getter is only a fallback for paths without explicit bounds.
*/
let takeRecordingBounds: Rectangle | null = null;
const recordingCompletion = new RecordingCompletion();
/**
* Every start and stop of a take goes through here: the browser path's `set-recording-state`
Expand All @@ -2075,6 +2191,28 @@ export function registerIpcHandlers(
if (!recording && !preparing) cameraPreview.setCaptureAllowed(true);
if (!preparing) mcpAppRecorder.recordingChanged(recording, recordingId);
onRecordingStateChange?.(recording, sourceName, preparing);
// The keystroke overlay lives only while a take is live, on the display being
// recorded. Windows only: the overlay's invisibility-to-capture relies on
// content protection, which `applyContentProtection` gates per platform.
// Opt-in via `keystrokeOverlayEnabled`: the low-level hook observes every key
// typed during a take, so it is off by default and installed only on request.
if (process.platform === "win32") {
if (recording && recordingPrefs.get().keystrokeOverlayEnabled) {
void showKeystrokeOverlay(takeRecordingBounds ?? getSelectedSourceBounds());
// The keystroke overlay needs the native keyboard hook in every cursor
// mode. In editable-overlay mode the cursor session already carries it;
// otherwise (system cursor) no session is running, so start a
// keyboard-only one. Guarded by `!preparing` so it attaches to the take
// proper, after the editable-overlay session has had a chance to start.
if (!preparing) void startKeystrokeKeyCapture();
} else {
// Always tear down on stop (or when the option is off), so a take that
// ends after the toggle was switched off cannot leave a hook behind.
hideKeystrokeOverlay();
takeRecordingBounds = null;
void stopKeystrokeKeyCapture();
}
}
};
const appSettings = new AppSettingsStore(app.getPath("userData"));
const broadcastSelectedSource = (source: SelectedSource | null) => {
Expand Down Expand Up @@ -2401,6 +2539,9 @@ export function registerIpcHandlers(
getMainWindow,
() => BrowserWindow.getAllWindows(),
(previous, next) => {
// Keep the module-level mirror in step with the durable setting, so a
// cursor session created on the next take installs the hook only if asked.
keystrokeKeysEnabled = next.keystrokeOverlayEnabled;
// Apple's picker bakes the exclusions into the filter it hands back, so a pick made
// before "Hide desktop icons" changed would still record the desktop the old way.
// Dropping it makes the HUD ask for a new pick instead of ignoring the toggle.
Expand All @@ -2420,6 +2561,9 @@ export function registerIpcHandlers(
}
},
);
// Seed the mirror from the persisted value: onChange only fires on later edits,
// so without this a restored "on" setting would still skip the hook on startup.
keystrokeKeysEnabled = recordingPrefs.get().keystrokeOverlayEnabled;

// Asked before every take starts. A disk that fills up mid-take used to be found only
// when the take was saved, and the take was lost with it.
Expand Down Expand Up @@ -3262,6 +3406,12 @@ export function registerIpcHandlers(
}
// Reserve startup before cursor/helper awaits without reporting a started take.
startReserved = true;
// Publish the overlay's display only now, after the final reservation
// guard: a rejected start must not move a take that is already live, and
// there is no await between here and the overlay show below (#1633).
// The request resolved this display; it may differ from the mutable
// selection when an MCP client targets another screen.
takeRecordingBounds = bounds;
setAppRecording(true, selectedSource?.name ?? "Screen", undefined, true);
await fs.mkdir(RECORDINGS_DIR, { recursive: true });
nativeWindowsCaptureOutput = "";
Expand Down
74 changes: 74 additions & 0 deletions electron/ipc/keystrokeOverlayOptIn.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// The keystroke overlay installs a low-level keyboard hook that observes every
// key typed during a take. It is off by default and opt-in per setting, and the
// helper must only install the hook when asked. The gate lives in handlers.ts
// (needs the whole Electron runtime) and in the native session's argv building,
// so we assert these invariants against source the way sibling tests do.

import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, "../..");
const read = (...segs: string[]) => fs.readFileSync(path.join(root, ...segs), "utf8");

const handlers = read("electron/ipc/handlers.ts");
const session = read("electron/native-bridge/cursor/recording/windowsNativeRecordingSession.ts");
const cpp = read("electron/native/wgc-capture/src/cursor-sampler.cpp");
const defaults = read("electron/app-settings.ts");
const types = read("electron/ipc/handlers.ts");

function fnBody(source: string, name: string): string {
const start = source.indexOf(`async function ${name}(`);
expect(start, `no ${name}`).toBeGreaterThan(-1);
const end = source.indexOf("\n}\n", start);
return source.slice(start, end === -1 ? undefined : end);
}

describe("keystroke overlay is opt-in", () => {
it("defaults off in both preference stores", () => {
expect(defaults).toMatch(/keystrokeOverlayEnabled: false/);
// handlers.ts carries the mirrored RecordingPrefs default.
expect(types).toMatch(/keystrokeOverlayEnabled: false/);
});

it("only starts the overlay and hook when the option is on", () => {
const register = handlers.slice(handlers.indexOf("const setAppRecording"));
const gate = register.slice(0, register.indexOf("const appSettings"));
expect(gate).toContain("recording && recordingPrefs.get().keystrokeOverlayEnabled");
expect(gate).toContain("showKeystrokeOverlay");
expect(gate).toContain("startKeystrokeKeyCapture");
// Stop always tears down, even if the toggle was switched off mid-take.
expect(gate).toContain("hideKeystrokeOverlay");
expect(gate).toContain("stopKeystrokeKeyCapture");
});

it("gates the cursor session's key callback on the option", () => {
const body = fnBody(handlers, "startCursorRecording");
expect(body).toContain("onKeyEvent: keystrokeKeysEnabled");
expect(body).toContain("captureKeys: keystrokeKeysEnabled");
});

it("seeds and updates the module-level gate from the durable prefs", () => {
expect(handlers).toContain(
"keystrokeKeysEnabled = recordingPrefs.get().keystrokeOverlayEnabled",
);
expect(handlers).toContain("keystrokeKeysEnabled = next.keystrokeOverlayEnabled");
});

it("passes --keys to the helper only when captureKeys is set", () => {
expect(session).toContain("this.options.captureKeys");
expect(session).toContain('args.push("--keys")');
});

it("installs the native keyboard hook only with --keys", () => {
expect(cpp).toContain('std::string(argv[3]) == "--keys"');
// The hook call must be inside the opt-in branch, not unconditional.
const optIn = cpp.indexOf("if (captureKeys)");
const hook = cpp.indexOf("SetWindowsHookEx(WH_KEYBOARD_LL");
expect(optIn, "no captureKeys branch").toBeGreaterThan(-1);
expect(hook, "no keyboard hook").toBeGreaterThan(-1);
expect(hook).toBeGreaterThan(optIn);
});
});
Loading
Loading