Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 支持原生触控板双指映射与侧栏坐标转换

Dashc2e385165627
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index d6b9c1f062..eef604af5b 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -1980,6 +1980,19 @@ const config: ForgeConfig = {
buildWindowsGamepadHelper(platform, arch);
buildWindowsAtomicRenameHelper(platform, arch);
buildWindowsTaskbarAddon(platform, arch);
+ if (platform === 'darwin') {
+ const trackpadBuild = spawnSync(
+ process.execPath,
+ [
+ path.join(__dirname, 'native/trackpad/build.mjs'),
+ path.join(__dirname, 'resources/tools/trackpad/cindy-trackpad.node'),
+ arch,
+ ],
+ { stdio: 'inherit' },
+ );
+ if (trackpadBuild.error || trackpadBuild.status !== 0)
+ throw new Error('Native trackpad build failed');
+ }
buildMacVoiceInputModifierShortcutListener(platform, arch);
buildMacAgentIslandHelper(platform, arch);
buildMacComputerPermissionGuideHelper(platform, arch);
diff --git a/apps/desktop/native/trackpad/build.mjs b/apps/desktop/native/trackpad/build.mjs
new file mode 100644
index 0000000000..779e68affe
--- /dev/null
+++ b/apps/desktop/native/trackpad/build.mjs
@@ -0,0 +1,63 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { createRequire } from 'node:module';
+import { fileURLToPath } from 'node:url';
+import { execFileSync } from 'node:child_process';
+
+const source = path.dirname(fileURLToPath(import.meta.url));
+const require = createRequire(path.join(source, '../../package.json'));
+export function buildTrackpad(output, arch = process.arch) {
+ if (process.platform !== 'darwin') return;
+ if (!['arm64', 'x64'].includes(arch)) throw new Error('Unsupported trackpad architecture');
+ const headers = path.join(
+ os.homedir(),
+ 'Library/Caches/node-gyp',
+ process.versions.node,
+ 'include/node',
+ );
+ if (!fs.existsSync(path.join(headers, 'node_api.h'))) {
+ const rebuild = createRequire(require.resolve('@electron/rebuild'));
+ execFileSync(
+ process.execPath,
+ [rebuild.resolve('node-gyp/bin/node-gyp.js'), 'install', '--ensure'],
+ { stdio: 'inherit' },
+ );
+ }
+ fs.mkdirSync(path.dirname(output), { recursive: true });
+ const temporary = `${output}.${process.pid}.tmp`;
+ try {
+ execFileSync(
+ 'xcrun',
+ [
+ 'clang++',
+ '-std=c++17',
+ '-fobjc-arc',
+ '-bundle',
+ '-undefined',
+ 'dynamic_lookup',
+ '-arch',
+ arch === 'x64' ? 'x86_64' : 'arm64',
+ '-mmacosx-version-min=12.0',
+ '-framework',
+ 'Cocoa',
+ '-I',
+ headers,
+ path.join(source, 'trackpad.mm'),
+ '-o',
+ temporary,
+ ],
+ { stdio: 'inherit' },
+ );
+ execFileSync('codesign', ['--force', '--sign', '-', temporary], { stdio: 'inherit' });
+ fs.renameSync(temporary, output);
+ } finally {
+ fs.rmSync(temporary, { force: true });
+ }
+}
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ buildTrackpad(
+ process.argv[2] || path.join(source, '../../resources/tools/trackpad/cindy-trackpad.node'),
+ process.argv[3],
+ );
+}
diff --git a/apps/desktop/native/trackpad/trackpad.mm b/apps/desktop/native/trackpad/trackpad.mm
new file mode 100644
index 0000000000..2a5e463bf7
--- /dev/null
+++ b/apps/desktop/native/trackpad/trackpad.mm
@@ -0,0 +1,218 @@
+// Local AppKit input only. No global event tap, private MultitouchSupport API,
+// accessibility permission, cursor warping, or changes to Chromium's view class.
+#import <Cocoa/Cocoa.h>
+#include <node_api.h>
+#include <string>
+
+@interface CindyTrackpad : NSObject
+@property(nonatomic, weak) NSWindow *window;
+@property(nonatomic, weak) NSView *view;
+@property(nonatomic, strong) id monitor;
+@property(nonatomic, strong) id resign;
+@property(nonatomic, strong) NSMutableDictionary *identities;
+@property(nonatomic) napi_threadsafe_function callback;
+@property(nonatomic) BOOL tracking;
+@property(nonatomic) BOOL suppressGestures;
+@property(nonatomic) BOOL waitingForLift;
+@property(nonatomic) BOOL previousRestingTouches;
+@property(nonatomic) uint32_t serial;
+- (void)finish;
+- (NSEvent *)event:(NSEvent *)event;
+@end
+
+static CindyTrackpad *capture;
+static uint32_t nextSerial = 0;
+
+static void Deliver(napi_env env, napi_value callback, void *, void *data) {
+ auto text = static_cast<std::string *>(data);
+ if (env && callback) {
+ napi_value value, receiver, result;
+ napi_create_string_utf8(env, text->c_str(), text->size(), &value);
+ napi_get_undefined(env, &receiver);
+ napi_call_function(env, receiver, callback, 1, &value, &result);
+ }
+ delete text;
+}
+
+@implementation CindyTrackpad
+- (void)emit:(NSDictionary *)frame {
+ if (!self.callback) return;
+ NSData *data = [NSJSONSerialization dataWithJSONObject:frame options:0 error:nil];
+ if (!data) return;
+ auto text = new std::string(static_cast<const char *>(data.bytes), data.length);
+ if (napi_call_threadsafe_function(self.callback, text, napi_tsfn_nonblocking) != napi_ok)
+ delete text;
+}
+- (void)finish {
+ if (self.monitor) self.view.wantsRestingTouches = self.previousRestingTouches;
+ if (self.tracking) [self emit:@{@"phase":@"cancel", @"touches":@[]}];
+ self.tracking = NO;
+ if (self.monitor) [NSEvent removeMonitor:self.monitor];
+ if (self.resign) [[NSNotificationCenter defaultCenter] removeObserver:self.resign];
+ self.monitor = nil;
+ self.resign = nil;
+ if (self.callback) napi_release_threadsafe_function(self.callback, napi_tsfn_release);
+ self.callback = nullptr;
+}
+- (NSEvent *)event:(NSEvent *)event {
+ NSWindow *window = self.window;
+ NSView *view = self.view;
+ if (!window || !view || !window.isKeyWindow || !NSApp.isActive || view.window != window) {
+ [self finish];
+ return event;
+ }
+ if (event.window != window) return event;
+ if (event.type == NSEventTypeGesture) {
+ // Generic touch events, never reconstructed from magnify/rotate events.
+ NSSet<NSTouch *> *all = [event touchesMatchingPhase:NSTouchPhaseAny inView:view];
+ if (!all.count) return event;
+ NSMutableArray<NSTouch *> *active = [NSMutableArray array];
+ BOOL cancelled = NO;
+ for (NSTouch *touch in all) {
+ if (touch.type != NSTouchTypeIndirect) continue;
+ if (touch.phase == NSTouchPhaseCancelled) cancelled = YES;
+ if (touch.phase & NSTouchPhaseTouching) [active addObject:touch];
+ }
+ if (self.waitingForLift) {
+ if (!active.count) self.waitingForLift = NO;
+ return event;
+ }
+ if (cancelled || active.count > 2) {
+ if (self.tracking) [self emit:@{@"phase":@"cancel", @"touches":@[]}];
+ self.tracking = NO;
+ self.suppressGestures = NO;
+ self.waitingForLift = active.count > 0;
+ return event;
+ }
+ BOOL beginning = !self.tracking;
+ if (beginning) {
+ if (active.count != 2) { self.suppressGestures = NO; return event; }
+ if ([NSEvent pressedMouseButtons]) return event;
+ NSPoint mouse = [window.contentView convertPoint:[window mouseLocationOutsideOfEventStream] fromView:nil];
+ NSView *hit = [window.contentView hitTest:mouse];
+ if (hit != view && ![hit isDescendantOf:view]) return event;
+ [self.identities removeAllObjects];
+ self.tracking = YES;
+ self.suppressGestures = YES;
+ }
+ NSMutableArray *points = [NSMutableArray array];
+ NSSize device = NSZeroSize;
+ for (NSTouch *touch in active) {
+ NSNumber *identifier = self.identities[touch.identity];
+ if (!identifier) {
+ // Adding/replacing a finger after the initial pair starts a fresh gesture.
+ if (self.identities.count >= 2) {
+ [self emit:@{@"phase":@"cancel", @"touches":@[]}];
+ self.tracking = NO;
+ self.suppressGestures = NO;
+ self.waitingForLift = YES;
+ return event;
+ }
+ identifier = @(self.identities.count);
+ self.identities[touch.identity] = identifier;
+ }
+ NSPoint p = touch.normalizedPosition;
+ device = touch.deviceSize;
+ [points addObject:@{@"id":identifier, @"x":@(p.x), @"y":@(1-p.y)}];
+ }
+ [self emit:@{@"phase":beginning?@"begin":active.count?@"change":@"end",
+ @"touches":points, @"width":@(device.width), @"height":@(device.height)}];
+ if (!active.count) self.tracking = NO;
+ return event;
+ }
+ // The same fingers also produce native wheel/magnify/rotate. Consume those
+ // only for this captured sequence; an ordinary mouse wheel still works.
+ if (self.suppressGestures && (event.type == NSEventTypeMagnify ||
+ event.type == NSEventTypeRotate || (event.type == NSEventTypeScrollWheel &&
+ (event.phase != NSEventPhaseNone || event.momentumPhase != NSEventPhaseNone)))) return nil;
+ if (event.type == NSEventTypeLeftMouseDown || event.type == NSEventTypeRightMouseDown) {
+ if (self.tracking) [self emit:@{@"phase":@"cancel", @"touches":@[]}];
+ self.tracking = NO;
+ self.suppressGestures = NO;
+ self.waitingForLift = YES;
+ }
+ return event;
+}
+@end
+
+static napi_value Start(napi_env env, napi_callback_info info) {
+ size_t count = 2; napi_value args[2], result;
+ napi_get_cb_info(env, info, &count, args, nullptr, nullptr);
+ void *bytes = nullptr; size_t length = 0; napi_valuetype type;
+ if (count != 2 || napi_get_buffer_info(env, args[0], &bytes, &length) != napi_ok ||
+ length != sizeof(void *) || napi_typeof(env, args[1], &type) != napi_ok || type != napi_function) {
+ napi_throw_type_error(env, nullptr, "Invalid trackpad binding"); return nullptr;
+ }
+ NSView *root = (__bridge NSView *)(*static_cast<void **>(bytes));
+ NSWindow *window = root.window;
+ NSResponder *responder = window.firstResponder;
+ NSView *view = [responder isKindOfClass:[NSView class]] ? (NSView *)responder : nil;
+ NSView *hit = [window.contentView hitTest:[window.contentView
+ convertPoint:[window mouseLocationOutsideOfEventStream] fromView:nil]];
+ if (![NSThread isMainThread] || !NSApp.isActive || !window.isKeyWindow || !view ||
+ (hit != view && ![hit isDescendantOf:view])) {
+ napi_get_null(env, &result); return result;
+ }
+ [capture finish];
+ CindyTrackpad *next = [CindyTrackpad new];
+ next.window = window; next.view = view; next.serial = ++nextSerial;
+ next.identities = [NSMutableDictionary dictionary];
+ napi_value name; napi_create_string_utf8(env, "CindyTrackpad", NAPI_AUTO_LENGTH, &name);
+ napi_threadsafe_function callback;
+ if (napi_create_threadsafe_function(env, args[1], nullptr, name, 0, 1, nullptr,
+ nullptr, nullptr, Deliver, &callback) != napi_ok) return nullptr;
+ next.callback = callback;
+ napi_unref_threadsafe_function(env, callback);
+ // Chromium enables indirect touches. Keep a stationary finger in the pair;
+ // restore this NSView preference when the local capture ends.
+ next.previousRestingTouches = view.wantsRestingTouches;
+ view.wantsRestingTouches = YES;
+ __weak CindyTrackpad *weak = next;
+ next.monitor = [NSEvent addLocalMonitorForEventsMatchingMask:
+ NSEventMaskGesture | NSEventMaskMagnify | NSEventMaskRotate | NSEventMaskScrollWheel |
+ NSEventMaskLeftMouseDown | NSEventMaskRightMouseDown handler:^NSEvent *(NSEvent *event) {
+ return weak ? [weak event:event] : event;
+ }];
+ next.resign = [[NSNotificationCenter defaultCenter] addObserverForName:NSWindowDidResignKeyNotification
+ object:window queue:nil usingBlock:^(NSNotification *) { [weak finish]; }];
+ capture = next;
+ napi_create_uint32(env, next.serial, &result); return result;
+}
+static napi_value Stop(napi_env env, napi_callback_info info) {
+ size_t count=1; napi_value arg, result; uint32_t serial=0;
+ napi_get_cb_info(env, info, &count, &arg, nullptr, nullptr);
+ if (count && napi_get_value_uint32(env, arg, &serial)==napi_ok && capture.serial==serial) {
+ [capture finish]; capture=nil;
+ }
+ napi_get_undefined(env, &result); return result;
+}
+// Electron's before-mouse-event can report subframe-relative coordinates.
+// Use window-content coordinates, independent of which Chromium NSView owns
+// firstResponder. The host converts these into the embedded guest viewport.
+static napi_value Position(napi_env env, napi_callback_info info) {
+ size_t count=1; napi_value arg, result; void *bytes=nullptr; size_t length=0;
+ napi_get_cb_info(env, info, &count, &arg, nullptr, nullptr);
+ if (!count || napi_get_buffer_info(env,arg,&bytes,&length)!=napi_ok || length!=sizeof(void *)) {
+ napi_throw_type_error(env,nullptr,"Invalid window handle"); return nullptr;
+ }
+ NSView *root=(__bridge NSView *)(*static_cast<void **>(bytes));
+ NSWindow *window=root.window;
+ NSView *view=window.contentView;
+ if (!view || !window.isKeyWindow || !NSApp.isActive) { napi_get_null(env,&result); return result; }
+ NSPoint p=[view convertPoint:[window mouseLocationOutsideOfEventStream] fromView:nil];
+ napi_create_object(env,&result); napi_value x,y;
+ napi_create_double(env,p.x-view.bounds.origin.x,&x);
+ napi_create_double(env,view.isFlipped?p.y-view.bounds.origin.y:NSMaxY(view.bounds)-p.y,&y);
+ napi_set_named_property(env,result,"x",x); napi_set_named_property(env,result,"y",y);
+ return result;
+}
+static void Cleanup(void *) { [capture finish]; capture=nil; }
+NAPI_MODULE_INIT() {
+ napi_property_descriptor properties[] = {
+ {"start", nullptr, Start, nullptr, nullptr, nullptr, napi_default, nullptr},
+ {"position", nullptr, Position, nullptr, nullptr, nullptr, napi_default, nullptr},
+ {"stop", nullptr, Stop, nullptr, nullptr, nullptr, napi_default, nullptr}};
+ napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties);
+ napi_add_env_cleanup_hook(env, Cleanup, nullptr);
+ return exports;
+}
diff --git a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-panels.md b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-panels.md
index 5d54b8b911..7272d2edb8 100644
--- a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-panels.md
+++ b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-panels.md
@@ -53,3 +53,21 @@
这些控件会反档;真要覆盖就跟着主机主题一起换;
- 滚动条统一规范:12px 槽 + 6px 圆角 thumb,滚动时加 `.is-scrolling` 显形
(颜色用 `var(--msg-scrollbar)` / `var(--msg-scrollbar-hover)`),2 秒无活动移除。
+
+### 可选的 Mac 原生双指输入
+
+需要真实双触点的平面画面(例如设备模拟器)可在顶层页面声明
+`<meta name="cindy-native-trackpad" content="touch">`,并在实际交互元素上加
+`data-cindy-trackpad`。支持此能力的 Mac 宿主只在页面聚焦、鼠标位于该元素时,将
+AppKit 的两指位置投递为标准 Touch/Pointer 事件,嵌套 iframe 同样适用。
+元素应设 `touch-action:none` 并处理结束、取消和失焦;不需要 preload、消息桥或新权限。
+落指中心取鼠标位置,触控板宽度对应元素宽度,两轴等比,超出元素边缘的触点裁剪。
+边缘不累计越界位移,反向移动立即生效。
+第三指交回系统;原生序列不重复投递 wheel/magnify。旧宿主、非 Mac、原生模块不可用
+或页面正在被其他调试会话占用时不启用;保留原有 wheel 兼容逻辑,不能假定所有宿主都有。
+
+对连续输入可使用 `data-cindy-trackpad="contacts"`:处理元素上的 `cindy-trackpad`
+事件,`detail` 为 `{phase,touches:[{id,x,y}]}`,坐标相对元素所属 frame 的 viewport。
+`begin/change/end/cancel` 对应落指、移动、结束、取消;touches 是全部仍按下的手指。
+一次事件必须同时更新所有触点再发送,避免先产生单指手势;结束/取消必须释放输入。
+标准 Touch/Pointer 处理仍需保留,供不支持整帧投递的宿主使用。
diff --git a/apps/desktop/scripts/native-trackpad-transport.verify.mjs b/apps/desktop/scripts/native-trackpad-transport.verify.mjs
new file mode 100644
index 0000000000..4f96cf2c34
--- /dev/null
+++ b/apps/desktop/scripts/native-trackpad-transport.verify.mjs
@@ -0,0 +1,99 @@
+/** Live transport tier, independent of desktop focus. This does not test AppKit.
+ * Usage: node native-trackpad-transport.verify.mjs /path/to/private-viewer-url
+ * The URL/cookie stay in memory and are never printed. Requires an already
+ * booted, authorized test device with a zoomable app in the foreground. */
+import fs from 'node:fs';
+import assert from 'node:assert/strict';
+import { createRequire } from 'node:module';
+const require = createRequire(import.meta.url);
+const WebSocket = require('ws');
+const url = new URL(fs.readFileSync(process.argv[2], 'utf8').trim());
+assert.equal(url.protocol, 'http:');
+assert(['127.0.0.1', 'localhost'].includes(url.hostname));
+const udid = url.searchParams.get('udid');
+const token = new URLSearchParams(url.hash.slice(1)).get('cindyClipboard')?.split('.')[1];
+assert(udid && token);
+const auth = await fetch(url.origin + '/control-api', {
+ method: 'POST',
+ headers: { Origin: url.origin, 'X-Cindy-Clipboard': token },
+ body: JSON.stringify({ action: 'status', udid }),
+});
+assert.equal(auth.status, 200);
+const cookie = auth.headers.get('set-cookie')?.split(';')[0];
+assert(cookie);
+const socket = new WebSocket(
+ url.origin.replace('http:', 'ws:') +
+ `/simulators/${encodeURIComponent(udid)}/stream?format=avcc&version=v2`,
+ {
+ headers: { Origin: url.origin, Cookie: cookie },
+ },
+);
+const timeout = setTimeout(() => {
+ socket.terminate();
+ process.exitCode = 1;
+}, 15000);
+let frames = [],
+ errors = 0;
+socket.on('message', (data, binary) => {
+ if (binary && [2, 3].includes(data[0])) frames.push(performance.now());
+ if (!binary) {
+ try {
+ const p = JSON.parse(data);
+ if (p.ok === false || p.type === 'error') errors++;
+ } catch {}
+ }
+});
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+try {
+ await new Promise((resolve, reject) => {
+ socket.once('open', resolve);
+ socket.once('error', reject);
+ });
+ for (let i = 0; i < 100 && frames.length < 3; i++) await sleep(50);
+ assert(frames.length >= 3, 'Video stream did not become ready');
+ const send = (phase, span) =>
+ socket.send(
+ JSON.stringify({
+ type: 'touch2-' + phase,
+ width: 440,
+ height: 956,
+ x1: 220 - span * 440,
+ x2: 220 + span * 440,
+ y1: 286.8,
+ y2: 286.8,
+ }),
+ );
+ frames = [];
+ const start = performance.now();
+ send('down', 0.12);
+ for (let i = 0; i < 100; i++) {
+ send('move', 0.12 + i * 0.0018);
+ await sleep(8);
+ }
+ for (let i = 98; i >= 0; i--) {
+ send('move', 0.12 + i * 0.0018);
+ await sleep(8);
+ }
+ send('up', 0.12);
+ await sleep(250);
+ const elapsed = performance.now() - start;
+ const gaps = frames
+ .slice(1)
+ .map((at, i) => at - frames[i])
+ .sort((a, b) => a - b);
+ console.log(
+ 'TRANSPORT_METRICS',
+ JSON.stringify({
+ frames: frames.length,
+ elapsedMs: Math.round(elapsed),
+ fps: Number(((frames.length / elapsed) * 1000).toFixed(1)),
+ p95FrameGapMs: Number(gaps[Math.floor(gaps.length * 0.95)]?.toFixed(1)),
+ errors,
+ }),
+ );
+ assert.equal(errors, 0);
+ assert(frames.length >= 70, 'Interactive video cadence is still low');
+} finally {
+ clearTimeout(timeout);
+ socket.terminate();
+}
diff --git a/apps/desktop/scripts/native-trackpad.verify.mjs b/apps/desktop/scripts/native-trackpad.verify.mjs
new file mode 100644
index 0000000000..2898cd5880
--- /dev/null
+++ b/apps/desktop/scripts/native-trackpad.verify.mjs
@@ -0,0 +1,429 @@
+/** Runtime tier: real Electron input through cross-origin + same-origin iframes.
+ * Run with node apps/desktop/scripts/native-trackpad.verify.mjs.
+ * The AppKit source is substituted with recorded normalized contacts: this does
+ * not claim physical-trackpad verification. No Cindy profile is opened. */
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import http from 'node:http';
+import assert from 'node:assert/strict';
+import { fileURLToPath } from 'node:url';
+import { createRequire } from 'node:module';
+import { execFileSync } from 'node:child_process';
+
+const require = createRequire(import.meta.url);
+const desktop = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+// Optional interactive acceptance window, backed by the same production input
+// module and the real addon. The URL file avoids printing viewer credentials.
+const viewerFile =
+ !process.versions.electron && process.argv[2] === '--viewer' ? process.argv[3] : undefined;
+if (!process.versions.electron) {
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-trackpad-verify-'));
+ try {
+ require('esbuild').buildSync({
+ entryPoints: [path.join(desktop, 'src/main/nativeTrackpad.ts')],
+ outfile: path.join(temp, 'input.cjs'),
+ bundle: true,
+ platform: 'node',
+ format: 'cjs',
+ external: ['electron'],
+ });
+ const env = { ...process.env };
+ env.CINDY_TRACKPAD_VERIFY_CONTACTS = process.argv.includes('--contacts') ? '1' : '0';
+ env.CINDY_TRACKPAD_EXERCISE = process.argv.includes('--exercise') ? '1' : '0';
+ delete env.ELECTRON_RUN_AS_NODE;
+ execFileSync(
+ require('electron'),
+ [fileURLToPath(import.meta.url), temp, ...(viewerFile ? [path.resolve(viewerFile)] : [])],
+ {
+ env,
+ stdio: 'inherit',
+ timeout: viewerFile ? undefined : 30000,
+ },
+ );
+ } finally {
+ fs.rmSync(temp, { recursive: true, force: true });
+ }
+} else {
+ void (async () => {
+ const { app, BrowserWindow } = require('electron');
+ const temp = process.argv[2];
+ app.setPath('userData', path.join(temp, 'profile'));
+ let win, server;
+ const deadline = setTimeout(() => app.exit(1), 25000);
+ try {
+ await app.whenReady();
+ const { installNativeTrackpad } = require(path.join(temp, 'input.cjs'));
+ const addon = require(path.join(desktop, 'resources/tools/trackpad/cindy-trackpad.node'));
+ assert.equal(typeof addon.start, 'function');
+ assert.equal(typeof addon.position, 'function');
+ assert.equal(typeof addon.stop, 'function');
+ addon.stop(0); // Unbound/stale capture cleanup must also be callable.
+ if (process.argv[3]) {
+ const url = fs.readFileSync(process.argv[3], 'utf8').trim(),
+ parsed = new URL(url);
+ assert.equal(parsed.protocol, 'http:');
+ assert(['127.0.0.1', 'localhost'].includes(parsed.hostname));
+ const exercise = process.env.CINDY_TRACKPAD_EXERCISE === '1';
+ if (!exercise) clearTimeout(deadline);
+ let exercisePoint, exerciseInput;
+ win = new BrowserWindow({
+ width: 900,
+ height: 1000,
+ title: '设备模拟器 · 原生双指测试',
+ webPreferences: { sandbox: true, contextIsolation: true },
+ });
+ const inputTrace = [];
+ if (exercise) {
+ const command = win.webContents.debugger.sendCommand.bind(win.webContents.debugger);
+ win.webContents.debugger.sendCommand = async (method, ...args) => {
+ try {
+ const r = await command(method, ...args);
+ inputTrace.push({
+ method,
+ node: r.node?.nodeName,
+ box: r.model?.content,
+ value: r.result?.value,
+ object: !!r.result?.objectId,
+ });
+ return r;
+ } catch (error) {
+ inputTrace.push({ method, error: String(error) });
+ throw error;
+ }
+ };
+ win.webContents.on('before-mouse-event', (_e, input) =>
+ inputTrace.push({ input: input.type }),
+ );
+ win.webContents.on('did-start-navigation', (_e, _url, inPlace, main) =>
+ inputTrace.push({ inPlace, main }),
+ );
+ }
+ installNativeTrackpad(win.webContents, win.webContents, () => true, {
+ platform: process.platform,
+ window: () => win,
+ load: () => ({
+ position: (handle) => (exercise ? exercisePoint : addon.position(handle)),
+ stop: (id) => {
+ if (!exercise) addon.stop(id);
+ },
+ start: (handle, callback) => {
+ if (exercise) {
+ exerciseInput = callback;
+ return 1;
+ }
+ const id = addon.start(handle, (packet) => {
+ const p = JSON.parse(packet);
+ if (p.phase === 'begin') console.log('NATIVE_CONTACTS_BEGIN');
+ callback(packet);
+ });
+ if (id !== null) console.log('NATIVE_CAPTURE_READY');
+ return id;
+ },
+ }),
+ });
+ win.on('page-title-updated', (event) => event.preventDefault());
+ app.on('window-all-closed', () => app.quit());
+ await win.loadURL(url);
+ win.setTitle('设备模拟器 · 原生双指测试');
+ win.show();
+ app.focus({ steal: true });
+ win.focus();
+ console.log('NATIVE_PREVIEW_READY');
+ if (exercise) {
+ // Explicit runtime tier: replay contacts through the actual viewer
+ // and its WebSocket/device transport; never presented as hardware input.
+ const find = async (frame, offset = { x: 0, y: 0 }) => {
+ const r = await frame.executeJavaScript(
+ `(()=>{const e=document.querySelector('[data-cindy-trackpad="contacts"]');if(!e)return null;const r=e.getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height};})()`,
+ );
+ if (r?.width > 0)
+ return {
+ frame,
+ x: offset.x + r.x,
+ y: offset.y + r.y,
+ width: r.width,
+ height: r.height,
+ };
+ for (const child of frame.frames) {
+ const bounds = await frame.executeJavaScript(
+ `(()=>{const e=[...document.querySelectorAll('iframe')].find(e=>e.src===${JSON.stringify(child.url)});if(!e)return null;const r=e.getBoundingClientRect();return {x:r.x,y:r.y};})()`,
+ );
+ if (bounds) {
+ const found = await find(child, { x: offset.x + bounds.x, y: offset.y + bounds.y });
+ if (found) return found;
+ }
+ }
+ };
+ let target;
+ for (let i = 0; i < 100 && !target; i++) {
+ target = await find(win.webContents.mainFrame);
+ if (!target) await new Promise((r) => setTimeout(r, 50));
+ }
+ assert(target, 'Live contact surface missing');
+ await target.frame.executeJavaScript(
+ `window.__inputProbe={sent:[],painted:0,received:0,decoded:0,raf:0};const tick=()=>{__inputProbe.raf++;requestAnimationFrame(tick)};requestAnimationFrame(tick);if(window.VideoDecoder){const decode=VideoDecoder.prototype.decode;VideoDecoder.prototype.decode=function(...args){__inputProbe.decoded++;return decode.apply(this,args);};}const originalSend=WebSocket.prototype.send;WebSocket.prototype.send=function(data){if(!this.__probed){this.__probed=true;this.addEventListener('message',e=>{if(e.data instanceof ArrayBuffer)__inputProbe.received++;});}try{const p=JSON.parse(data);if(p.type?.startsWith('touch'))__inputProbe.sent.push({at:Date.now(),...p});}catch{}return originalSend.call(this,data);};const originalDraw=CanvasRenderingContext2D.prototype.drawImage;CanvasRenderingContext2D.prototype.drawImage=function(...args){__inputProbe.painted++;return originalDraw.apply(this,args);};`,
+ );
+ for (let i = 0; i < 200; i++) {
+ if (await target.frame.executeJavaScript('__inputProbe.painted>=3')) break;
+ await new Promise((r) => setTimeout(r, 25));
+ }
+ target = await find(win.webContents.mainFrame);
+ assert(target, 'Live surface disappeared');
+ exercisePoint = { x: target.x + target.width * 0.5, y: target.y + target.height * 0.3 };
+ for (let i = 0; i < 100 && !exerciseInput; i++) {
+ if (!win.isFocused()) app.focus({ steal: true });
+ win.focus();
+ win.webContents.focus();
+ win.webContents.sendInputEvent({ type: 'mouseMove', ...exercisePoint });
+ await new Promise((r) => setTimeout(r, 10));
+ }
+ if (!exerciseInput) {
+ fs.writeFileSync(
+ '/tmp/cindy-trackpad-arm-failure.png',
+ (await win.webContents.capturePage()).toPNG(),
+ );
+ console.log(
+ 'ARM_FAILURE',
+ JSON.stringify({
+ focus: win.isFocused(),
+ guestFocus: win.webContents.isFocused(),
+ point: exercisePoint,
+ meta: await win.webContents.executeJavaScript(
+ 'document.querySelector("meta[name=cindy-native-trackpad]")?.content',
+ ),
+ trace: inputTrace.slice(-18),
+ }),
+ );
+ }
+ assert(exerciseInput, 'Live input not armed');
+ const emit = (phase, span) =>
+ exerciseInput(
+ JSON.stringify({
+ phase,
+ width: 100,
+ height: 70,
+ touches:
+ phase === 'end'
+ ? []
+ : [
+ { id: 0, x: 0.5 - span, y: 0.5 },
+ { id: 1, x: 0.5 + span, y: 0.5 },
+ ],
+ }),
+ );
+ // capturePage immediately before playback perturbs video cadence on
+ // macOS (21 vs 104 painted frames in the same ~2 s replay). Capture
+ // evidence only after measuring so the observer does not become the
+ // apparent input/stream bottleneck.
+ await target.frame.executeJavaScript(
+ '__inputProbe.painted=__inputProbe.decoded=__inputProbe.received=__inputProbe.raf=0',
+ );
+ const started = Date.now();
+ emit('begin', 0.12);
+ for (let i = 0; i < 100; i++) {
+ emit('change', 0.12 + i * 0.0018);
+ await new Promise((r) => setTimeout(r, 8));
+ }
+ for (let i = 98; i >= 0; i--) {
+ emit('change', 0.12 + i * 0.0018);
+ await new Promise((r) => setTimeout(r, 8));
+ }
+ emit('end', 0);
+ await new Promise((r) => setTimeout(r, 250));
+ const probe = await target.frame.executeJavaScript('__inputProbe');
+ console.log(
+ 'LIVE_INPUT',
+ JSON.stringify({
+ elapsed: Date.now() - started,
+ frames: probe.painted,
+ received: probe.received,
+ decoded: probe.decoded,
+ raf: probe.raf,
+ types: probe.sent.reduce((a, p) => ((a[p.type] = (a[p.type] || 0) + 1), a), {}),
+ first: probe.sent[0],
+ last: probe.sent.at(-1),
+ }),
+ );
+ assert.equal(probe.sent[0]?.type, 'touch2-down');
+ assert.equal(probe.sent.at(-1)?.type, 'touch2-up');
+ assert(!probe.sent.some((p) => p.type.startsWith('touch1')));
+ assert.equal(
+ probe.sent.length,
+ 201,
+ 'Replay interrupted (focus/navigation) or mixed with another input source',
+ );
+ assert(probe.painted >= 70, 'Full viewer video cadence is still low');
+ fs.writeFileSync(
+ '/tmp/cindy-trackpad-live-after.png',
+ (await win.webContents.capturePage()).toPNG(),
+ );
+ win.destroy();
+ clearTimeout(deadline);
+ app.exit(0);
+ }
+ return;
+ }
+ server = http.createServer((req, res) => {
+ res.setHeader('Content-Type', 'text/html');
+ const port = server.address().port;
+ if (req.url === '/outer')
+ res.end(
+ `<meta name="cindy-native-trackpad" content="touch"><iframe style="position:absolute;left:40px;top:60px;width:500px;height:600px;border:0" src="http://127.0.0.1:${port}/middle"></iframe>`,
+ );
+ else if (req.url === '/middle')
+ res.end(
+ '<iframe style="position:absolute;left:10px;top:10px;width:480px;height:580px;border:0" src="/screen"></iframe>',
+ );
+ else
+ res.end(`<style>body{margin:0}canvas{position:absolute;left:20px;top:10px;width:400px;height:500px;touch-action:none}</style><canvas data-cindy-trackpad="${process.env.CINDY_TRACKPAD_VERIFY_CONTACTS === '1' ? 'contacts' : ''}"></canvas><script>
+ window.events=[];for(const type of ['touchstart','touchmove','touchend','touchcancel'])document.querySelector('canvas').addEventListener(type,e=>{e.preventDefault();events.push({type,at:Date.now(),touches:[...e.touches].map(t=>({id:t.identifier,x:t.clientX,y:t.clientY}))});},{passive:false});
+ let count=0;document.querySelector('canvas').addEventListener('cindy-trackpad',e=>{
+ const f=e.detail,type=f.phase==='begin'?'touchstart':f.phase==='cancel'?'touchcancel':f.phase==='end'||f.touches.length<count?'touchend':'touchmove';
+ count=f.touches.length;events.push({type,at:Date.now(),touches:f.touches});
+ });
+ </script>`);
+ });
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
+ win = new BrowserWindow({
+ width: 700,
+ height: 800,
+ webPreferences: { sandbox: true, contextIsolation: true },
+ });
+ const wc = win.webContents;
+ const command = wc.debugger.sendCommand.bind(wc.debugger);
+ wc.debugger.sendCommand = async (method, ...args) => {
+ try {
+ const result = await command(method, ...args);
+ if (method === 'Input.dispatchTouchEvent' || method === 'DOM.getBoxModel')
+ console.log(method, JSON.stringify(args), JSON.stringify(result));
+ return result;
+ } catch (error) {
+ console.error('CDP', method, error);
+ throw error;
+ }
+ };
+ let callback, armed;
+ const ready = new Promise((r) => (armed = r));
+ installNativeTrackpad(wc, wc, () => true, {
+ platform: 'darwin',
+ load: () => ({
+ position: () => ({ x: 270, y: 330 }),
+ start: (_handle, cb) => {
+ console.log('capture armed');
+ callback = cb;
+ armed();
+ return 1;
+ },
+ stop: () => {},
+ }),
+ window: () => win,
+ });
+ await win.loadURL(`http://localhost:${server.address().port}/outer`);
+ await wc.capturePage(); // Wait for the nested frame's first compositor frame.
+ win.show();
+ win.focus();
+ wc.focus();
+ for (let i = 0; i < 100 && !callback; i++) {
+ win.focus();
+ wc.focus();
+ wc.sendInputEvent({ type: 'mouseMove', x: 270, y: 330 });
+ await new Promise((r) => setTimeout(r, 10));
+ }
+ assert(callback, 'Native surface not armed after focus/DOM readiness');
+ await ready;
+ const frame = wc.mainFrame.frames[0].frames[0];
+ const points = [
+ { id: 0, x: 0.3, y: 0.5 },
+ { id: 1, x: 0.7, y: 0.5 },
+ ];
+ const emit = (phase, touches) => {
+ console.log('emit', phase);
+ callback(JSON.stringify({ phase, touches, width: 100, height: 70 }));
+ };
+ const until = async (predicate) => {
+ for (let i = 0; i < 100; i++) {
+ const events = await frame.executeJavaScript('events');
+ if (predicate(events)) return events;
+ await new Promise((r) => setTimeout(r, 10));
+ }
+ throw Error(`Touch delivery did not settle; focused=${wc.isFocused()}/${win.isFocused()}`);
+ };
+ emit('begin', points);
+ await until((e) => e.some((v) => v.type === 'touchstart' && v.touches.length === 2));
+ emit('change', [points[0], { id: 1, x: 0.8, y: 0.6 }]);
+ const events = await until((e) => e.some((v) => v.type === 'touchmove'));
+ const start = events.find((v) => v.touches.length === 2).touches;
+ const moved = events.findLast((v) => v.type === 'touchmove').touches;
+ assert.deepEqual(moved[0], start[0]);
+ assert.equal(Math.round(moved[1].x - start[1].x), 50);
+ assert.equal(Math.round(moved[1].y - start[1].y), 35);
+ // Runtime tier: measure sustained input, not just eventual correctness.
+ // Each position identifies its sample across the real renderer boundary.
+ const sent = new Map();
+ for (let i = 0; i < 120; i++) {
+ const x = 0.55 + i / 1000;
+ sent.set(Math.round((start[1].x + (x - 0.7) * 500) * 10), Date.now());
+ emit('change', [points[0], { id: 1, x, y: 0.5 }]);
+ await new Promise((r) => setTimeout(r, 8));
+ }
+ const measured = await until((e) =>
+ e.some(
+ (v) => v.type === 'touchmove' && Math.abs(v.touches[1]?.x - (start[1].x - 15.5)) < 0.1,
+ ),
+ );
+ const latency = measured
+ .filter((v) => v.type === 'touchmove' && v.touches.length === 2)
+ .map((v) =>
+ sent.has(Math.round(v.touches[1].x * 10))
+ ? v.at - sent.get(Math.round(v.touches[1].x * 10))
+ : null,
+ )
+ .filter((v) => v !== null)
+ .sort((a, b) => a - b);
+ console.log(
+ 'INPUT_METRICS',
+ JSON.stringify({
+ sent: 120,
+ received: latency.length,
+ p50: latency[Math.floor(latency.length * 0.5)],
+ p95: latency[Math.floor(latency.length * 0.95)],
+ max: latency.at(-1),
+ initialContacts: measured
+ .filter((v) => v.type === 'touchstart')
+ .map((v) => v.touches.length),
+ }),
+ );
+ if (process.env.CINDY_TRACKPAD_VERIFY_CONTACTS === '1') {
+ assert.deepEqual(
+ measured.filter((v) => v.type === 'touchstart').map((v) => v.touches.length),
+ [2],
+ );
+ assert.equal(latency.length, 120);
+ }
+ emit('change', [points[0]]);
+ await until((e) => e.some((v) => v.type === 'touchend' && v.touches.length === 1));
+ emit('end', []);
+ await until((e) => e.some((v) => v.type === 'touchend' && v.touches.length === 0));
+ emit('begin', points);
+ await until(
+ (e) => e.filter((v) => v.type === 'touchstart' && v.touches.length === 2).length === 2,
+ );
+ win.emit('blur');
+ await until((e) => e.some((v) => v.type === 'touchcancel'));
+ console.log(
+ 'PASS: native addon loads; nested iframe mapping, stationary finger, independent motion, liftoff and blur cancellation',
+ );
+ win.destroy();
+ server.close();
+ clearTimeout(deadline);
+ app.exit(0);
+ } catch (error) {
+ console.error(error);
+ win?.destroy();
+ server?.close();
+ clearTimeout(deadline);
+ app.exit(1);
+ }
+ })();
+}
diff --git a/apps/desktop/src/main/__tests__/nativeTrackpad.test.ts b/apps/desktop/src/main/__tests__/nativeTrackpad.test.ts
new file mode 100644
index 0000000000..b937198351
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/nativeTrackpad.test.ts
@@ -0,0 +1,403 @@
+import { EventEmitter } from 'node:events';
+import { expect, test, vi } from 'vitest';
+import type { WebContents, BrowserWindow } from 'electron';
+import { installNativeTrackpad } from '../nativeTrackpad';
+
+// Unit tier: production input entry with native/CDP endpoints. No OS I/O or sleeps.
+const settle = async () => {
+ for (let i = 0; i < 30; i++) await Promise.resolve();
+};
+function setup({ optIn = true, occupied = false, iframe = false, contacts = false } = {}) {
+ let focused = true,
+ current = true;
+ const host = Object.assign(new EventEmitter(), {
+ isDestroyed: () => false,
+ getZoomFactor: (): number => 1,
+ executeJavaScript: vi.fn(async (): Promise<any> => ({
+ x: 770,
+ y: 46,
+ width: 510,
+ height: 754,
+ })),
+ });
+ const debug = Object.assign(new EventEmitter(), {
+ isAttached: () => occupied,
+ attach: vi.fn(),
+ detach: vi.fn(),
+ sendCommand: vi.fn(
+ async (method: string, _args?: Record<string, unknown>, session?: string): Promise<any> => {
+ if (method === 'Target.setAutoAttach' && iframe && !session)
+ debug.emit('message', {}, 'Target.attachedToTarget', {
+ targetInfo: { type: 'iframe', targetId: 'child' },
+ sessionId: 'child-session',
+ });
+ if (method === 'DOM.getNodeForLocation') return { backendNodeId: 1 };
+ if (method === 'DOM.resolveNode') return { object: { objectId: 'node' } };
+ if (
+ method === 'Runtime.callFunctionOn' &&
+ String(_args?.functionDeclaration).includes('getAttribute')
+ )
+ return { result: { value: contacts ? 'contacts' : '' } };
+ if (
+ method === 'Runtime.callFunctionOn' &&
+ String(_args?.functionDeclaration).includes('getBoundingClientRect')
+ )
+ return { result: { value: { x: 20, y: 10 } } };
+ if (method === 'Runtime.callFunctionOn')
+ return { result: { objectId: iframe && !session ? undefined : 'surface' } };
+ if (method === 'DOM.describeNode')
+ return { node: { nodeName: 'IFRAME', frameId: 'child' } };
+ if (method === 'DOM.getBoxModel')
+ return {
+ model: {
+ content:
+ iframe && !session
+ ? [40, 60, 540, 60, 540, 660, 40, 660]
+ : [30, 20, 430, 20, 430, 520, 30, 520],
+ },
+ };
+ return {};
+ },
+ ),
+ });
+ const guest = Object.assign(new EventEmitter(), {
+ id: 6,
+ debugger: debug,
+ isDestroyed: () => false,
+ isFocused: () => focused,
+ getZoomFactor: (): number => 1,
+ executeJavaScript: vi.fn(async () => optIn),
+ });
+ const window = Object.assign(new EventEmitter(), {
+ isFocused: () => true,
+ isVisible: () => true,
+ getNativeWindowHandle: () => Buffer.alloc(8),
+ });
+ const callbacks: ((p: string) => void)[] = [];
+ const native = {
+ position: undefined as undefined | (() => { x: number; y: number }),
+ start: vi.fn((_h: Buffer, cb: (p: string) => void) => {
+ callbacks.push(cb);
+ return callbacks.length;
+ }),
+ stop: vi.fn(),
+ };
+ installNativeTrackpad(
+ host as unknown as WebContents,
+ guest as unknown as WebContents,
+ () => current,
+ {
+ platform: 'darwin',
+ load: () => native,
+ window: () => window as unknown as BrowserWindow,
+ },
+ );
+ const hover = async () => {
+ guest.emit('before-mouse-event', {}, { type: 'mouseMove', x: 270, y: 330 });
+ await settle();
+ };
+ const arm = async () => {
+ guest.emit('dom-ready');
+ await settle();
+ await hover();
+ };
+ const points = [
+ { id: 0, x: 0.3, y: 0.5 },
+ { id: 1, x: 0.7, y: 0.5 },
+ ];
+ const emit = (phase: string, touches = points, index = callbacks.length - 1) =>
+ callbacks[index](JSON.stringify({ phase, touches, width: 100, height: 70 }));
+ const inputs = () =>
+ debug.sendCommand.mock.calls
+ .filter(([m]) => m === 'Input.dispatchTouchEvent')
+ .map(([, p]) => p);
+ return {
+ host,
+ guest,
+ debug,
+ window,
+ native,
+ callbacks,
+ arm,
+ hover,
+ emit,
+ inputs,
+ points,
+ focus: (v: boolean) => (focused = v),
+ owner: (v: boolean) => (current = v),
+ };
+}
+
+test('requires an opted-in focused surface and leaves another debugger alone', async () => {
+ for (const options of [{ optIn: false }, { occupied: true }]) {
+ const h = setup(options);
+ await h.arm();
+ expect(h.native.start).not.toHaveBeenCalled();
+ expect(h.debug.detach).not.toHaveBeenCalled();
+ }
+ const h = setup();
+ h.focus(false);
+ await h.arm();
+ expect(h.native.start).not.toHaveBeenCalled();
+ h.focus(true);
+ h.owner(false);
+ await h.hover();
+ expect(h.native.start).not.toHaveBeenCalled();
+ h.owner(true);
+ await h.hover();
+ expect(h.native.start).toHaveBeenCalledOnce();
+});
+
+// User regression: a portrait sidebar compressed translation to its narrow
+// width. Through the production entry, verify useful travel in both axes while
+// retaining pair geometry (pinch ratio/rotation) and a stationary finger.
+// Unit tier; previous independent-motion cases did not test portrait gain.
+test('portrait mapping uses the long edge without changing pinch ratio or rotation', async () => {
+ const h = setup();
+ await h.arm();
+ const pair = [
+ { id: 0, x: 0.4, y: 0.5 },
+ { id: 1, x: 0.6, y: 0.5 },
+ ];
+ h.emit('begin', pair);
+ h.emit(
+ 'change',
+ pair.map((p) => ({ ...p, x: p.x + 0.05, y: p.y + 0.1 })),
+ );
+ const start = h.inputs()[0]!.touchPoints as { x: number; y: number }[];
+ const moved = h.inputs()[1]!.touchPoints as { x: number; y: number }[];
+ expect(moved[0].x - start[0].x).toBeCloseTo(25);
+ expect(moved[0].y - start[0].y).toBeCloseTo(35);
+ expect(moved[1].x - moved[0].x).toBeCloseTo(start[1].x - start[0].x);
+ h.emit('change', [
+ { id: 0, x: 0.55, y: 0.6 - 0.1 / 0.7 },
+ { id: 1, x: 0.55, y: 0.6 + 0.1 / 0.7 },
+ ]);
+ const rotated = h.inputs()[2]!.touchPoints as { x: number; y: number }[];
+ expect(rotated[1].x - rotated[0].x).toBeCloseTo(0);
+ expect(rotated[1].y - rotated[0].y).toBeCloseTo(start[1].x - start[0].x);
+ h.emit('change', [
+ { id: 0, x: 0.55, y: 0.6 - 0.15 / 0.7 },
+ { id: 1, x: 0.55, y: 0.6 + 0.15 / 0.7 },
+ ]);
+ const expanded = h.inputs()[3]!.touchPoints as { x: number; y: number }[];
+ expect((expanded[1].y - expanded[0].y) / (start[1].x - start[0].x)).toBeCloseTo(1.5);
+});
+
+test('maps independent contacts without scale hysteresis, including iframe offsets and liftoff', async () => {
+ const h = setup({ iframe: true });
+ await h.arm();
+ h.emit('begin');
+ expect(h.inputs()[0]).toMatchObject({
+ type: 'touchStart',
+ touchPoints: [
+ { id: 0, x: 170, y: 330 },
+ { id: 1, x: 370, y: 330 },
+ ],
+ });
+ h.emit('change', [h.points[0], { id: 1, x: 0.8, y: 0.6 }]);
+ expect(h.inputs()[1]).toMatchObject({
+ type: 'touchMove',
+ touchPoints: [
+ { id: 0, x: 170, y: 330 },
+ { id: 1, x: expect.closeTo(420, 8), y: 365 },
+ ],
+ });
+ h.emit('change', [h.points[0], { id: 1, x: 0.6, y: 0.5 }]);
+ expect(h.inputs()[2]).toMatchObject({
+ touchPoints: [
+ { id: 0, x: 170, y: 330 },
+ { id: 1, x: expect.closeTo(320, 8), y: 330 },
+ ],
+ });
+ h.emit('change', [h.points[0]]);
+ expect(h.inputs()[3]).toMatchObject({
+ type: 'touchEnd',
+ touchPoints: [{ id: 1, x: expect.closeTo(320, 8), y: 330 }],
+ });
+ h.emit('end', []);
+ expect(h.inputs()[4]).toMatchObject({
+ type: 'touchEnd',
+ touchPoints: [{ id: 0, x: 170, y: 330 }],
+ });
+});
+
+test('owner revocation cancels active contacts; late frames never cross a navigation', async () => {
+ const h = setup();
+ await h.arm();
+ h.emit('begin');
+ h.owner(false);
+ h.emit('change');
+ expect(h.native.stop).toHaveBeenCalledWith(1);
+ expect(h.inputs().at(-1)).toEqual({ type: 'touchCancel', touchPoints: [] });
+ h.owner(true);
+ await h.hover();
+ h.emit('begin');
+ h.guest.emit('did-start-navigation', {}, 'https://example.test', false, true);
+ const count = h.inputs().length;
+ h.emit('change', h.points, 1);
+ expect(h.inputs()).toHaveLength(count);
+ expect(h.native.stop).toHaveBeenCalledWith(2);
+});
+
+test('malformed native contacts and mouse clicks release input', async () => {
+ const h = setup();
+ await h.arm();
+ h.emit('begin');
+ h.emit('change', [{ id: 0, x: 2, y: 0.5 }]);
+ expect(h.inputs().at(-1)).toEqual({ type: 'touchCancel', touchPoints: [] });
+ await h.hover();
+ h.emit('begin');
+ h.guest.emit('before-mouse-event', {}, { type: 'mouseDown', x: 0, y: 0 });
+ expect(h.native.stop).toHaveBeenCalledWith(2);
+ expect(h.inputs().at(-1)).toEqual({ type: 'touchCancel', touchPoints: [] });
+});
+
+// Regression: Chromium split one native begin into 1/2 contacts and held moves
+// for input ACK. A contacts surface gets an atomic pair in its own frame space.
+test('atomic contacts preserve the pair and cancel before releasing their frame object', async () => {
+ const h = setup({ iframe: true, contacts: true });
+ await h.arm();
+ h.emit('begin');
+ h.emit('change', [h.points[0], { id: 1, x: 0.8, y: 0.6 }]);
+ const packets = () =>
+ h.debug.sendCommand.mock.calls.filter(
+ ([m, p]) => m === 'Runtime.callFunctionOn' && p?.arguments,
+ );
+ expect(packets()[0]).toMatchObject([
+ 'Runtime.callFunctionOn',
+ {
+ arguments: [
+ {
+ value: {
+ phase: 'begin',
+ touches: [
+ { id: 0, x: 120, y: 260 },
+ { id: 1, x: 320, y: 260 },
+ ],
+ },
+ },
+ ],
+ },
+ 'child-session',
+ ]);
+ expect(packets()[1][1]).toMatchObject({
+ arguments: [
+ {
+ value: {
+ phase: 'change',
+ touches: [
+ { id: 0, x: 120, y: 260 },
+ { id: 1, x: expect.closeTo(370, 8), y: 295 },
+ ],
+ },
+ },
+ ],
+ });
+ expect(h.inputs()).toEqual([]);
+ h.window.emit('blur');
+ expect(packets().at(-1)?.[1]).toMatchObject({
+ arguments: [{ value: { phase: 'cancel', touches: [] } }],
+ });
+ const n = packets().length;
+ h.emit('change');
+ await settle();
+ expect(packets()).toHaveLength(n);
+ expect(h.debug.sendCommand).toHaveBeenCalledWith(
+ 'Runtime.releaseObject',
+ { objectId: 'surface' },
+ 'child-session',
+ );
+});
+
+test('reversing at a screen edge moves immediately without unwinding offscreen distance', async () => {
+ const h = setup();
+ await h.arm();
+ h.emit('begin');
+ h.emit('change', [h.points[0], { id: 1, x: 1, y: 0.5 }]);
+ expect(h.inputs().at(-1)?.touchPoints).toMatchObject([{ id: 0 }, { id: 1, x: 429.5 }]);
+ h.emit('change', [h.points[0], { id: 1, x: 0.99, y: 0.5 }]);
+ expect(h.inputs().at(-1)?.touchPoints).toMatchObject([{ id: 0 }, { id: 1, x: 424.5 }]);
+});
+
+test('same-document route updates cancel old contacts and rearm the opted-in surface', async () => {
+ const h = setup({ contacts: true });
+ await h.arm();
+ h.emit('begin');
+ h.guest.emit('did-start-navigation', {}, 'http://localhost/control?udid=selected', true, true);
+ await h.hover();
+ expect(h.native.start).toHaveBeenCalledTimes(2);
+ const before = h.debug.sendCommand.mock.calls.length;
+ h.emit('change', h.points, 0);
+ expect(h.debug.sendCommand.mock.calls).toHaveLength(before);
+});
+
+// A route update or initial focus change can precede the async opt-in reply.
+// It must not disable this document forever; a real navigation must reject it.
+test('pending document opt-in survives input teardown but never a document replacement', async () => {
+ for (const replacement of [false, true]) {
+ const h = setup({ contacts: true });
+ let resolve!: (value: boolean) => void;
+ h.guest.executeJavaScript.mockImplementationOnce(
+ () => new Promise<boolean>((done) => (resolve = done)),
+ );
+ h.guest.emit('dom-ready');
+ h.window.emit('blur');
+ h.guest.emit('did-start-navigation', {}, 'https://example.test/viewer', !replacement, true);
+ resolve(true);
+ await settle();
+ await h.hover();
+ expect(h.native.start).toHaveBeenCalledTimes(replacement ? 0 : 1);
+ }
+});
+
+test('embedded guest subtracts its host viewport origin before native hit testing', async () => {
+ const h = setup();
+ h.native.position = () => ({ x: 1040, y: 376 });
+ await h.arm();
+ expect(h.debug.sendCommand).toHaveBeenCalledWith(
+ 'DOM.getNodeForLocation',
+ { x: 270, y: 330, includeUserAgentShadowDOM: true },
+ undefined,
+ );
+ h.emit('begin');
+ expect(h.inputs()[0]?.touchPoints).toMatchObject([
+ { x: 170, y: 330 },
+ { x: 370, y: 330 },
+ ]);
+});
+
+test('embedded coordinates respect independent host/guest zoom and reject a missing view', async () => {
+ const h = setup();
+ h.host.getZoomFactor = () => 1.25;
+ h.guest.getZoomFactor = () => 2;
+ h.native.position = () => ({ x: 1502.5, y: 717.5 });
+ await h.arm();
+ expect(h.debug.sendCommand).toHaveBeenCalledWith(
+ 'DOM.getNodeForLocation',
+ { x: 270, y: 330, includeUserAgentShadowDOM: true },
+ undefined,
+ );
+ const missing = setup();
+ missing.native.position = () => ({ x: 1040, y: 376 });
+ missing.host.executeJavaScript.mockResolvedValue(null);
+ await missing.arm();
+ expect(missing.native.start).not.toHaveBeenCalled();
+});
+
+test('blur invalidates an outstanding embedded pointer conversion', async () => {
+ const h = setup();
+ h.native.position = () => ({ x: 1040, y: 376 });
+ let resolve!: (v: any) => void;
+ h.host.executeJavaScript.mockImplementation(
+ () =>
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ await h.arm();
+ h.window.emit('blur');
+ resolve({ x: 770, y: 46, width: 510, height: 754 });
+ await settle();
+ expect(h.native.start).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/main/__tests__/webview-security.test.ts b/apps/desktop/src/main/__tests__/webview-security.test.ts
index b284cb2508..231d8c6da3 100644
--- a/apps/desktop/src/main/__tests__/webview-security.test.ts
+++ b/apps/desktop/src/main/__tests__/webview-security.test.ts
@@ -27,6 +27,9 @@ const nativeSurfaceMocks = vi.hoisted(() => ({
attribute: vi.fn(),
}));
+// Native capture's focus/frame/lifecycle contract has its own injected tests.
+vi.mock('../nativeTrackpad', () => ({ installNativeTrackpad: vi.fn() }));
+
vi.mock('../rsb-browser-bridge/native-popup-surfaces', () => ({
createRsbNativePopupSurface: nativeSurfaceMocks.create,
attributeRsbNativePopupSurface: nativeSurfaceMocks.attribute,
diff --git a/apps/desktop/src/main/nativeTrackpad.ts b/apps/desktop/src/main/nativeTrackpad.ts
new file mode 100644
index 0000000000..19d66d6c0c
--- /dev/null
+++ b/apps/desktop/src/main/nativeTrackpad.ts
@@ -0,0 +1,526 @@
+import path from 'node:path';
+import { createRequire } from 'node:module';
+import { app, BrowserWindow, type WebContents } from 'electron';
+import { isNativeTrackpadFrame, type NativeTrackpadFrame } from '../shared/nativeTrackpad';
+import { createLogger } from './logger';
+
+interface NativeInput {
+ start(handle: Buffer, callback: (frame: string) => void): number | null;
+ stop(id: number): void;
+ position?(handle: Buffer): Point | null;
+}
+interface Point {
+ x: number;
+ y: number;
+}
+interface Rect extends Point {
+ width: number;
+ height: number;
+}
+interface Contact extends Point {
+ id: number;
+ radiusX: number;
+ radiusY: number;
+ force: number;
+}
+// One native sample stays one DOM event. Chromium's touch injection otherwise
+// splits the initial pair into 1/2 contacts and delays moves until input ACK.
+const deliverContacts = `function(frame) {
+ if (this.isConnected && this.getAttribute('data-cindy-trackpad') === 'contacts')
+ this.dispatchEvent(new CustomEvent('cindy-trackpad', {detail: frame}));
+}`;
+const requireNative = createRequire(__filename);
+const log = createLogger('nativeTrackpad');
+let native: NativeInput | null | undefined;
+function load(): NativeInput | null {
+ if (native !== undefined) return native;
+ try {
+ const base = app.isPackaged ? process.resourcesPath : path.join(app.getAppPath(), 'resources');
+ native = requireNative(path.join(base, 'tools/trackpad/cindy-trackpad.node')) as NativeInput;
+ } catch {
+ log.warn('Native trackpad unavailable; retaining wheel gestures');
+ native = null;
+ }
+ return native;
+}
+const inside = (r: Rect, p: Point) =>
+ p.x >= r.x && p.x < r.x + r.width && p.y >= r.y && p.y < r.y + r.height;
+
+/** Opt-in native input. CDP hit testing crosses iframe origins without opening
+ * a JS/IPC bridge in the ghost sandbox. Only focused/key-window input is sent. */
+export function installNativeTrackpad(
+ host: WebContents,
+ guest: WebContents,
+ isCurrent = () => true,
+ deps = {
+ platform: process.platform as string,
+ load,
+ window: (wc: WebContents) => BrowserWindow.fromWebContents(wc),
+ },
+): void {
+ if (deps.platform !== 'darwin') return;
+ let enabled = false,
+ attached = false,
+ locating = false,
+ epoch = 0;
+ let documentEpoch = 0;
+ let capture: number | null = null,
+ bridge: NativeInput | null = null,
+ rect: Rect | null = null;
+ let pointer: Point = { x: 0, y: 0 };
+ const frames = new Map<string, string>();
+ let surface: { objectId: string; session?: string; offset: Point } | null = null;
+ let pointerRead = 0;
+ let gesture: {
+ centre: Point;
+ anchor: Point;
+ ratio: number;
+ distance: number;
+ points: Contact[];
+ raw: NativeTrackpadFrame['touches'];
+ } | null = null;
+ const current = () => {
+ try {
+ return !guest.isDestroyed() && !host.isDestroyed() && isCurrent() && guest.isFocused();
+ } catch {
+ return false;
+ }
+ };
+ const cancelTouches = () => {
+ const pending =
+ gesture && attached && !guest.isDestroyed()
+ ? surface
+ ? dispatchContacts('cancel', [])
+ : guest.debugger
+ .sendCommand('Input.dispatchTouchEvent', { type: 'touchCancel', touchPoints: [] })
+ .catch(() => {})
+ : Promise.resolve();
+ gesture = null;
+ return pending;
+ };
+ const stop = () => {
+ epoch++;
+ pointerRead++;
+ if (capture !== null) bridge?.stop(capture);
+ capture = null;
+ rect = null;
+ const cancelled = cancelTouches();
+ const previous = surface;
+ surface = null;
+ if (previous && attached && !guest.isDestroyed())
+ void cancelled
+ .then(() =>
+ guest.debugger.sendCommand(
+ 'Runtime.releaseObject',
+ { objectId: previous.objectId },
+ previous.session,
+ ),
+ )
+ .catch(() => {});
+ return cancelled;
+ };
+ const dispatchContacts = (phase: string, points: Contact[]) => {
+ const target = surface!;
+ return guest.debugger
+ .sendCommand(
+ 'Runtime.callFunctionOn',
+ {
+ objectId: target.objectId,
+ functionDeclaration: deliverContacts,
+ arguments: [
+ {
+ value: {
+ phase,
+ touches: points.map((p) => ({
+ id: p.id,
+ x: p.x - target.offset.x,
+ y: p.y - target.offset.y,
+ })),
+ },
+ },
+ ],
+ },
+ target.session,
+ )
+ .then(() => {})
+ .catch(() => {
+ // Clear the gesture before teardown so a failed cancel cannot recurse.
+ if (surface === target) {
+ gesture = null;
+ detach();
+ }
+ });
+ };
+ const detach = () => {
+ const cancelled = stop(),
+ stamp = epoch;
+ // Deliver the release before closing CDP. A new capture supersedes teardown.
+ void cancelled.then(() => {
+ if (stamp !== epoch) return;
+ frames.clear();
+ if (attached && !guest.isDestroyed()) {
+ attached = false;
+ guest.debugger.detach();
+ }
+ });
+ };
+ const send = (packet: NativeTrackpadFrame, stamp: number) => {
+ if (stamp !== epoch) return;
+ if (!current() || !rect) {
+ stop();
+ return;
+ }
+ if (packet.phase === 'cancel') {
+ void cancelTouches();
+ return;
+ }
+ if (packet.phase === 'begin') {
+ log.debug('Native contact sequence began', { guestId: guest.id });
+ const [a, b] = packet.touches;
+ gesture = {
+ centre: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 },
+ anchor: { ...pointer },
+ ratio: packet.height! / packet.width!,
+ // Use the long edge for both axes: portrait viewers otherwise shrink
+ // all motion to their narrow width. One uniform scale preserves each
+ // finger, pinch ratios and angles; do not accelerate only the centroid.
+ distance: Math.max(rect.width, rect.height),
+ points: [],
+ raw: [],
+ };
+ }
+ if (!gesture) return;
+ const g = gesture,
+ r = rect,
+ clip = (v: number, min: number, max: number) => Math.max(min + 0.5, Math.min(max - 0.5, v));
+ const touchPoints = packet.touches.map((p) => {
+ const previous = g.points.find((t) => t.id === p.id);
+ const raw = g.raw.find((t) => t.id === p.id);
+ // Consume movement at the boundary instead of accumulating an invisible
+ // overshoot. Even a tiny reversal then moves the contact immediately.
+ const origin = previous && raw ? previous : g.anchor;
+ const from = previous && raw ? raw : g.centre;
+ return {
+ id: p.id,
+ x: clip(origin.x + (p.x - from.x) * g.distance, r.x, r.x + r.width),
+ y: clip(origin.y + (p.y - from.y) * g.distance * g.ratio, r.y, r.y + r.height),
+ radiusX: 1,
+ radiusY: 1,
+ force: 1,
+ };
+ });
+ g.raw = packet.touches;
+ // CDP touchEnd names the released contacts, not the remaining ones.
+ const released = g.points.filter((p) => !touchPoints.some((t) => t.id === p.id));
+ const type =
+ packet.phase === 'begin'
+ ? 'touchStart'
+ : packet.phase === 'end' || released.length
+ ? 'touchEnd'
+ : 'touchMove';
+ g.points = touchPoints;
+ if (packet.phase === 'end') gesture = null;
+ if (surface) {
+ void dispatchContacts(packet.phase, touchPoints);
+ return;
+ }
+ void guest.debugger
+ .sendCommand('Input.dispatchTouchEvent', {
+ type,
+ touchPoints: type === 'touchEnd' ? released : touchPoints,
+ })
+ .catch(() => {
+ if (stamp === epoch) detach();
+ });
+ };
+ const locate = async () => {
+ if (!enabled || locating || !current()) return;
+ if (rect && inside(rect, pointer) && capture !== null) return;
+ stop();
+ const win = deps.window(host);
+ if (!win || !win.isFocused() || !win.isVisible()) return;
+ bridge = deps.load();
+ if (!bridge) return;
+ if (!attached) {
+ // Never borrow or detach another feature's debugger session.
+ if (guest.debugger.isAttached()) return;
+ try {
+ guest.debugger.attach('1.3');
+ attached = true;
+ } catch {
+ return;
+ }
+ }
+ locating = true;
+ const stamp = epoch,
+ point = { ...pointer };
+ const objects: { objectId: string; session?: string }[] = [];
+ try {
+ await guest.debugger.sendCommand('Target.setAutoAttach', {
+ autoAttach: true,
+ waitForDebuggerOnStart: false,
+ flatten: true,
+ });
+ let session: string | undefined,
+ offset = { x: 0, y: 0 },
+ surfaceId: string | undefined;
+ // An out-of-process iframe is a separate CDP target. Hit-test down the
+ // visible frame chain, retaining offsets in the guest's viewport space.
+ for (let depth = 0; depth < 8; depth++) {
+ const hit = await guest.debugger.sendCommand(
+ 'DOM.getNodeForLocation',
+ {
+ x: Math.round(point.x - offset.x),
+ y: Math.round(point.y - offset.y),
+ includeUserAgentShadowDOM: true,
+ },
+ session,
+ );
+ const resolved = await guest.debugger.sendCommand(
+ 'DOM.resolveNode',
+ { backendNodeId: hit.backendNodeId },
+ session,
+ );
+ const objectId = resolved.object?.objectId;
+ if (!objectId) return;
+ objects.push({ objectId, session });
+ const surface = await guest.debugger.sendCommand(
+ 'Runtime.callFunctionOn',
+ {
+ objectId,
+ functionDeclaration:
+ 'function(){return this.closest?.("[data-cindy-trackpad]")||null;}',
+ },
+ session,
+ );
+ surfaceId = surface.result?.objectId;
+ if (surfaceId) {
+ objects.push({ objectId: surfaceId, session });
+ break;
+ }
+ const { node } = await guest.debugger.sendCommand(
+ 'DOM.describeNode',
+ { backendNodeId: hit.backendNodeId },
+ session,
+ );
+ if (node?.nodeName !== 'IFRAME' || !node.frameId) return;
+ const { model } = await guest.debugger.sendCommand(
+ 'DOM.getBoxModel',
+ { objectId },
+ session,
+ );
+ if (!model?.content) return;
+ offset = { x: offset.x + model.content[0], y: offset.y + model.content[1] };
+ const child = frames.get(node.frameId);
+ if (!child) return;
+ session = child;
+ await guest.debugger.sendCommand(
+ 'Target.setAutoAttach',
+ { autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
+ session,
+ );
+ }
+ if (!surfaceId) return;
+ const { model } = await guest.debugger.sendCommand(
+ 'DOM.getBoxModel',
+ { objectId: surfaceId },
+ session,
+ );
+ const q = model?.content;
+ if (!Array.isArray(q) || q.length !== 8 || q.some((v) => !Number.isFinite(v))) return;
+ const xs = [q[0], q[2], q[4], q[6]],
+ ys = [q[1], q[3], q[5], q[7]];
+ const candidate = {
+ x: offset.x + Math.min(...xs),
+ y: offset.y + Math.min(...ys),
+ width: Math.max(...xs) - Math.min(...xs),
+ height: Math.max(...ys) - Math.min(...ys),
+ };
+ if (
+ stamp !== epoch ||
+ !current() ||
+ candidate.width < 2 ||
+ candidate.height < 2 ||
+ !inside(candidate, pointer)
+ )
+ return;
+ rect = candidate;
+ const mode = await guest.debugger.sendCommand(
+ 'Runtime.callFunctionOn',
+ {
+ objectId: surfaceId,
+ functionDeclaration: 'function(){return this.getAttribute("data-cindy-trackpad");}',
+ returnByValue: true,
+ },
+ session,
+ );
+ if (stamp !== epoch || !current()) return;
+ if (mode.result?.value === 'contacts') {
+ // DOM event coordinates are relative to the element's own frame, not
+ // its OOPIF target (which can itself contain same-origin frames).
+ const bounds = await guest.debugger.sendCommand(
+ 'Runtime.callFunctionOn',
+ {
+ objectId: surfaceId,
+ functionDeclaration:
+ 'function(){const r=this.getBoundingClientRect();return {x:r.x,y:r.y};}',
+ returnByValue: true,
+ },
+ session,
+ );
+ if (stamp !== epoch || !current()) return;
+ const local = bounds.result?.value;
+ if (!local || !Number.isFinite(local.x) || !Number.isFinite(local.y)) return;
+ surface = {
+ objectId: surfaceId,
+ session,
+ offset: { x: candidate.x - local.x, y: candidate.y - local.y },
+ };
+ }
+ capture = bridge.start(win.getNativeWindowHandle(), (text) => {
+ if (stamp !== epoch) return;
+ let packet: unknown;
+ try {
+ packet = JSON.parse(text);
+ } catch {
+ stop();
+ return;
+ }
+ if (!isNativeTrackpadFrame(packet)) {
+ stop();
+ return;
+ }
+ send(packet, stamp);
+ });
+ log.debug('Native contact capture armed', { guestId: guest.id, capture });
+ } catch {
+ if (stamp === epoch) stop();
+ } finally {
+ for (const { objectId, session } of objects)
+ if (objectId !== surface?.objectId && attached && !guest.isDestroyed())
+ void guest.debugger
+ .sendCommand('Runtime.releaseObject', { objectId }, session)
+ .catch(() => {});
+ locating = false;
+ }
+ };
+ guest.on('dom-ready', () => {
+ enabled = false;
+ detach();
+ // Opt-in belongs to the document, not the current focus/capture session.
+ // Blur or history.replaceState while this read is pending must not leave
+ // the same document permanently disabled.
+ const stamp = ++documentEpoch;
+ void guest
+ .executeJavaScript(
+ 'document.querySelector("meta[name=cindy-native-trackpad]")?.content === "touch"',
+ )
+ .then((value) => {
+ if (stamp === documentEpoch && !guest.isDestroyed()) {
+ enabled = value === true;
+ if (enabled) log.debug('Native contact document opted in', { guestId: guest.id });
+ }
+ })
+ .catch(() => {});
+ });
+ guest.on('before-mouse-event', async (_event, input) => {
+ if (!enabled || !current()) return;
+ if (input.type === 'mouseDown') {
+ void stop();
+ return;
+ }
+ if (gesture) return;
+ if (input.type === 'mouseLeave') {
+ stop();
+ return;
+ }
+ if (input.type !== 'mouseMove' && input.type !== 'mouseUp') return;
+ const win = deps.window(host);
+ if (!win) return;
+ const native = deps.load();
+ const p = native?.position ? native.position(win.getNativeWindowHandle()) : input;
+ if (!p) return;
+ const scale = guest.getZoomFactor();
+ let origin = { x: 0, y: 0 };
+ if (native?.position && host !== guest) {
+ // AppKit reports window-content points. A sidebar webview has its own
+ // viewport: subtract the exact embedding element before CDP hit testing.
+ // Read only the trusted host; the plugin receives no new IPC capability.
+ const read = ++pointerRead;
+ try {
+ const bounds = await host.executeJavaScript(`(() => {
+ const view = [...document.querySelectorAll('webview')].find(v => {
+ try { return v.getWebContentsId() === ${guest.id}; } catch { return false; }
+ });
+ if (!view) return null;
+ const r = view.getBoundingClientRect();
+ return {x:r.x, y:r.y, width:r.width, height:r.height};
+ })()`);
+ if (
+ read !== pointerRead ||
+ !current() ||
+ !bounds ||
+ ![bounds.x, bounds.y, bounds.width, bounds.height].every(Number.isFinite) ||
+ bounds.width <= 0 ||
+ bounds.height <= 0
+ )
+ return;
+ const hostScale = host.getZoomFactor();
+ origin = { x: bounds.x * hostScale, y: bounds.y * hostScale };
+ } catch {
+ return;
+ }
+ }
+ pointer = { x: (p.x - origin.x) / scale, y: (p.y - origin.y) / scale };
+ if (rect && !inside(rect, pointer)) stop();
+ if (input.type === 'mouseMove' || input.type === 'mouseUp') void locate();
+ });
+ guest.debugger.on('message', (_e, method, params) => {
+ if (!attached) return;
+ if (method === 'Target.attachedToTarget' && params.targetInfo?.type === 'iframe')
+ frames.set(params.targetInfo.targetId, params.sessionId);
+ if (method === 'Target.detachedFromTarget')
+ for (const [id, session] of frames)
+ if (session === params.sessionId) {
+ frames.delete(id);
+ stop();
+ }
+ });
+ guest.debugger.on('detach', () => {
+ attached = false;
+ frames.clear();
+ stop();
+ });
+ guest.on('blur', detach);
+ guest.on('zoom-changed', detach);
+ guest.on('did-start-navigation', (_e, _url, inPlace, main) => {
+ if (main) {
+ // A controller's history.replaceState does not get another dom-ready.
+ // Drop the old binding, but keep the same document's explicit opt-in.
+ if (inPlace) {
+ void stop();
+ return;
+ }
+ documentEpoch++;
+ enabled = false;
+ detach();
+ }
+ });
+ guest.on('render-process-gone', () => {
+ documentEpoch++;
+ enabled = false;
+ detach();
+ });
+ const win = deps.window(host);
+ win?.on('resize', detach);
+ win?.on('blur', detach);
+ win?.on('hide', detach);
+ guest.once('destroyed', () => {
+ detach();
+ host.removeListener('destroyed', detach);
+ win?.removeListener('resize', detach);
+ win?.removeListener('blur', detach);
+ win?.removeListener('hide', detach);
+ });
+ host.once('destroyed', detach);
+}
diff --git a/apps/desktop/src/main/webview-security.ts b/apps/desktop/src/main/webview-security.ts
index acbde7d234..5e4a50f6ab 100644
--- a/apps/desktop/src/main/webview-security.ts
+++ b/apps/desktop/src/main/webview-security.ts
@@ -23,6 +23,7 @@
*/
import path from 'node:path';
+import { installNativeTrackpad } from './nativeTrackpad';
import { app, session, type BrowserWindow, type Session, type WebContents } from 'electron';
import { CURRENT_APP_ID } from '../shared/brandRegion';
@@ -775,6 +776,7 @@ export function installBrowserGuestHandlers(
hostContents: WebContents,
guestContents: WebContents,
): void {
+ installNativeTrackpad(hostContents, guestContents);
guestContents.setWindowOpenHandler((details) => {
if (!isRoutablePopupUrl(details.url) && !isInitialBlankPopupUrl(details.url)) {
return { action: 'deny' };
@@ -1060,6 +1062,10 @@ export function installWebviewHardener(): void {
// 崩溃豁免登记(lifecycle 的全局 render-process-gone 守卫据此放行,
// 面板错误接管态负责用户侧收尾)。
registerGhostWebContents(guestContents.id);
+ installNativeTrackpad(contents, guestContents, () => {
+ if (!isGhostGuestOwnerActive(authorized.owner)) return false;
+ return authorized.isCurrent();
+ });
// 意识面板零弹窗、零跳转:window.open 全拒,导航锁死在自己协议同源内。
// 两个声明式例外(都是拦下导航、主机代办,面板侧依旧零桥):
// - /preview/ 预览链接 → 主窗口弹 lightbox(cindy-brain/previewGate.ts);
diff --git a/apps/desktop/src/shared/nativeTrackpad.ts b/apps/desktop/src/shared/nativeTrackpad.ts
new file mode 100644
index 0000000000..2ba509f7d1
--- /dev/null
+++ b/apps/desktop/src/shared/nativeTrackpad.ts
@@ -0,0 +1,41 @@
+export interface NativeTrackpadFrame {
+ phase: 'begin' | 'change' | 'end' | 'cancel';
+ width?: number;
+ height?: number;
+ touches: { id: number; x: number; y: number }[];
+}
+
+export function isNativeTrackpadFrame(value: unknown): value is NativeTrackpadFrame {
+ if (!value || typeof value !== 'object') return false;
+ const p = value as NativeTrackpadFrame;
+ if (
+ !['begin', 'change', 'end', 'cancel'].includes(p.phase) ||
+ !Array.isArray(p.touches) ||
+ p.touches.length > 2
+ )
+ return false;
+ if (p.phase === 'begin' && p.touches.length !== 2) return false;
+ if (['end', 'cancel'].includes(p.phase) && p.touches.length !== 0) return false;
+ if (
+ p.touches.length &&
+ (!Number.isFinite(p.width) || !Number.isFinite(p.height) || p.width! <= 0 || p.height! <= 0)
+ )
+ return false;
+ const ids = new Set<number>();
+ return p.touches.every((t) => {
+ if (
+ !t ||
+ ![0, 1].includes(t.id) ||
+ ids.has(t.id) ||
+ !Number.isFinite(t.x) ||
+ !Number.isFinite(t.y) ||
+ t.x < 0 ||
+ t.x > 1 ||
+ t.y < 0 ||
+ t.y > 1
+ )
+ return false;
+ ids.add(t.id);
+ return true;
+ });
+}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 66011fb65d..1a2018e017 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -3670,3 +3670,25 @@ worker 的任务,按最近更新取前 200 条;伙伴行 `revision` 追加
旧控制端按未知 rel 忽略,`conversation` 仍是第一条链接,打开聊天不变;新控制端连接旧 Host
时没有该链接,任务行不显示标记。Mobile 读取的链接上限由 64 放宽到 256 以容纳这组链接。
不增加 IPC channel、请求参数、数据库字段、push 类型或 Mobile 原生配置。
+
+## macOS 原生触控板输入
+
+本机聚焦的浏览器/插件页可在顶层 HTML 声明
+`<meta name="cindy-native-trackpad" content="touch">`,并用 `data-cindy-trackpad`
+标记接收触摸的平面元素。宿主将 AppKit 的两指位置映射为该元素的浏览器触摸事件;
+鼠标位置是落指中心,两轴按触控板物理比例等比映射,按原始抬指/取消结束。
+映射使用画面长边作为统一距离基准,避免竖屏窄边压缩平移;落指间距与后续位移
+使用同一比例,未裁切时保持缩放比例、旋转角度和静止手指的位置,不单独加速双指中心。
+触点在元素边缘停止,越界位移不累计;反向移动立即响应,不要求先退回越界距离。
+不新增 preload、renderer IPC 或远程请求;插件沙箱仍为零桥,归属与聚焦检查沿用宿主。
+后台窗口、第三指、页面导航、失焦会取消触摸;原生模块不可用或已有调试会话时保留原输入。
+旧宿主忽略 meta/属性,继续 wheel 兼容路径;手机、Windows、Linux 不接收本机 AppKit 数据。
+AppKit 鼠标位置固定使用窗口内容坐标;嵌入侧栏须先扣除宿主内对应 webview 的位置,
+并分别处理宿主与 guest 缩放,再在 guest 内命中检测。独立窗口没有这个偏移,
+不能单独替代开发版实际侧栏的输入验收。
+
+`data-cindy-trackpad="contacts"` 可选整帧输入:元素收到 `cindy-trackpad` DOM
+事件,`detail={phase,touches:[{id,x,y}]}`;坐标相对该元素所属 frame 的 viewport,
+phase 为 begin/change/end/cancel,touches 是仍按下的全部触点。整帧原子投递,避免
+Chromium 把双指拆成单指前奏及等待触摸 ACK。空属性仍投递标准 Touch/Pointer 事件;
+旧宿主按旧路径工作,插件仍保留标准触摸处理。只有宿主向页面投递数据,没有反向特权桥。
diff --git a/scripts/ensure-dev-runtime-assets.mjs b/scripts/ensure-dev-runtime-assets.mjs
index d56de390a7..a83683b58b 100644
--- a/scripts/ensure-dev-runtime-assets.mjs
+++ b/scripts/ensure-dev-runtime-assets.mjs
@@ -24,8 +24,12 @@ import {
updateScriptForKind,
} from './ensure-agent-binaries.mjs';
import { fixNodePtyExecutables } from './fix-node-pty-perms.mjs';
+import { buildTrackpad } from '../apps/desktop/native/trackpad/build.mjs';
const ROOT = path.resolve(fileURLToPath(new URL('..', import.meta.url)));
+if (process.platform === 'darwin') {
+ buildTrackpad(path.join(ROOT, 'apps/desktop/resources/tools/trackpad/cindy-trackpad.node'));
+}
const LFS_POINTER_HEADER = 'version https://git-lfs.github.com/spec/v1';
const MIN_EXPECTED_BYTES = 1024;