The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): detect the dual-Command gesture on macOS
brooklyn!76a4d3b62a97
diff --git a/apps/desktop/electron/command-screenshot-monitor.test.ts b/apps/desktop/electron/command-screenshot-monitor.test.tsnew file mode 100644index 00000000000..2eb7d15eb85--- /dev/null+++ b/apps/desktop/electron/command-screenshot-monitor.test.ts@@ -0,0 +1,247 @@+import assert from 'node:assert/strict'+import { execFileSync, spawn as nodeSpawn, type SpawnOptions, spawnSync } from 'node:child_process'+import { EventEmitter } from 'node:events'+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { resolve } from 'node:path'+import { PassThrough } from 'node:stream'++import { test, vi } from 'vitest'++import {+ type CommandScreenshotCapture,+ CommandScreenshotMonitor,+ type CommandScreenshotStatus,+ resolveCommandScreenshotMonitorPath,+} from './command-screenshot-monitor'++class FakeChild extends EventEmitter {+ stdin = new PassThrough()+ stdout = new PassThrough()+ stderr = null+ kill = vi.fn((_signal?: NodeJS.Signals) => true)+}++test('launches the unpacked helper without prompting and delivers only validated capture messages', () => {+ const child = new FakeChild()+ const spawn = vi.fn((_command: string, _args: string[], _options: SpawnOptions) => child)+ const captures: CommandScreenshotCapture[] = []+ const statuses: CommandScreenshotStatus[] = []+ const monitor = new CommandScreenshotMonitor({+ platform: 'darwin', appPath: '/Applications/Hermes.app/Contents/Resources/app.asar', spawn,+ })+ monitor.start(value => captures.push(value), value => statuses.push(value))+ assert.equal(spawn.mock.calls.length, 1)+ assert.deepEqual(spawn.mock.calls[0], [+ '/Applications/Hermes.app/Contents/Resources/app.asar.unpacked/dist/native/command-screenshot-monitor',+ [], { stdio: ['pipe', 'pipe', 'ignore'], shell: false, detached: false, windowsHide: true },+ ])+ child.stdout.write('{"type":"capture","windowId":2,"width":100,"height":200}\n')+ assert.deepEqual(captures, []) // No capture until readiness is established.+ child.stdout.write('{"type":"rea')+ child.stdout.write('dy"}\nnot json\n{"type":"key","key":"private"}\n')+ child.stdout.write('{"type":"capture","windowId":0,"width":100,"height":200}\n')+ child.stdout.write('{"type":"capture","windowId":2,"width":-1,"height":200}\n')+ child.stdout.write('{"type":"capture","windowId":2,"width":100,"height":200,"private":"discard"}\n')+ assert.deepEqual(captures, [{ type: 'capture', windowId: 2, width: 100, height: 200 }])+ assert.deepEqual(statuses, [{ type: 'starting' }, { type: 'ready' }])+ monitor.stop()+ child.emit('close', 0, null)+ assert.equal(child.kill.mock.calls[0]?.[0], 'SIGTERM')+ assert.equal(child.stdout.listenerCount('data'), 0)+ assert.deepEqual(statuses.at(-1), { type: 'stopped' })+ assert.equal(resolveCommandScreenshotMonitorPath('/tmp/dev'), '/tmp/dev/dist/native/command-screenshot-monitor')+})++test('bounds startup and termination, preserves permission failures, and isolates restarts', () => {+ vi.useFakeTimers()+ try {+ const first = new FakeChild()+ const second = new FakeChild()+ const spawn = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second)+ const statuses: CommandScreenshotStatus[] = []+ const captures: CommandScreenshotCapture[] = []+ const monitor = new CommandScreenshotMonitor({+ platform: 'darwin', spawn, startupTimeoutMs: 100, stopTimeoutMs: 50,+ })+ monitor.start(value => captures.push(value), value => statuses.push(value), true)+ assert.deepEqual(spawn.mock.calls[0][1], ['--request-permission'])+ first.stdout.write('{"type":"error","code":"permission-required"}\n')+ assert.deepEqual(statuses.at(-1), { type: 'error', code: 'permission-required' })+ assert.equal(first.stdin.writableEnded, true)+ monitor.start(value => captures.push(value), value => statuses.push(value))+ first.stdout.write('{"type":"ready"}\n{"type":"capture","windowId":1,"width":1,"height":1}\n')+ assert.deepEqual(captures, [])+ vi.advanceTimersByTime(50)+ assert.deepEqual(first.kill.mock.calls, [['SIGTERM'], ['SIGKILL']])+ first.emit('close', null, 'SIGKILL')+ assert.deepEqual(statuses.at(-1), { type: 'starting' })+ vi.advanceTimersByTime(50)+ assert.deepEqual(statuses.at(-1), { type: 'error', code: 'unavailable' })+ assert.equal(second.kill.mock.calls[0]?.[0], 'SIGTERM')+ second.emit('close', 0, null)+ assert.equal(vi.getTimerCount(), 0)+ assert.equal(second.listenerCount('error'), 0)+ } finally {+ vi.useRealTimers()+ }+})++test('stopping from the starting callback cancels the child before it can become ready', () => {+ const child = new FakeChild()+ const statuses: CommandScreenshotStatus[] = []+ const monitor = new CommandScreenshotMonitor({ platform: 'darwin', spawn: () => child })+ monitor.start(() => assert.fail('stopped monitor delivered a capture'), status => {+ statuses.push(status)+ if (status.type === 'starting') {+ monitor.stop()+ }+ })+ assert.equal(child.kill.mock.calls[0]?.[0], 'SIGTERM')+ child.stdout.write('{"type":"ready"}\n')+ child.emit('close', 0, null)+ assert.deepEqual(statuses, [{ type: 'starting' }, { type: 'stopped' }])+})++test.skipIf(process.platform !== 'darwin')('native state machine requires distinct keys, a clean chord and full release', () => {+ const dir = mkdtempSync(resolve(tmpdir(), 'hermes-command-monitor-test-'))+ try {+ const fixture = resolve(dir, 'gesture.m')+ const binary = resolve(dir, 'gesture')+ // Compile the real state machine; no posted input events, screen pixels or TCC prompts.+ writeFileSync(fixture, `+#define COMMAND_SCREENSHOT_MONITOR_TEST 1+#include "${resolve(import.meta.dirname, 'native/command-screenshot-monitor.m')}"+#include <assert.h>+static const CGEventFlags L = kCGEventFlagMaskCommand | NX_DEVICELCMDKEYMASK;+static const CGEventFlags R = kCGEventFlagMaskCommand | NX_DEVICERCMDKEYMASK;+static const CGEventFlags B = kCGEventFlagMaskCommand | NX_DEVICELCMDKEYMASK | NX_DEVICERCMDKEYMASK;+static bool flags(CommandGesture *s, CGKeyCode key, CGEventFlags f) {+ return CommandGestureUpdate(s, kCGEventFlagsChanged, key, f, false);+}+int main(void) { @autoreleasepool {+ CommandGesture s = {0};+ assert(!flags(&s, 55, L));+ assert(!flags(&s, 55, L)); // duplicate left Command is not the right Command+ assert(flags(&s, 54, B)); // capture immediately on the second physical press+ assert(!flags(&s, 54, L));+ assert(!flags(&s, 54, B));+ assert(!flags(&s, 54, L)); // one release does not re-arm+ assert(!flags(&s, 55, 0));+ assert(!flags(&s, 54, R));+ assert(flags(&s, 55, B));+ assert(!flags(&s, 55, R));+ assert(!flags(&s, 54, 0));+ for (int phase = 0; phase < 2; phase++) {+ s = (CommandGesture){0};+ if (phase == 0) CommandGestureUpdate(&s, kCGEventKeyDown, 0, 0, false);+ flags(&s, 55, L);+ if (phase == 1) CommandGestureUpdate(&s, kCGEventKeyDown, 0, L, false);+ assert(!flags(&s, 54, B));+ CommandGestureUpdate(&s, kCGEventKeyUp, 0, B, false);+ assert(!flags(&s, 54, L));+ assert(!flags(&s, 55, 0));+ flags(&s, 55, L);+ assert(flags(&s, 54, B));+ assert(!flags(&s, 54, L));+ flags(&s, 55, 0);+ }+ s = (CommandGesture){0};+ flags(&s, 55, L);+ CommandGestureUpdate(&s, kCGEventKeyUp, 0, L, false); // key was held before startup+ assert(!flags(&s, 54, B));+ s = (CommandGesture){0};+ flags(&s, 55, L);+ assert(flags(&s, 54, B));+ assert(!flags(&s, 54, B)); // repeat while held never triggers again+ assert(!CommandGestureUpdate(&s, kCGEventKeyDown, 0, B, true));+ assert(!flags(&s, 54, L)); // later keys cannot retroactively cancel the capture+ CGEventFlags modifiers[] = { kCGEventFlagMaskShift, kCGEventFlagMaskControl,+ kCGEventFlagMaskAlternate, kCGEventFlagMaskSecondaryFn, kCGEventFlagMaskAlphaShift };+ for (unsigned i = 0; i < sizeof(modifiers) / sizeof(*modifiers); i++) {+ s = (CommandGesture){0};+ flags(&s, 55, L | modifiers[i]);+ assert(!flags(&s, 54, B | modifiers[i]));+ flags(&s, 56, B);+ assert(!flags(&s, 54, L));+ assert(!flags(&s, 55, 0));+ }+ s = (CommandGesture){0};+ flags(&s, 55, kCGEventFlagMaskCommand);+ flags(&s, 54, kCGEventFlagMaskCommand);+ assert(!flags(&s, 54, 0)); // aggregate flags cannot prove two physical keys+ s = (CommandGesture){0};+ flags(&s, 54, B); // starting in the middle of a held chord must not arm+ assert(!flags(&s, 54, L));+ NSDictionary *(^window)(int, int, int, bool, double) = ^NSDictionary *(int wid, int pid, int layer, bool visible, double width) {+ return @{ (id)kCGWindowNumber: @(wid), (id)kCGWindowOwnerPID: @(pid),+ (id)kCGWindowLayer: @(layer), (id)kCGWindowIsOnscreen: @(visible), (id)kCGWindowAlpha: @1,+ (id)kCGWindowBounds: @{ @"X": @0, @"Y": @0, @"Width": @(width), @"Height": @200 } };+ };+ NSArray *windows = @[window(1, 42, 20, true, 100), window(2, 90, 0, true, 100),+ window(3, 42, 0, false, 100), window(4, 42, 0, true, 0),+ window(5, 42, 0, true, 300), window(6, 42, 0, true, 400)];+ NSDictionary *capture = CommandCaptureWindow(windows, 42);+ assert([capture[@"windowId"] intValue] == 5);+ assert([capture[@"width"] intValue] == 300 && [capture[@"height"] intValue] == 200);+ assert(CommandCaptureWindow(windows, 123) == nil); // never capture another app or a display+ assert(CommandCaptureWindow(windows, 0) == nil);+ puts("native gesture assertions passed");+} return 0; }+`)+ execFileSync('xcrun', ['clang', '-fobjc-arc', '-fblocks', '-framework', 'Cocoa', '-framework', 'CoreGraphics', fixture, '-o', binary], { timeout: 30_000 })+ assert.equal(execFileSync(binary, [], { encoding: 'utf8', timeout: 5_000 }).trim(), 'native gesture assertions passed')+ } finally {+ rmSync(dir, { recursive: true, force: true })+ }+}, 40_000)++test.skipIf(process.platform !== 'darwin')('builds a universal helper with a read-only permission check and real controller lifecycle', async () => {+ const dir = mkdtempSync(resolve(tmpdir(), 'hermes-command-monitor-build-'))+ try {+ const script = resolve(import.meta.dirname, '../scripts/build-command-screenshot-monitor.mjs')+ execFileSync(process.execPath, [script, '--out-dir', resolve(dir, 'dist')], { timeout: 60_000 })+ const binary = resolveCommandScreenshotMonitorPath(dir)+ const architectures = execFileSync('xcrun', ['lipo', '-archs', binary], { encoding: 'utf8' }).trim().split(/\s+/).sort()+ assert.deepEqual(architectures, ['arm64', 'x86_64'])+ const result = spawnSync(binary, ['--check'], { encoding: 'utf8', timeout: 5_000 })+ assert.equal(result.error, undefined)+ assert.equal(result.stderr, '')+ const permission = JSON.parse(result.stdout)+ assert.deepEqual(permission, result.status === 0+ ? { type: 'ready' } : { type: 'error', code: 'permission-required' })+ assert.ok(result.status === 0 || result.status === 2)+ const invalid = spawnSync(binary, ['--check', '--request-permission'], { encoding: 'utf8', timeout: 5_000 })+ assert.equal(invalid.status, 64)+ assert.deepEqual(JSON.parse(invalid.stdout), { type: 'error', code: 'unavailable' })+ let closed: Promise<NodeJS.Signals | null> | undefined+ const monitor = new CommandScreenshotMonitor({+ appPath: dir,+ spawn: (command, args, options) => {+ const child = nodeSpawn(command, args, options)+ closed = new Promise(settle => child.once('close', (_code, signal) => settle(signal)))+ return child+ },+ })+ const statuses: CommandScreenshotStatus[] = []+ const terminal = await new Promise<CommandScreenshotStatus>((settle, reject) => {+ const timeout = setTimeout(() => { monitor.stop(); reject(new Error('real monitor did not settle')) }, 10_000)+ monitor.start(() => {}, status => {+ statuses.push(status)+ if (status.type === 'ready' || status.type === 'error') {+ clearTimeout(timeout)+ settle(status)+ }+ })+ })+ assert.equal(statuses[0].type, 'starting')+ if (permission.type === 'error') {+ assert.deepEqual(terminal, permission)+ }+ monitor.stop()+ assert.ok(closed)+ assert.notEqual(await closed, 'SIGKILL') // the real helper exits without escalation+ } finally {+ rmSync(dir, { recursive: true, force: true })+ }+}, 75_000)diff --git a/apps/desktop/electron/command-screenshot-monitor.ts b/apps/desktop/electron/command-screenshot-monitor.tsnew file mode 100644index 00000000000..2e7436d258d--- /dev/null+++ b/apps/desktop/electron/command-screenshot-monitor.ts@@ -0,0 +1,189 @@+import { spawn as nodeSpawn, type SpawnOptions } from 'node:child_process'+import type { EventEmitter } from 'node:events'+import { dirname, resolve } from 'node:path'+import type { Readable, Writable } from 'node:stream'+import { fileURLToPath } from 'node:url'++import type { ScreenshotWindow } from './command-screenshot-types'++export interface CommandScreenshotCapture extends ScreenshotWindow {+ type: 'capture'+}++export type CommandScreenshotStatus =+ | { type: 'starting' | 'ready' | 'stopped' }+ | { type: 'error'; code: 'permission-required' | 'unavailable' }++interface MonitorChild extends EventEmitter {+ stdin: Writable | null+ stdout: Readable | null+ kill(signal?: NodeJS.Signals): boolean+}++interface MonitorOptions {+ appPath?: string+ platform?: NodeJS.Platform+ spawn?: (command: string, args: string[], options: SpawnOptions) => MonitorChild+ startupTimeoutMs?: number+ stopTimeoutMs?: number+}++export function resolveCommandScreenshotMonitorPath(+ appPath = resolve(dirname(fileURLToPath(import.meta.url)), '..'),+): string {+ // Executables cannot run inside ASAR. dist/** is already explicitly unpacked.+ return resolve(appPath, 'dist/native/command-screenshot-monitor')+ .replace(/\.asar(?=[/\\])/g, '.asar.unpacked')+}++function parseMessage(line: string): CommandScreenshotCapture | CommandScreenshotStatus | null {+ let value: unknown+ try {+ value = JSON.parse(line)+ } catch {+ return null+ }+ if (!value || typeof value !== 'object') {+ return null+ }+ const message = value as Record<string, unknown>+ if (message.type === 'ready') {+ return { type: 'ready' }+ }+ if (message.type === 'error' && (message.code === 'permission-required' || message.code === 'unavailable')) {+ return { type: 'error', code: message.code }+ }+ if (message.type !== 'capture') {+ return null+ }+ const { windowId, width, height } = message+ if (typeof windowId !== 'number' || !Number.isInteger(windowId) || windowId <= 0 || windowId > 0xffffffff+ || typeof width !== 'number' || !Number.isFinite(width) || width <= 0+ || typeof height !== 'number' || !Number.isFinite(height) || height <= 0) {+ return null+ }+ return { type: 'capture', windowId, width, height }+}++/** Own one passive native monitor. Call stop() before app quit or disabling the gesture. */+export class CommandScreenshotMonitor {+ private cleanup: (() => void) | undefined++ constructor(private readonly options: MonitorOptions = {}) {}++ /** Only explicit user intent may pass requestPermission=true (opens the macOS prompt). */+ start(+ onCapture: (capture: CommandScreenshotCapture) => void,+ onStatus: (status: CommandScreenshotStatus) => void,+ requestPermission = false,+ ): void {+ this.stop()+ if ((this.options.platform ?? process.platform) !== 'darwin') {+ onStatus({ type: 'error', code: 'unavailable' })+ return+ }+ let child: MonitorChild+ try {+ child = (this.options.spawn ?? nodeSpawn)(resolveCommandScreenshotMonitorPath(this.options.appPath),+ requestPermission ? ['--request-permission'] : [],+ { stdio: ['pipe', 'pipe', 'ignore'], shell: false, detached: false, windowsHide: true })+ } catch {+ onStatus({ type: 'error', code: 'unavailable' })+ return+ }+ let ready = false+ let active = true+ let pending = ''+ let killTimer: ReturnType<typeof setTimeout> | undefined+ const startupTimer = setTimeout(() => fail(), this.options.startupTimeoutMs ?? (requestPermission ? 60_000 : 5_000))+ startupTimer.unref()+ const dispose = () => {+ active = false+ pending = ''+ clearTimeout(startupTimer)+ child.stdout?.removeListener('data', onData)+ if (this.cleanup === stop) {+ this.cleanup = undefined+ }+ }+ const terminate = (status: CommandScreenshotStatus) => {+ if (!active) {+ return+ }+ dispose()+ child.stdin?.end() // EOF also stops the helper if the parent exits unexpectedly.+ child.kill('SIGTERM')+ killTimer = setTimeout(() => child.kill('SIGKILL'), this.options.stopTimeoutMs ?? 1_000)+ killTimer.unref()+ onStatus(status)+ }+ const fail = () => terminate({ type: 'error', code: 'unavailable' })+ const onData = (chunk: Buffer | string) => {+ if (!active) {+ return+ }+ if (chunk.length > 65_536) {+ fail()+ return+ }+ pending += chunk.toString()+ const lines = pending.split('\n')+ pending = lines.pop() ?? ''+ if (pending.length > 4_096) {+ fail()+ return+ }+ for (const line of lines) {+ if (!active) {+ break+ }+ if (line.length > 4_096) {+ fail()+ break+ }+ const message = parseMessage(line)+ if (!message) {+ continue+ }+ if (message.type === 'capture') {+ if (ready) {+ onCapture(message)+ }+ } else if (message.type === 'ready' && !ready) {+ ready = true+ clearTimeout(startupTimer)+ onStatus(message)+ } else if (message.type === 'error') {+ terminate(message)+ }+ }+ }+ const onClose = () => {+ const unexpected = active+ dispose()+ clearTimeout(killTimer)+ child.removeListener('close', onClose)+ child.removeListener('error', fail)+ child.stdin?.removeListener('error', fail)+ child.stdout?.removeListener('error', fail)+ if (unexpected) {+ onStatus({ type: 'error', code: 'unavailable' })+ }+ }+ const stop = () => terminate({ type: 'stopped' })+ this.cleanup = stop+ child.stdout?.on('data', onData)+ child.stdout?.on('error', fail)+ child.stdin?.on('error', fail)+ child.once('close', onClose)+ child.on('error', fail)+ onStatus({ type: 'starting' })+ if (!child.stdout || !child.stdin) {+ fail()+ }+ }++ stop(): void {+ this.cleanup?.()+ }+}diff --git a/apps/desktop/electron/command-screenshot-types.ts b/apps/desktop/electron/command-screenshot-types.tsnew file mode 100644index 00000000000..fbce4224d58--- /dev/null+++ b/apps/desktop/electron/command-screenshot-types.ts@@ -0,0 +1,23 @@+export interface ScreenshotStatus {+ enabled: boolean+ state: 'disabled' | 'starting' | 'ready' | 'input-permission' | 'screen-permission' | 'unavailable'+}++export interface ScreenshotWindow {+ windowId: number+ width: number+ height: number+}++export type ScreenshotResult =+ | { ok: true; png: Uint8Array }+ | { ok: false; reason: 'expired' | 'screen-permission' | 'unavailable' }++export interface ScreenshotApi {+ getSettings(): Promise<ScreenshotStatus>+ setEnabled(enabled: boolean): Promise<ScreenshotStatus>+ openPermissionSettings(kind: 'input' | 'screen'): Promise<void>+ onStatus(callback: (status: ScreenshotStatus) => void): () => void+ onRequest(callback: (requestId: string) => void): () => void+ capture(requestId: string): Promise<ScreenshotResult>+}diff --git a/apps/desktop/electron/native/command-screenshot-monitor.m b/apps/desktop/electron/native/command-screenshot-monitor.mnew file mode 100644index 00000000000..bce1607fdd6--- /dev/null+++ b/apps/desktop/electron/native/command-screenshot-monitor.m@@ -0,0 +1,187 @@+// Passive modifier gesture detection. Never reads characters, activates an app,+// captures pixels, or writes files. stdout is a bounded JSON-lines protocol.+#import <Cocoa/Cocoa.h>+#import <CoreGraphics/CoreGraphics.h>+#import <IOKit/hidsystem/IOLLEvent.h>+#include <stdbool.h>+#include <stdio.h>++// Only physical key state is retained, not characters or an event history.+typedef struct {+ bool left;+ bool right;+ bool blocked;+ bool keys[128];+ unsigned heldKeys;+} CommandGesture;++static bool CommandGestureUpdate(CommandGesture *state, CGEventType type,+ CGKeyCode key, CGEventFlags flags, bool repeat) {+ bool left = (flags & NX_DEVICELCMDKEYMASK) != 0;+ bool right = (flags & NX_DEVICERCMDKEYMASK) != 0;+ bool any = left || right || (flags & kCGEventFlagMaskCommand);+ bool wasBoth = state->left && state->right;+ bool commandEvent = type == kCGEventFlagsChanged && (key == 54 || key == 55);+ CGEventFlags forbidden = kCGEventFlagMaskAlphaShift | kCGEventFlagMaskShift+ | kCGEventFlagMaskControl | kCGEventFlagMaskAlternate | kCGEventFlagMaskSecondaryFn+ | kCGEventFlagMaskHelp | kCGEventFlagMaskNumericPad;++ if (type == kCGEventKeyDown) {+ state->blocked = true;+ if (key < 128 && !state->keys[key]) { state->keys[key] = true; state->heldKeys++; }+ } else if (type == kCGEventKeyUp) {+ state->blocked = true; // also reject keys already held when monitoring started+ if (key < 128 && state->keys[key]) {+ state->keys[key] = false;+ state->heldKeys--;+ }+ }+ if ((flags & forbidden) || state->heldKeys || repeat+ || (any && !(left || right))) state->blocked = true;++ // Capture on the clean second physical press, while both keys are still down.+ // Subsequent letters cannot retroactively cancel an already authorized capture.+ bool capture = false;+ if (commandEvent && left && right && !wasBoth) {+ // Both physical transitions must be seen. An initial or ambiguous held chord+ // is not evidence of a gesture and is ignored until both keys are released.+ bool secondPress = (key == 54 && state->left && !state->right)+ || (key == 55 && state->right && !state->left);+ capture = secondPress && !state->blocked;+ state->blocked = true; // no repeat or partial-release re-arming+ }+ state->left = left;+ state->right = right;+ if (!any) state->blocked = state->heldKeys > 0 || (flags & forbidden) != 0;+ return capture;+}++static NSDictionary *CommandCaptureWindow(NSArray *windows, pid_t frontmostPID) {+ if (frontmostPID <= 0) return nil;+ // CGWindowListCopyWindowInfo returns front-to-back order. Restrict to the+ // foreground app, not an overlay or a background window behind the desktop.+ for (NSDictionary *window in windows) {+ NSNumber *pid = window[(id)kCGWindowOwnerPID];+ NSNumber *layer = window[(id)kCGWindowLayer];+ NSNumber *wid = window[(id)kCGWindowNumber];+ if (!pid || pid.intValue != frontmostPID || !layer || layer.intValue != 0+ || ![window[(id)kCGWindowIsOnscreen] boolValue]+ || [window[(id)kCGWindowAlpha] doubleValue] <= 0+ || !wid || wid.longLongValue <= 0 || wid.unsignedLongLongValue > UINT32_MAX) continue;+ NSDictionary *bounds = window[(id)kCGWindowBounds];+ CGRect rect;+ if (![bounds isKindOfClass:NSDictionary.class]+ || !CGRectMakeWithDictionaryRepresentation((__bridge CFDictionaryRef)bounds, &rect)+ || !isfinite(rect.size.width) || !isfinite(rect.size.height)+ || rect.size.width <= 0 || rect.size.height <= 0) continue;+ return @{ @"type": @"capture", @"windowId": wid,+ @"width": @(rect.size.width), @"height": @(rect.size.height) };+ }+ return nil;+}++#ifndef COMMAND_SCREENSHOT_MONITOR_TEST+#include <dispatch/dispatch.h>+#include <fcntl.h>+#include <signal.h>+#include <unistd.h>++static void EmitJSON(NSDictionary *message) {+ NSMutableData *line = [[NSJSONSerialization dataWithJSONObject:message options:0 error:nil] mutableCopy];+ [line appendBytes:"\n" length:1];+ // Never block the input callback on a stalled parent. Every protocol message+ // fits a single atomic pipe write; a closed/full pipe ends this helper.+ if (!line || line.length > 512 || write(STDOUT_FILENO, line.bytes, line.length) != (ssize_t)line.length) _exit(0);+}++static void EmitError(NSString *code) {+ EmitJSON(@{ @"type": @"error", @"code": code });+}++static CGEventRef ObserveEvent(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *info) {+ (void)proxy;+ @autoreleasepool {+ if (type == kCGEventTapDisabledByTimeout || type == kCGEventTapDisabledByUserInput) {+ // Missed input makes physical state unknowable. Fail closed, with no+ // automatic restart loop that could repeatedly fight permission revocation.+ EmitError(CGPreflightListenEventAccess() ? @"unavailable" : @"permission-required");+ CFRunLoopStop(CFRunLoopGetMain());+ return event;+ }+ bool capture = CommandGestureUpdate(info, type,+ (CGKeyCode)CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode),+ CGEventGetFlags(event), CGEventGetIntegerValueField(event, kCGKeyboardEventAutorepeat) != 0);+ if (capture) {+ pid_t pid = NSWorkspace.sharedWorkspace.frontmostApplication.processIdentifier;+ NSArray *windows = CFBridgingRelease(CGWindowListCopyWindowInfo(+ kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID));+ NSDictionary *target = CommandCaptureWindow(windows, pid);+ // The desktop or an app without a normal window is not a capture target.+ // A missed target does not broaden into a full-display capture.+ if (target) EmitJSON(target);+ }+ return event; // listen-only: do not consume or alter another app's input.+ }+}++int main(int argc, const char *argv[]) {+ @autoreleasepool {+ signal(SIGPIPE, SIG_IGN);+ int stdoutFlags = fcntl(STDOUT_FILENO, F_GETFL);+ if (stdoutFlags >= 0) fcntl(STDOUT_FILENO, F_SETFL, stdoutFlags | O_NONBLOCK);+ bool check = argc == 2 && strcmp(argv[1], "--check") == 0;+ bool request = argc == 2 && strcmp(argv[1], "--request-permission") == 0;+ if (argc > 1 && !check && !request) { EmitError(@"unavailable"); return 64; }+ bool allowed = CGPreflightListenEventAccess();+ if (!allowed && request) allowed = CGRequestListenEventAccess();+ if (!allowed) { EmitError(@"permission-required"); return 2; }+ if (check) { EmitJSON(@{ @"type": @"ready" }); return 0; }++ CommandGesture gesture = {0};+ // One initial modifier snapshot, not key polling: a chord held before this+ // process started must finish before a new gesture can arm.+ CGEventFlags initial = CGEventSourceFlagsState(kCGEventSourceStateCombinedSessionState);+ gesture.left = (initial & NX_DEVICELCMDKEYMASK) != 0;+ gesture.right = (initial & NX_DEVICERCMDKEYMASK) != 0;+ gesture.blocked = (initial & kCGEventFlagMaskCommand) != 0;+ CGEventMask mask = CGEventMaskBit(kCGEventFlagsChanged)+ | CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp);+ CFMachPortRef tap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap,+ kCGEventTapOptionListenOnly, mask, ObserveEvent, &gesture);+ if (!tap) { EmitError(CGPreflightListenEventAccess() ? @"unavailable" : @"permission-required"); return 3; }+ CFRunLoopSourceRef source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0);+ if (!source) { CFMachPortInvalidate(tap); CFRelease(tap); EmitError(@"unavailable"); return 3; }+ CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopCommonModes);++ // The parent's pipe EOF and termination signals all take the same clean+ // teardown path. There are no timers or background key-state polling loops.+ signal(SIGTERM, SIG_IGN);+ signal(SIGINT, SIG_IGN);+ dispatch_source_t term = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGTERM, 0, dispatch_get_main_queue());+ dispatch_source_t interrupt = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGINT, 0, dispatch_get_main_queue());+ dispatch_source_t input = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, STDIN_FILENO, 0, dispatch_get_main_queue());+ dispatch_block_t stop = ^{ CFRunLoopStop(CFRunLoopGetMain()); };+ dispatch_source_set_event_handler(term, stop);+ dispatch_source_set_event_handler(interrupt, stop);+ dispatch_source_set_event_handler(input, ^{+ char byte;+ if (read(STDIN_FILENO, &byte, 1) <= 0) CFRunLoopStop(CFRunLoopGetMain());+ });+ dispatch_resume(term);+ dispatch_resume(interrupt);+ dispatch_resume(input);+ CGEventTapEnable(tap, true);+ EmitJSON(@{ @"type": @"ready" });+ CFRunLoopRun();+ dispatch_source_cancel(input);+ dispatch_source_cancel(interrupt);+ dispatch_source_cancel(term);+ CGEventTapEnable(tap, false);+ CFMachPortInvalidate(tap);+ CFRunLoopRemoveSource(CFRunLoopGetMain(), source, kCFRunLoopCommonModes);+ CFRelease(source);+ CFRelease(tap);+ return 0;+ }+}+#endifdiff --git a/apps/desktop/scripts/build-command-screenshot-monitor.mjs b/apps/desktop/scripts/build-command-screenshot-monitor.mjsnew file mode 100644index 00000000000..7aef6368694--- /dev/null+++ b/apps/desktop/scripts/build-command-screenshot-monitor.mjs@@ -0,0 +1,39 @@+#!/usr/bin/env node+// Build-time only: the shipped app never needs clang or Xcode tools.+import { execFileSync } from 'node:child_process'+import { chmodSync, mkdirSync, renameSync, rmSync } from 'node:fs'+import { dirname, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'++const script = fileURLToPath(import.meta.url)+const root = resolve(dirname(script), '..')++export function buildCommandScreenshotMonitor({ distDir = resolve(root, 'dist') } = {}) {+ if (process.platform !== 'darwin') return null+ const output = resolve(distDir, 'native/command-screenshot-monitor')+ const staging = `${output}.${process.pid}.tmp`+ mkdirSync(dirname(output), { recursive: true })+ try {+ execFileSync('xcrun', [+ 'clang', '-arch', 'arm64', '-arch', 'x86_64', '-mmacosx-version-min=11.0',+ '-fobjc-arc', '-fblocks', '-O2', '-Wall', '-Wextra',+ '-framework', 'Cocoa', '-framework', 'CoreGraphics',+ resolve(root, 'electron/native/command-screenshot-monitor.m'), '-o', staging,+ ], { stdio: 'inherit', timeout: 120_000 })+ chmodSync(staging, 0o755)+ renameSync(staging, output)+ // electron-builder signs this Mach-O with the app; dist/** is already asarUnpack.+ console.log(`built ${output} (arm64 + x86_64)`)+ return output+ } finally {+ rmSync(staging, { force: true })+ }+}++if (process.argv[1] && resolve(process.argv[1]) === script) {+ const args = process.argv.slice(2)+ if (args.length && (args.length !== 2 || args[0] !== '--out-dir')) {+ throw new Error('Usage: build-command-screenshot-monitor.mjs [--out-dir PATH]')+ }+ buildCommandScreenshotMonitor(args.length ? { distDir: resolve(args[1]) } : {})+}diff --git a/apps/desktop/scripts/bundle-electron-main.mjs b/apps/desktop/scripts/bundle-electron-main.mjsindex 4cd93075b2f..b613b98ca2c 100644--- a/apps/desktop/scripts/bundle-electron-main.mjs+++ b/apps/desktop/scripts/bundle-electron-main.mjs@@ -13,11 +13,14 @@ import { build } from 'esbuild'import { resolve, dirname } from 'node:path'import { fileURLToPath } from 'node:url'import { mkdirSync } from 'node:fs'+import { buildCommandScreenshotMonitor } from './build-command-screenshot-monitor.mjs'const here = dirname(fileURLToPath(import.meta.url))const root = resolve(here, '..')const distDir = resolve(root, 'dist')mkdirSync(distDir, { recursive: true })+// Stage for both --dev and release bundles; non-mac hosts skip this helper.+buildCommandScreenshotMonitor({ distDir })const mainEntry = resolve(root, 'electron/main.ts')const mainOut = resolve(distDir, 'electron-main.mjs')