The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): detect clean modifier taps with passive native listeners
brooklyn!9ff6e071fa22
diff --git a/apps/desktop/electron/hud-modifier-monitor.test.ts b/apps/desktop/electron/hud-modifier-monitor.test.tsnew file mode 100644index 00000000000..64512559c47--- /dev/null+++ b/apps/desktop/electron/hud-modifier-monitor.test.ts@@ -0,0 +1,74 @@+import assert from 'node:assert/strict'+import { EventEmitter } from 'node:events'+import { PassThrough } from 'node:stream'++import { test, vi } from 'vitest'++import { hudModifierMonitorSupported, resolveHudModifierMonitorPath } from './hud-modifier-monitor'+import { NativeGestureMonitor, type NativeGestureStatus } from './native-gesture-monitor'++class Child extends EventEmitter {+ stdin = new PassThrough()+ stdout = new PassThrough()+ kill = vi.fn((_signal?: NodeJS.Signals) => true)+}++test('native transport gates gestures on ready, bounds framing and isolates replacement children', () => {+ vi.useFakeTimers()++ try {+ const first = new Child()+ const second = new Child()+ const spawn = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second)+ const statuses: NativeGestureStatus[] = []+ let summons = 0++ const monitor = new NativeGestureMonitor({+ path: '/helper',+ parseGesture: value => (value.type === 'summon' ? true : null),+ spawn,+ startupTimeoutMs: 100,+ stopTimeoutMs: 50+ })++ monitor.start(+ () => summons++,+ status => statuses.push(status)+ )+ assert.deepEqual(spawn.mock.calls[0][1], [])+ first.stdout.write('{"type":"summon"}\n{"type":"rea')+ assert.equal(summons, 0)+ first.stdout.write('dy"}\n{"type":"key","value":"discard"}\n{"type":"summon"}\n')+ assert.equal(summons, 1)+ monitor.start(+ () => summons++,+ status => statuses.push(status),+ true+ )+ assert.deepEqual(spawn.mock.calls[1][1], ['--request-permission'])+ first.stdout.write('{"type":"summon"}\n')+ first.emit('close', 0, null)+ second.stdout.write('x'.repeat(4097))+ assert.deepEqual(statuses.at(-1), { type: 'error', code: 'unavailable' })+ vi.advanceTimersByTime(50)+ assert.deepEqual(second.kill.mock.calls, [['SIGTERM'], ['SIGKILL']])+ second.emit('close', 0, null)+ assert.equal(summons, 1)+ assert.equal(vi.getTimerCount(), 0)+ } finally {+ vi.useRealTimers()+ }+})++test('support policy excludes Wayland even when Xwayland supplies DISPLAY', () => {+ assert.equal(hudModifierMonitorSupported('linux', { DISPLAY: ':0', WAYLAND_DISPLAY: 'wayland-0' }), false)+ assert.equal(hudModifierMonitorSupported('linux', { DISPLAY: ':0', XDG_SESSION_TYPE: 'wayland' }), false)+ assert.equal(hudModifierMonitorSupported('linux', { DISPLAY: ':0', XDG_SESSION_TYPE: 'x11' }), true)+ assert.equal(hudModifierMonitorSupported('linux', {}), false)+ assert.equal(hudModifierMonitorSupported('darwin', {}), true)+ assert.equal(hudModifierMonitorSupported('win32', {}), true)+ assert.equal(hudModifierMonitorSupported('freebsd', {}), false)+ const path = resolveHudModifierMonitorPath('/apps/app.asar')+ assert.ok(path.includes('app.asar.unpacked'))+ assert.ok(path.endsWith(process.platform === 'win32' ? 'hud-modifier-monitor.exe' : 'hud-modifier-monitor'))+})diff --git a/apps/desktop/electron/hud-modifier-monitor.ts b/apps/desktop/electron/hud-modifier-monitor.tsnew file mode 100644index 00000000000..f8aa97f250e--- /dev/null+++ b/apps/desktop/electron/hud-modifier-monitor.ts@@ -0,0 +1,56 @@+import { dirname, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'++import { NativeGestureMonitor, type NativeGestureStatus } from './native-gesture-monitor'++export type HudModifierStatus = NativeGestureStatus++/** A session capability, not a claim that Xwayland can observe Wayland apps. */+export function hudModifierMonitorSupported(+ platform: NodeJS.Platform = process.platform,+ env: NodeJS.ProcessEnv = process.env+): boolean {+ return (+ platform === 'darwin' ||+ platform === 'win32' ||+ (platform === 'linux' && !!env.DISPLAY && !env.WAYLAND_DISPLAY && env.XDG_SESSION_TYPE?.toLowerCase() !== 'wayland')+ )+}++export function resolveHudModifierMonitorPath(+ appPath = resolve(dirname(fileURLToPath(import.meta.url)), '..')+): string {+ const binary = process.platform === 'win32' ? 'hud-modifier-monitor.exe' : 'hud-modifier-monitor'+ const target = `${process.platform}-${process.platform === 'darwin' ? 'universal' : process.arch}`++ return resolve(appPath, 'dist/native', target, binary).replace(/\.asar(?=[/\\])/g, '.asar.unpacked')+}++/** Input remains inside the native process; only readiness/errors and summon cross the pipe. */+export class HudModifierMonitor {+ private readonly monitor: NativeGestureMonitor<true>++ constructor({ appPath }: { appPath?: string } = {}) {+ this.monitor = new NativeGestureMonitor({+ path: resolveHudModifierMonitorPath(appPath),+ parseGesture: value => (value.type === 'summon' ? true : null)+ })+ }++ /** Request macOS Input Monitoring permission only after an explicit opt-in/retry. */+ start(onSummon: () => void, onStatus: (status: HudModifierStatus) => void, requestPermission = false): void {+ this.stop()++ if (!hudModifierMonitorSupported()) {+ onStatus({ type: 'error', code: 'unavailable' })++ return+ }++ this.monitor.start(onSummon, onStatus, requestPermission)+ }++ stop(): void {+ this.monitor.stop()+ }+}diff --git a/apps/desktop/electron/hud-modifier-native.test.ts b/apps/desktop/electron/hud-modifier-native.test.tsnew file mode 100644index 00000000000..6f887c334a2--- /dev/null+++ b/apps/desktop/electron/hud-modifier-native.test.ts@@ -0,0 +1,103 @@+import assert from 'node:assert/strict'+import { execFileSync, spawnSync } from 'node:child_process'+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { resolve } from 'node:path'++import { test } from 'vitest'++import { HudModifierMonitor, type HudModifierStatus, resolveHudModifierMonitorPath } from './hud-modifier-monitor'++test.skipIf(process.platform !== 'darwin')(+ 'executes native gesture adapters and real controller without posting input',+ async () => {+ const dir = mkdtempSync(resolve(tmpdir(), 'hermes-hud-native-'))+ const native = resolve(import.meta.dirname, 'native')++ try {+ const gesture = resolve(dir, 'gesture')+ execFileSync('xcrun', [+ '--sdk',+ 'macosx',+ 'clang',+ '-std=c11',+ '-Wall',+ '-Wextra',+ '-Werror',+ resolve(native, 'hud-modifier-gesture.test.c'),+ '-o',+ gesture+ ])+ assert.match(execFileSync(gesture, [], { encoding: 'utf8', timeout: 5_000 }), /assertions passed/)+ const adapter = resolve(dir, 'adapter')+ execFileSync('xcrun', [+ '--sdk',+ 'macosx',+ 'clang',+ '-fobjc-arc',+ '-fblocks',+ '-Wall',+ '-Wextra',+ '-Werror',+ '-framework',+ 'Cocoa',+ '-framework',+ 'CoreGraphics',+ resolve(native, 'hud-modifier-monitor.test.m'),+ '-o',+ adapter+ ])+ assert.match(execFileSync(adapter, [], { encoding: 'utf8', timeout: 5_000 }), /assertions passed/)+ execFileSync(+ process.execPath,+ [resolve(import.meta.dirname, '../scripts/build-hud-modifier-monitor.mjs'), '--out-dir', resolve(dir, 'dist')],+ { timeout: 60_000 }+ )+ const binary = resolveHudModifierMonitorPath(dir)+ assert.deepEqual(+ execFileSync('xcrun', ['lipo', '-archs', binary], { encoding: 'utf8' }).trim().split(/\s+/).sort(),+ ['arm64', 'x86_64']+ )+ const check = spawnSync(binary, ['--check'], { encoding: 'utf8', timeout: 5_000 })+ assert.equal(check.error, undefined)+ assert.equal(check.stderr, '')+ assert.ok(check.status === 0 || check.status === 2)+ const permission = JSON.parse(check.stdout)+ assert.deepEqual(+ permission,+ check.status === 0 ? { type: 'ready' } : { type: 'error', code: 'permission-required' }+ )+ 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' })+ const statuses: HudModifierStatus[] = []+ const monitor = new HudModifierMonitor({ appPath: dir })++ try {+ const status = await new Promise<HudModifierStatus>((settle, reject) => {+ const timer = setTimeout(() => reject(new Error('native helper did not settle')), 10_000)+ monitor.start(+ () => {},+ value => {+ statuses.push(value)++ if (value.type === 'ready' || value.type === 'error') {+ clearTimeout(timer)+ settle(value)+ }+ }+ )+ })++ assert.equal(statuses[0].type, 'starting')+ assert.deepEqual(status, permission)+ console.info(`HUD native check: ${JSON.stringify(status)}; no input posted`)+ } finally {+ monitor.stop()+ }+ } finally {+ rmSync(dir, { recursive: true, force: true })+ }+ },+ 75_000+)diff --git a/apps/desktop/electron/native/hud-modifier-gesture.h b/apps/desktop/electron/native/hud-modifier-gesture.hnew file mode 100644index 00000000000..6ea5cf5aff8--- /dev/null+++ b/apps/desktop/electron/native/hud-modifier-gesture.h@@ -0,0 +1,35 @@+#ifndef HERMES_HUD_MODIFIER_GESTURE_H+#define HERMES_HUD_MODIFIER_GESTURE_H+#include <stdbool.h>+#include <stdint.h>++// Only a summary of the current gesture survives an event; no input history.+// Bits 1/2 are the two target modifiers; bit 4 means any extra modifier.+typedef struct {+ unsigned modifiers;+ bool started;+ bool both;+ bool blocked;+ bool releasing;+ uint64_t began;+} HudModifierGesture;++static inline bool HudModifierUpdate(HudModifierGesture *s, unsigned modifiers,+ bool held, bool interrupted, uint64_t now) {+ if (held || interrupted || (modifiers & ~3u)) s->blocked = true;+ unsigned pressed = modifiers & ~s->modifiers;+ if (s->releasing && pressed) s->blocked = true;+ if (s->modifiers & ~modifiers) s->releasing = true;+ if (!s->modifiers && !s->blocked && (modifiers == 1 || modifiers == 2)) {+ s->started = true;+ s->began = now;+ }+ if (modifiers && !s->started) s->blocked = true;+ if (modifiers == 3 && s->started) s->both = true;+ bool summon = !modifiers && s->both && !s->blocked+ && now >= s->began && now - s->began <= 500;+ s->modifiers = modifiers;+ if (!modifiers && !held) *s = (HudModifierGesture){0};+ return summon;+}+#endifdiff --git a/apps/desktop/electron/native/hud-modifier-gesture.test.c b/apps/desktop/electron/native/hud-modifier-gesture.test.cnew file mode 100644index 00000000000..08e56068e09--- /dev/null+++ b/apps/desktop/electron/native/hud-modifier-gesture.test.c@@ -0,0 +1,59 @@+#include "hud-modifier-gesture.h"+#include <assert.h>+#include <stdio.h>++int main(void) {+ // Either press/release ordering is valid, but neither first release summons.+ for (unsigned first = 1; first <= 2; first++) {+ for (unsigned last = 1; last <= 2; last++) {+ HudModifierGesture s = {0};+ assert(!HudModifierUpdate(&s, first, false, false, 10));+ assert(!HudModifierUpdate(&s, 3, false, false, 20));+ assert(!HudModifierUpdate(&s, last, false, false, 30));+ assert(HudModifierUpdate(&s, 0, false, false, 40));+ assert(!HudModifierUpdate(&s, 0, false, false, 50));+ }+ }+ // A foreign event at any phase permanently cancels this attempt, even if+ // the foreign key/button is released before the target modifiers.+ for (int phase = 0; phase < 3; phase++) {+ HudModifierGesture s = {0};+ HudModifierUpdate(&s, 1, false, phase == 0, 10);+ HudModifierUpdate(&s, 3, false, phase == 1, 20);+ HudModifierUpdate(&s, 2, false, phase == 2, 30);+ assert(!HudModifierUpdate(&s, 0, false, false, 40));+ HudModifierUpdate(&s, 1, false, false, 50);+ HudModifierUpdate(&s, 3, false, false, 60);+ HudModifierUpdate(&s, 2, false, false, 70);+ assert(HudModifierUpdate(&s, 0, false, false, 80));+ }+ // Extra modifiers, held keys/buttons, and partial-release re-press cannot arm.+ for (int kind = 0; kind < 3; kind++) {+ HudModifierGesture s = {0};+ HudModifierUpdate(&s, 1, kind == 1, false, 10);+ HudModifierUpdate(&s, kind == 0 ? 7 : 3, kind == 1, false, 20);+ if (kind == 0) HudModifierUpdate(&s, 3, false, false, 25);+ HudModifierUpdate(&s, 2, false, false, 30);+ if (kind == 2) {+ HudModifierUpdate(&s, 3, false, false, 35);+ HudModifierUpdate(&s, 2, false, false, 36);+ }+ assert(!HudModifierUpdate(&s, 0, false, false, 40));+ }+ for (unsigned initial = 1; initial <= 3; initial++) {+ HudModifierGesture s = {0};+ HudModifierUpdate(&s, initial, true, true, 0);+ HudModifierUpdate(&s, 3, false, false, 10);+ HudModifierUpdate(&s, 2, false, false, 20);+ assert(!HudModifierUpdate(&s, 0, false, false, 30));+ }+ for (uint64_t duration = 500; duration <= 501; duration++) {+ HudModifierGesture s = {0};+ HudModifierUpdate(&s, 1, false, false, 10);+ HudModifierUpdate(&s, 3, false, false, 20);+ HudModifierUpdate(&s, 2, false, false, 30);+ assert(HudModifierUpdate(&s, 0, false, false, 10 + duration) == (duration == 500));+ }+ puts("native modifier gesture assertions passed");+ return 0;+}diff --git a/apps/desktop/electron/native/hud-modifier-monitor-win.c b/apps/desktop/electron/native/hud-modifier-monitor-win.cnew file mode 100644index 00000000000..451f1c229a6--- /dev/null+++ b/apps/desktop/electron/native/hud-modifier-monitor-win.c@@ -0,0 +1,122 @@+// Raw Input with INPUTSINK observes without hooks, grabs, or suppressing keys.+#define WIN32_LEAN_AND_MEAN+#define _WIN32_WINNT 0x0601+#include <windows.h>+#include <stdio.h>+#include <string.h>+#include "hud-modifier-gesture.h"++static HudModifierGesture gesture;+static bool keys[256]; // Current physical state, not a log or character buffer.+static unsigned buttons;+static HANDLE output;+static void Emit(const char *line) {+ DWORD written = 0, size = (DWORD)strlen(line);+ if (!WriteFile(output, line, size, &written, NULL) || written != size) ExitProcess(0);+}+static void Unavailable(void) { Emit("{\"type\":\"error\",\"code\":\"unavailable\"}\n"); }+static bool Target(unsigned key) { return key == VK_LCONTROL || key == VK_RCONTROL || key == VK_LMENU; }+static bool MouseKey(unsigned key) {+ return key == VK_LBUTTON || key == VK_RBUTTON || key == VK_MBUTTON || key == VK_XBUTTON1 || key == VK_XBUTTON2;+}+static void Update(bool interrupted) {+ unsigned first = keys[VK_LCONTROL] + keys[VK_RCONTROL];+ // Right Alt is AltGr on many layouts. Never summon for the generated Ctrl+Alt+ // pair of an AltGr tap; Ctrl on either side + left Alt remains available.+ unsigned modifiers = (first ? 1u : 0u) | (keys[VK_LMENU] ? 2u : 0u) | (first > 1 ? 4u : 0u);+ bool held = buttons != 0;+ for (unsigned key = 0; key < 256; key++) {+ if (!Target(key) && !MouseKey(key) && key != VK_CONTROL && key != VK_MENU && key != VK_SHIFT) held |= keys[key];+ }+ if (HudModifierUpdate(&gesture, modifiers, held, interrupted, GetTickCount64())) Emit("{\"type\":\"summon\"}\n");+}+static void Snapshot(void) {+ for (unsigned key = 0; key < 256; key++) keys[key] = (GetAsyncKeyState((int)key) & 0x8000) != 0;+ buttons = keys[VK_LBUTTON] | (keys[VK_RBUTTON] << 1) | (keys[VK_MBUTTON] << 2)+ | (keys[VK_XBUTTON1] << 3) | (keys[VK_XBUTTON2] << 4);+ gesture = (HudModifierGesture){0};+ Update(true);+}+static LRESULT CALLBACK Observe(HWND window, UINT message, WPARAM wParam, LPARAM lParam) {+ if (message == WM_INPUT_DEVICE_CHANGE) {+ Snapshot();+ } else if (message == WM_INPUT) {+ RAWINPUT raw;+ UINT size = sizeof(raw);+ if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, &raw, &size, sizeof(RAWINPUTHEADER)) == (UINT)-1) {+ Unavailable(); PostQuitMessage(3);+ } else if (raw.header.dwType == RIM_TYPEKEYBOARD) {+ RAWKEYBOARD *key = &raw.data.keyboard;+ unsigned code = key->VKey;+ if (code == VK_CONTROL) code = (key->Flags & RI_KEY_E0) ? VK_RCONTROL : VK_LCONTROL;+ if (code == VK_MENU) code = (key->Flags & RI_KEY_E0) ? VK_RMENU : VK_LMENU;+ if (code == VK_SHIFT) code = MapVirtualKeyW(key->MakeCode, MAPVK_VSC_TO_VK_EX);+ bool down = !(key->Flags & RI_KEY_BREAK);+ bool interrupted = code >= 256 || !Target(code);+ if (code < 256) {+ interrupted |= keys[code] == down; // Repeat, duplicate, or missed physical transition.+ keys[code] = down;+ }+ Update(interrupted);+ } else if (raw.header.dwType == RIM_TYPEMOUSE) {+ unsigned flags = raw.data.mouse.usButtonFlags;+ for (unsigned button = 0; button < 5; button++) {+ if (flags & (1u << (button * 2))) buttons |= 1u << button;+ if (flags & (2u << (button * 2))) buttons &= ~(1u << button);+ }+ Update(flags != 0 || buttons != 0); // Wheel, click, or motion while dragging.+ }+ // DefWindowProc performs Raw Input cleanup, not input consumption.+ } else if (message == WM_CLOSE) {+ DestroyWindow(window);+ return 0;+ } else if (message == WM_DESTROY) {+ PostQuitMessage(0);+ return 0;+ }+ return DefWindowProcW(window, message, wParam, lParam);+}+static DWORD WINAPI WatchParent(void *context) {+ char byte;+ DWORD count;+ HANDLE input = GetStdHandle(STD_INPUT_HANDLE);+ while (ReadFile(input, &byte, 1, &count, NULL) && count) {}+ PostMessageW((HWND)context, WM_CLOSE, 0, 0);+ return 0;+}+int main(int argc, char **argv) {+ output = GetStdHandle(STD_OUTPUT_HANDLE);+ // Node supplies an anonymous/named pipe. Never block the window's input loop+ // behind a stalled parent; full-pipe writes fail and end this helper.+ DWORD mode = PIPE_NOWAIT;+ if (GetFileType(output) != FILE_TYPE_PIPE || !SetNamedPipeHandleState(output, &mode, NULL, NULL)) return 3;+ bool check = argc == 2 && strcmp(argv[1], "--check") == 0;+ if (argc > 1 && !check && !(argc == 2 && strcmp(argv[1], "--request-permission") == 0)) { Unavailable(); return 64; }+ HINSTANCE instance = GetModuleHandleW(NULL);+ WNDCLASSW definition = {0};+ definition.lpfnWndProc = Observe; definition.hInstance = instance;+ definition.lpszClassName = L"HermesHudModifierMonitor";+ if (!RegisterClassW(&definition)) { Unavailable(); return 3; }+ HWND window = CreateWindowExW(0, definition.lpszClassName, L"", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, instance, NULL);+ if (!window) { Unavailable(); return 3; }+ RAWINPUTDEVICE devices[] = {+ { 1, 6, RIDEV_INPUTSINK | RIDEV_DEVNOTIFY, window },+ { 1, 2, RIDEV_INPUTSINK | RIDEV_DEVNOTIFY, window }+ };+ if (!RegisterRawInputDevices(devices, 2, sizeof(RAWINPUTDEVICE))) { Unavailable(); DestroyWindow(window); return 3; }+ Snapshot();+ HANDLE parent = CreateThread(NULL, 0, WatchParent, window, 0, NULL);+ if (!parent) { Unavailable(); DestroyWindow(window); return 3; }+ Emit("{\"type\":\"ready\"}\n");+ MSG message;+ int result = 0;+ while (!check && (result = GetMessageW(&message, NULL, 0, 0)) > 0) {+ TranslateMessage(&message); DispatchMessageW(&message);+ }+ if (result < 0) Unavailable();+ DestroyWindow(window);+ CancelSynchronousIo(parent);+ CloseHandle(parent);+ UnregisterClassW(definition.lpszClassName, instance);+ return result < 0 ? 3 : 0;+}diff --git a/apps/desktop/electron/native/hud-modifier-monitor-x11.c b/apps/desktop/electron/native/hud-modifier-monitor-x11.cnew file mode 100644index 00000000000..47b5c9b9933--- /dev/null+++ b/apps/desktop/electron/native/hud-modifier-monitor-x11.c@@ -0,0 +1,163 @@+// XI2 raw events are passive; no grabs, remapping, characters, or event logging.+#include <X11/Xlib.h>+#include <X11/XKBlib.h>+#include <X11/keysym.h>+#include <X11/extensions/XInput2.h>+#include <errno.h>+#include <fcntl.h>+#include <poll.h>+#include <signal.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <strings.h>+#include <time.h>+#include <unistd.h>+#include "hud-modifier-gesture.h"++static HudModifierGesture gesture;+static bool keys[256]; // Current physical state only, never emitted.+static unsigned char targets[256];+static bool buttons[256];+static volatile sig_atomic_t stopping;+static void Stop(int signalNumber) { (void)signalNumber; stopping = 1; }+static uint64_t Now(void) {+ struct timespec t;+ clock_gettime(CLOCK_MONOTONIC, &t);+ return (uint64_t)t.tv_sec * 1000 + (uint64_t)t.tv_nsec / 1000000;+}+static void Emit(const char *line) {+ size_t size = strlen(line);+ if (write(STDOUT_FILENO, line, size) != (ssize_t)size) _exit(0);+}+static int Unavailable(void) { Emit("{\"type\":\"error\",\"code\":\"unavailable\"}\n"); return 3; }+static int XFailure(Display *display, XErrorEvent *error) {+ (void)display; (void)error;+ Unavailable(); _exit(3);+}+static int XIOFailure(Display *display) { (void)display; Unavailable(); _exit(3); }++static void Update(bool interrupted) {+ unsigned modifiers = 0, first = 0, second = 0;+ bool held = false;+ for (unsigned key = 0; key < 256; key++) {+ if (!keys[key]) continue;+ if (targets[key] == 1) first++;+ else if (targets[key] == 2) second++;+ else held = true;+ }+ for (unsigned button = 0; button < 256; button++) held |= buttons[button];+ if (first) modifiers |= 1;+ if (second) modifiers |= 2;+ if (first > 1 || second > 1) modifiers |= 4;+ if (HudModifierUpdate(&gesture, modifiers, held, interrupted, Now())) Emit("{\"type\":\"summon\"}\n");+}++static void Snapshot(Display *display) {+ memset(keys, 0, sizeof(keys));+ memset(buttons, 0, sizeof(buttons));+ memset(targets, 0, sizeof(targets));+ KeySym symbols[] = { XK_Control_L, XK_Control_R, XK_Alt_L, XK_Alt_R };+ for (unsigned i = 0; i < 4; i++) {+ KeyCode code = XKeysymToKeycode(display, symbols[i]);+ // Do not turn AltGr / level-switch keys into a Ctrl+Alt tap.+ if (code && XkbKeycodeToKeysym(display, code, 0, 0) == symbols[i]) targets[code] = i < 2 ? 1 : 2;+ }+ char map[32];+ XQueryKeymap(display, map);+ for (unsigned key = 0; key < 256; key++) keys[key] = ((unsigned char)map[key / 8] & (1u << (key % 8))) != 0;+ int count = 0;+ XIDeviceInfo *devices = XIQueryDevice(display, XIAllMasterDevices, &count);+ if (!devices) { Unavailable(); _exit(3); }+ for (int device = 0; device < count; device++) {+ for (int c = 0; c < devices[device].num_classes; c++) {+ if (devices[device].classes[c]->type != XIButtonClass) continue;+ XIButtonClassInfo *b = (XIButtonClassInfo *)devices[device].classes[c];+ for (int button = 0; button < 256 && button < b->state.mask_len * 8; button++) {+ buttons[button] |= XIMaskIsSet(b->state.mask, button) != 0;+ }+ }+ }+ XIFreeDeviceInfo(devices);+ gesture = (HudModifierGesture){0};+ Update(true); // An already-held chord cannot authorize a summon.+}++int main(int argc, char **argv) {+ signal(SIGPIPE, SIG_IGN); signal(SIGINT, Stop); signal(SIGTERM, Stop);+ int outFlags = fcntl(STDOUT_FILENO, F_GETFL);+ if (outFlags < 0 || fcntl(STDOUT_FILENO, F_SETFL, outFlags | O_NONBLOCK) < 0) return 3;+ bool check = argc == 2 && strcmp(argv[1], "--check") == 0;+ if (argc > 1 && !check && !(argc == 2 && strcmp(argv[1], "--request-permission") == 0)) return Unavailable();+ const char *wayland = getenv("WAYLAND_DISPLAY"), *session = getenv("XDG_SESSION_TYPE");+ if ((wayland && *wayland) || (session && strcasecmp(session, "wayland") == 0)) return Unavailable();+ Display *display = XOpenDisplay(NULL);+ if (!display) return Unavailable();+ XSetErrorHandler(XFailure); XSetIOErrorHandler(XIOFailure);+ int opcode, event, error;+ if (XQueryExtension(display, "XWAYLAND", &opcode, &event, &error)+ || !XQueryExtension(display, "XInputExtension", &opcode, &event, &error)) {+ XCloseDisplay(display); return Unavailable();+ }+ int major = 2, minor = 2;+ if (XIQueryVersion(display, &major, &minor) != Success || major < 2 || (major == 2 && minor < 2)) {+ XCloseDisplay(display); return Unavailable();+ }+ Bool detectable = False;+ XkbSetDetectableAutoRepeat(display, True, &detectable);+ if (!detectable) { XCloseDisplay(display); return Unavailable(); }+ unsigned char rawMask[XIMaskLen(XI_LASTEVENT)] = {0};+ XISetMask(rawMask, XI_RawKeyPress); XISetMask(rawMask, XI_RawKeyRelease);+ XISetMask(rawMask, XI_RawButtonPress); XISetMask(rawMask, XI_RawButtonRelease);+ XISetMask(rawMask, XI_RawMotion);+ unsigned char devicesMask[XIMaskLen(XI_LASTEVENT)] = {0};+ XISetMask(devicesMask, XI_HierarchyChanged);+ XIEventMask masks[] = {+ { XIAllMasterDevices, sizeof(rawMask), rawMask },+ { XIAllDevices, sizeof(devicesMask), devicesMask }+ };+ XISelectEvents(display, DefaultRootWindow(display), masks, 2);+ XSync(display, False);+ Snapshot(display);+ Emit("{\"type\":\"ready\"}\n");+ struct pollfd fds[] = { { ConnectionNumber(display), POLLIN, 0 }, { STDIN_FILENO, POLLIN, 0 } };+ while (!check && !stopping) {+ while (XPending(display) && !stopping) {+ XEvent input;+ XNextEvent(display, &input);+ if (input.type == MappingNotify) { XRefreshKeyboardMapping(&input.xmapping); Snapshot(display); continue; }+ if (input.type != GenericEvent || input.xcookie.extension != opcode || !XGetEventData(display, &input.xcookie)) continue;+ if (input.xcookie.evtype == XI_HierarchyChanged) {+ Snapshot(display);+ } else {+ XIRawEvent *raw = input.xcookie.data;+ int code = raw->detail;+ bool interrupted = false;+ if (raw->evtype == XI_RawKeyPress || raw->evtype == XI_RawKeyRelease) {+ if (code < 0 || code >= 256) interrupted = true;+ else {+ bool down = raw->evtype == XI_RawKeyPress;+ interrupted = !targets[code] || keys[code] == down || (raw->flags & XIKeyRepeat);+ keys[code] = down;+ }+ } else if (raw->evtype == XI_RawButtonPress || raw->evtype == XI_RawButtonRelease) {+ // X11 wheel events are buttons as well.+ if (code >= 0 && code < 256) buttons[code] = raw->evtype == XI_RawButtonPress;+ interrupted = true;+ } else if (raw->evtype == XI_RawMotion) {+ for (unsigned b = 0; b < 256; b++) interrupted |= buttons[b];+ }+ Update(interrupted);+ }+ XFreeEventData(display, &input.xcookie);+ }+ if (stopping) break;+ int result = poll(fds, 2, -1);+ if (result < 0) { if (errno == EINTR) continue; Unavailable(); break; }+ if (fds[1].revents & (POLLHUP | POLLERR | POLLNVAL)) break;+ if (fds[1].revents & POLLIN) { char byte; if (read(STDIN_FILENO, &byte, 1) <= 0) break; }+ if (fds[0].revents & (POLLHUP | POLLERR | POLLNVAL)) { Unavailable(); break; }+ }+ XCloseDisplay(display);+ return 0;+}diff --git a/apps/desktop/electron/native/hud-modifier-monitor.m b/apps/desktop/electron/native/hud-modifier-monitor.mnew file mode 100644index 00000000000..02503e6a9f7--- /dev/null+++ b/apps/desktop/electron/native/hud-modifier-monitor.m@@ -0,0 +1,161 @@+// Passive, opt-in Cmd+Option tap. No character decoding, input log, or event IPC.+#import <Cocoa/Cocoa.h>+#import <CoreGraphics/CoreGraphics.h>+#import <IOKit/hidsystem/IOLLEvent.h>+#include "hud-modifier-gesture.h"++// Transient physical state only, discarded on release/exit (never serialized).+typedef struct {+ HudModifierGesture gesture;+ bool keys[128];+ unsigned heldKeys;+ uint32_t buttons;+} HudMacState;++static bool TargetKey(CGKeyCode key) { return key == 54 || key == 55 || key == 58 || key == 61; }++static unsigned Modifiers(CGEventFlags flags) {+ CGEventFlags extra = kCGEventFlagMaskAlphaShift | kCGEventFlagMaskShift+ | kCGEventFlagMaskControl | kCGEventFlagMaskSecondaryFn | kCGEventFlagMaskHelp;+ return ((flags & kCGEventFlagMaskCommand) ? 1u : 0u)+ | ((flags & kCGEventFlagMaskAlternate) ? 2u : 0u) | ((flags & extra) ? 4u : 0u);+}++static bool HudMacUpdate(HudMacState *s, CGEventType type, CGKeyCode key,+ CGEventFlags flags, bool repeat, unsigned button, uint64_t ms) {+ bool interrupted = repeat;+ unsigned modifiers = Modifiers(flags);+ switch (type) {+ case kCGEventFlagsChanged:+ interrupted |= !TargetKey(key) || modifiers == s->gesture.modifiers;+ break;+ case kCGEventKeyDown:+ case kCGEventKeyUp:+ interrupted = true;+ if (key < 128 && !TargetKey(key)) {+ bool down = type == kCGEventKeyDown;+ if (down != s->keys[key]) {+ s->heldKeys = down ? s->heldKeys + 1 : s->heldKeys - 1;+ s->keys[key] = down;+ }+ }+ break;+ case kCGEventLeftMouseDown:+ case kCGEventRightMouseDown:+ case kCGEventOtherMouseDown:+ if (button < 32) s->buttons |= 1u << button;+ interrupted = true;+ break;+ case kCGEventLeftMouseUp:+ case kCGEventRightMouseUp:+ case kCGEventOtherMouseUp:+ if (button < 32) s->buttons &= ~(1u << button);+ interrupted = true;+ break;+ case kCGEventMouseMoved:+ if (!s->buttons) return false;+ interrupted = true;+ break;+ default: // Wheel and drag always cancel, even if their button press was missed.+ interrupted = true;+ break;+ }+ return HudModifierUpdate(&s->gesture, modifiers, s->heldKeys || s->buttons, interrupted, ms);+}++#ifndef HUD_MODIFIER_MONITOR_TEST+#include <dispatch/dispatch.h>+#include <fcntl.h>+#include <signal.h>+#include <stdio.h>+#include <string.h>+#include <unistd.h>++static void Emit(const char *line) {+ size_t size = strlen(line);+ // A fixed, atomic, nonblocking message: a stalled/closed parent ends monitoring.+ if (write(STDOUT_FILENO, line, size) != (ssize_t)size) _exit(0);+}+static void Error(void) {+ Emit(CGPreflightListenEventAccess()+ ? "{\"type\":\"error\",\"code\":\"unavailable\"}\n"+ : "{\"type\":\"error\",\"code\":\"permission-required\"}\n");+}+static CGEventRef Observe(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *info) {+ (void)proxy;+ if (type == kCGEventTapDisabledByTimeout || type == kCGEventTapDisabledByUserInput) {+ // Never re-enable with stale state after lost events or permission revocation.+ Error();+ CFRunLoopStop(CFRunLoopGetMain());+ return event;+ }+ if (HudMacUpdate(info, type, (CGKeyCode)CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode),+ CGEventGetFlags(event), CGEventGetIntegerValueField(event, kCGKeyboardEventAutorepeat) != 0,+ (unsigned)CGEventGetIntegerValueField(event, kCGMouseEventButtonNumber), CGEventGetTimestamp(event) / 1000000)) {+ Emit("{\"type\":\"summon\"}\n");+ }+ return event; // The tap is listen-only: nothing is consumed or changed.+}++int main(int argc, const char *argv[]) { @autoreleasepool {+ signal(SIGPIPE, SIG_IGN);+ int flags = fcntl(STDOUT_FILENO, F_GETFL);+ if (flags < 0 || fcntl(STDOUT_FILENO, F_SETFL, flags | O_NONBLOCK) < 0) return 3;+ bool check = argc == 2 && strcmp(argv[1], "--check") == 0;+ bool request = argc == 2 && strcmp(argv[1], "--request-permission") == 0;+ if (argc > 1 && !check && !request) {+ Emit("{\"type\":\"error\",\"code\":\"unavailable\"}\n"); return 64;+ }+ bool allowed = CGPreflightListenEventAccess();+ if (!allowed && request) allowed = CGRequestListenEventAccess();+ if (!allowed) { Emit("{\"type\":\"error\",\"code\":\"permission-required\"}\n"); return 2; }+ HudMacState state = {0};+ CGEventMask mask = CGEventMaskBit(kCGEventFlagsChanged) | CGEventMaskBit(kCGEventKeyDown)+ | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventLeftMouseDown) | CGEventMaskBit(kCGEventLeftMouseUp)+ | CGEventMaskBit(kCGEventRightMouseDown) | CGEventMaskBit(kCGEventRightMouseUp)+ | CGEventMaskBit(kCGEventOtherMouseDown) | CGEventMaskBit(kCGEventOtherMouseUp)+ | CGEventMaskBit(kCGEventScrollWheel) | CGEventMaskBit(kCGEventLeftMouseDragged)+ | CGEventMaskBit(kCGEventRightMouseDragged) | CGEventMaskBit(kCGEventOtherMouseDragged);+ CFMachPortRef tap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap,+ kCGEventTapOptionListenOnly, mask, Observe, &state);+ if (!tap) { Error(); return 3; }+ CFRunLoopSourceRef source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0);+ if (!source) { CFMachPortInvalidate(tap); CFRelease(tap); Error(); return 3; }+ CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopCommonModes);+ // Seed once, after installing the tap. No polling or history of typed input.+ for (CGKeyCode key = 0; key < 128; key++) {+ // Flags-only keys (54..63) are represented by the modifier snapshot, not+ // heldKeys: they never produce the KeyUp that clears an ordinary key.+ if ((key < 54 || key > 63) && CGEventSourceKeyState(kCGEventSourceStateCombinedSessionState, key)) {+ state.keys[key] = true; state.heldKeys++;+ }+ }+ for (unsigned button = 0; button < 32; button++) {+ if (CGEventSourceButtonState(kCGEventSourceStateCombinedSessionState, button)) state.buttons |= 1u << button;+ }+ unsigned initial = Modifiers(CGEventSourceFlagsState(kCGEventSourceStateCombinedSessionState));+ HudModifierUpdate(&state.gesture, initial, state.heldKeys || state.buttons, initial != 0, 0);++ 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);+ Emit("{\"type\":\"ready\"}\n");+ if (!check) 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/electron/native/hud-modifier-monitor.test.m b/apps/desktop/electron/native/hud-modifier-monitor.test.mnew file mode 100644index 00000000000..8538e6d4c8c--- /dev/null+++ b/apps/desktop/electron/native/hud-modifier-monitor.test.m@@ -0,0 +1,61 @@+#define HUD_MODIFIER_MONITOR_TEST 1+#include "hud-modifier-monitor.m"+#include <assert.h>++static CGEventFlags command = kCGEventFlagMaskCommand | NX_DEVICELCMDKEYMASK;+static CGEventFlags option = kCGEventFlagMaskAlternate | NX_DEVICELALTKEYMASK;+static bool flags(HudMacState *s, CGKeyCode key, CGEventFlags f, uint64_t ms) {+ return HudMacUpdate(s, kCGEventFlagsChanged, key, f, false, 0, ms);+}+static void begin(HudMacState *s) {+ assert(!flags(s, 55, command, 10));+ assert(!flags(s, 58, command | option, 20));+}+static bool release(HudMacState *s) {+ assert(!flags(s, 55, option, 30));+ return flags(s, 58, 0, 40);+}+int main(void) { @autoreleasepool {+ HudMacState s = {0};+ begin(&s);+ assert(release(&s));+ CGEventType interruptions[] = { kCGEventKeyDown, kCGEventKeyUp,+ kCGEventLeftMouseDown, kCGEventLeftMouseUp, kCGEventRightMouseDown,+ kCGEventOtherMouseDown, kCGEventScrollWheel, kCGEventLeftMouseDragged,+ kCGEventRightMouseDragged, kCGEventOtherMouseDragged };+ for (unsigned i = 0; i < sizeof(interruptions) / sizeof(*interruptions); i++) {+ s = (HudMacState){0};+ begin(&s);+ assert(!HudMacUpdate(&s, interruptions[i], 0, command | option, false, 0, 25));+ assert(!release(&s));+ }+ s = (HudMacState){0}; begin(&s);+ assert(!HudMacUpdate(&s, kCGEventKeyDown, 0, command | option, true, 0, 25));+ assert(!release(&s));+ s = (HudMacState){0}; begin(&s);+ assert(!flags(&s, 56, command | option | kCGEventFlagMaskShift, 25));+ assert(!flags(&s, 56, command | option, 26));+ assert(!release(&s));+ s = (HudMacState){0}; begin(&s);+ assert(!flags(&s, 54, command | option | NX_DEVICERCMDKEYMASK, 25));+ assert(!release(&s));+ // Plain pointer movement is harmless; drag/click/wheel was tested above.+ s = (HudMacState){0}; begin(&s);+ assert(!HudMacUpdate(&s, kCGEventMouseMoved, 0, command | option, false, 0, 25));+ assert(release(&s));+ // Snapshots of a held key, mouse, or chord cannot authorize a release.+ s = (HudMacState){0}; s.keys[0] = true; s.heldKeys = 1;+ begin(&s); assert(!release(&s));+ s = (HudMacState){0}; s.buttons = 1;+ begin(&s); assert(!release(&s));+ s = (HudMacState){0};+ HudModifierUpdate(&s.gesture, 3, true, true, 0);+ assert(!release(&s));+ // Two Command keys retain their independent screenshot meaning.+ s = (HudMacState){0};+ assert(!flags(&s, 55, command, 10));+ assert(!flags(&s, 54, command | NX_DEVICERCMDKEYMASK, 20));+ assert(!flags(&s, 54, command, 30));+ assert(!flags(&s, 55, 0, 40));+ puts("native macOS event adapter assertions passed");+} return 0; }diff --git a/apps/desktop/electron/native/hud-modifier-x11.test.py b/apps/desktop/electron/native/hud-modifier-x11.test.pynew file mode 100644index 00000000000..cbe61fc826d--- /dev/null+++ b/apps/desktop/electron/native/hud-modifier-x11.test.py@@ -0,0 +1,114 @@+"""Exercise the actual XI2 helper on a PRIVATE Xvfb server, never the user's display.++Usage: python3 hud-modifier-x11.test.py /path/to/hud-modifier-monitor+Requires Xvfb and libXtst. No Desktop launch, global host input, or permission prompt.+"""+import json+import ctypes+import os+import select+import subprocess+import sys+import time+++def message(child, timeout=5):+ assert select.select([child.stdout], [], [], timeout)[0], "helper timed out"+ line = child.stdout.readline()+ assert line, "helper exited unexpectedly"+ return json.loads(line)+++def main(binary):+ read_fd, write_fd = os.pipe()+ server = subprocess.Popen(+ ["Xvfb", "-displayfd", str(write_fd), "-screen", "0", "640x480x24", "-nolisten", "tcp", "-ac"],+ pass_fds=(write_fd,), stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,+ )+ os.close(write_fd)+ child = None+ try:+ assert select.select([read_fd], [], [], 10)[0], "Xvfb did not start"+ display = os.read(read_fd, 32).decode().strip()+ assert display.isdigit(), "Xvfb did not supply a private display"+ env = {**os.environ, "DISPLAY": ":" + display, "XDG_SESSION_TYPE": "x11"}+ env.pop("WAYLAND_DISPLAY", None)+ # Keep one injector connection alive. Starting a new xdotool process+ # enables/disables XTEST devices, correctly invalidating the helper's+ # state via XI_HierarchyChanged in the middle of a gesture.+ x11 = ctypes.CDLL("libX11.so.6")+ xtst = ctypes.CDLL("libXtst.so.6")+ x11.XOpenDisplay.argtypes = [ctypes.c_char_p]+ x11.XOpenDisplay.restype = ctypes.c_void_p+ x11.XStringToKeysym.argtypes = [ctypes.c_char_p]+ x11.XStringToKeysym.restype = ctypes.c_ulong+ x11.XKeysymToKeycode.argtypes = [ctypes.c_void_p, ctypes.c_ulong]+ x11.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int]+ xtst.XTestFakeKeyEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_ulong]+ xtst.XTestFakeButtonEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_ulong]+ xtst.XTestFakeRelativeMotionEvent.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_ulong]+ injector = x11.XOpenDisplay(env["DISPLAY"].encode())+ assert injector+ def keys(*args):+ pending = iter(args)+ for command in pending:+ value = next(pending)+ if command == "sleep":+ time.sleep(float(value))+ elif command in ("keydown", "keyup", "key"):+ code = x11.XKeysymToKeycode(injector, x11.XStringToKeysym(value.encode()))+ assert code+ xtst.XTestFakeKeyEvent(injector, code, command != "keyup", 0)+ if command == "key": xtst.XTestFakeKeyEvent(injector, code, False, 0)+ elif command in ("mousedown", "mouseup", "click"):+ xtst.XTestFakeButtonEvent(injector, int(value), command != "mouseup", 0)+ if command == "click": xtst.XTestFakeButtonEvent(injector, int(value), False, 0)+ elif command == "move":+ xtst.XTestFakeRelativeMotionEvent(injector, int(value), int(next(pending)), 0)+ else:+ raise AssertionError(command)+ x11.XSync(injector, False)+ time.sleep(0.015)+ keys("key", "Shift_L", "click", "1")+ child = subprocess.Popen([binary], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)+ assert child.stdin is not None and child.stdout is not None and child.stderr is not None+ assert message(child) == {"type": "ready"}+ def press():+ keys("keydown", "Control_L", "keydown", "Alt_L")+ def release():+ keys("keyup", "Control_L", "keyup", "Alt_L")+ press()+ release()+ assert message(child) == {"type": "summon"}+ for interference in [+ ("key", "x"), ("key", "Shift_L"), ("click", "1"), ("click", "4"),+ ("mousedown", "1", "move", "10", "10", "mouseup", "1"),+ ]:+ press()+ keys(*interference)+ release()+ assert not select.select([child.stdout], [], [], 2)[0], ("unexpected summon", interference)+ # Time is measured from first press until BOTH releases, not chord formation.+ press()+ keys("sleep", "0.6")+ release()+ assert not select.select([child.stdout], [], [], 2)[0], "long hold summoned"+ # EOF retires the actual helper promptly.+ child.stdin.close()+ assert child.wait(timeout=5) == 0+ assert child.stderr.read() == b""+ # Even DISPLAY pointing at X11 must not claim global access on Wayland.+ denied = subprocess.run([binary, "--check"], env={**env, "WAYLAND_DISPLAY": "wayland-test"}, capture_output=True, timeout=5)+ assert json.loads(denied.stdout) == {"type": "error", "code": "unavailable"}+ print("isolated XI2: summon, key/modifier/mouse/wheel/drag cancellation, duration, EOF, and Wayland checks passed")+ finally:+ os.close(read_fd)+ if child is not None and child.poll() is None:+ child.kill()+ child.wait(timeout=5)+ server.terminate()+ server.wait(timeout=5)+++if __name__ == "__main__":+ main(sys.argv[1])diff --git a/apps/desktop/scripts/before-pack.mjs b/apps/desktop/scripts/before-pack.mjsindex cb8ce15d617..4063687b1c0 100644--- a/apps/desktop/scripts/before-pack.mjs+++ b/apps/desktop/scripts/before-pack.mjs@@ -61,6 +61,7 @@ import { existsSync, rmSync, renameSync } from 'node:fs'import path from 'node:path'import { Arch } from 'electron-builder'import { removeDirSync, stageNodePty, stageGetWindows } from './stage-native-deps.mjs'+import { buildHudModifierMonitor } from './build-hud-modifier-monitor.mjs'export function cleanStaleAppOutDir(appOutDir) {if (!appOutDir || typeof appOutDir !== 'string') {@@ -146,6 +147,7 @@ export default async function beforePack(context) {const platform = context && context.electronPlatformNameconst archName = context && typeof context.arch === 'number' ? Arch[context.arch] : undefinedif (platform && archName) {+ buildHudModifierMonitor({ platform, arch: archName })if (archName === 'universal') {console.warn('[before-pack] target arch is "universal" — node-pty has no universal prebuild; ' +diff --git a/apps/desktop/scripts/build-hud-modifier-monitor.mjs b/apps/desktop/scripts/build-hud-modifier-monitor.mjsnew file mode 100644index 00000000000..57242ed2fb4--- /dev/null+++ b/apps/desktop/scripts/build-hud-modifier-monitor.mjs@@ -0,0 +1,97 @@+#!/usr/bin/env node+// Optional, host-native helper. No compiler or development headers at runtime.+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 hudModifierBinaryRelativePath(platform = process.platform, arch = process.arch) {+ return `native/${platform}-${platform === 'darwin' ? 'universal' : arch}/hud-modifier-monitor${platform === 'win32' ? '.exe' : ''}`+}++export function buildHudModifierMonitor({+ distDir = resolve(root, 'dist'),+ platform = process.platform,+ arch = process.arch+} = {}) {+ // Cross-packaging must not ship a host binary under the target's name. The+ // capability stays unavailable unless that target was built on its own host.+ if (platform !== process.platform || (platform !== 'darwin' && arch !== process.arch)) {+ console.warn(`[hud-modifier] ${platform}-${arch} needs a native build; modifier tap unavailable for this target`)+ return null+ }+ if (!['darwin', 'linux', 'win32'].includes(platform)) return null+ const output = resolve(distDir, hudModifierBinaryRelativePath(platform, arch))+ const staging = `${output}.${process.pid}.tmp${platform === 'win32' ? '.exe' : ''}`+ const source = name => resolve(root, 'electron/native', name)+ mkdirSync(dirname(output), { recursive: true })+ try {+ if (platform === 'darwin') {+ execFileSync(+ 'xcrun',+ [+ '--sdk',+ 'macosx',+ 'clang',+ '-arch',+ 'arm64',+ '-arch',+ 'x86_64',+ '-mmacosx-version-min=11.0',+ '-fobjc-arc',+ '-fblocks',+ '-O2',+ '-Wall',+ '-Wextra',+ '-framework',+ 'Cocoa',+ '-framework',+ 'CoreGraphics',+ source('hud-modifier-monitor.m'),+ '-o',+ staging+ ],+ { stdio: 'pipe', timeout: 120_000 }+ )+ } else {+ const windows = platform === 'win32'+ execFileSync(+ process.env.CC || (windows ? 'clang' : 'cc'),+ [+ '-std=gnu11',+ '-O2',+ '-Wall',+ '-Wextra',+ source(windows ? 'hud-modifier-monitor-win.c' : 'hud-modifier-monitor-x11.c'),+ '-o',+ staging,+ ...(windows ? ['-luser32'] : ['-lX11', '-lXi'])+ ],+ { stdio: 'pipe', timeout: 120_000 }+ )+ }+ chmodSync(staging, 0o755)+ renameSync(staging, output)+ console.log(`built ${output}`)+ return output+ } catch (error) {+ rmSync(output, { force: true }) // Never keep a stale helper after a failed rebuild.+ if (platform === 'darwin') throw error // The existing macOS build already requires Xcode.+ const prerequisite = platform === 'linux' ? 'a C compiler, libx11-dev and libxi-dev' : 'Clang and the Windows SDK'+ console.warn(`[hud-modifier] unavailable: native build needs ${prerequisite}; desktop packaging continues`)+ console.warn(String(error.stderr || error.message))+ return null+ } 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-hud-modifier-monitor.mjs [--out-dir PATH]')+ buildHudModifierMonitor(args.length ? { distDir: resolve(args[1]) } : {})+}diff --git a/apps/desktop/scripts/bundle-electron-main.mjs b/apps/desktop/scripts/bundle-electron-main.mjsindex 23f23d261c5..6dcb7cfa501 100644--- a/apps/desktop/scripts/bundle-electron-main.mjs+++ b/apps/desktop/scripts/bundle-electron-main.mjs@@ -15,6 +15,7 @@ import { resolve, dirname } from 'node:path'import { fileURLToPath } from 'node:url'import { mkdirSync } from 'node:fs'import { buildCommandScreenshotMonitor } from './build-command-screenshot-monitor.mjs'+import { buildHudModifierMonitor } from './build-hud-modifier-monitor.mjs'const here = dirname(fileURLToPath(import.meta.url))const root = resolve(here, '..')@@ -22,6 +23,7 @@ const distDir = resolve(root, 'dist')mkdirSync(distDir, { recursive: true })// Stage for both --dev and release bundles; non-mac hosts skip this helper.buildCommandScreenshotMonitor({ distDir })+buildHudModifierMonitor({ distDir })const mainEntry = resolve(root, 'electron/entry.ts')const mainOut = resolve(distDir, 'electron-main.mjs')