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。

fix(desktop): 修复原生触点目标失效和抬指清理

Dashf5b8ad1bedfe
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 7272d2edb8..351a835dc8 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
@@ -61,7 +61,7 @@
`data-cindy-trackpad`。支持此能力的 Mac 宿主只在页面聚焦、鼠标位于该元素时,将
AppKit 的两指位置投递为标准 Touch/Pointer 事件,嵌套 iframe 同样适用。
元素应设 `touch-action:none` 并处理结束、取消和失焦;不需要 preload、消息桥或新权限。
-落指中心取鼠标位置,触控板宽度对应元素宽度,两轴等比,超出元素边缘的触点裁剪。
+落指中心取鼠标位置,触控板宽度对应元素长边,两轴按触控板物理比例等比映射,超出元素边缘的触点裁剪。
边缘不累计越界位移,反向移动立即生效。
第三指交回系统;原生序列不重复投递 wheel/magnify。旧宿主、非 Mac、原生模块不可用
或页面正在被其他调试会话占用时不启用;保留原有 wheel 兼容逻辑,不能假定所有宿主都有。
diff --git a/apps/desktop/scripts/native-trackpad.verify.mjs b/apps/desktop/scripts/native-trackpad.verify.mjs
index 2898cd5880..813326fafa 100644
--- a/apps/desktop/scripts/native-trackpad.verify.mjs
+++ b/apps/desktop/scripts/native-trackpad.verify.mjs
@@ -1,7 +1,9 @@
/** 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. */
+ * not claim physical-trackpad verification. --headless also substitutes focus
+ * and pointer-entry signals, retaining real renderer/CDP delivery for locked
+ * desktops; it does not verify OS focus. No Cindy profile is opened. */
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -30,6 +32,7 @@ if (!process.versions.electron) {
});
const env = { ...process.env };
env.CINDY_TRACKPAD_VERIFY_CONTACTS = process.argv.includes('--contacts') ? '1' : '0';
+ env.CINDY_TRACKPAD_VERIFY_HEADLESS = process.argv.includes('--headless') ? '1' : '0';
env.CINDY_TRACKPAD_EXERCISE = process.argv.includes('--exercise') ? '1' : '0';
delete env.ELECTRON_RUN_AS_NODE;
execFileSync(
@@ -48,11 +51,13 @@ if (!process.versions.electron) {
void (async () => {
const { app, BrowserWindow } = require('electron');
const temp = process.argv[2];
+ const headless = process.env.CINDY_TRACKPAD_VERIFY_HEADLESS === '1';
app.setPath('userData', path.join(temp, 'profile'));
let win, server;
const deadline = setTimeout(() => app.exit(1), 25000);
try {
await app.whenReady();
+ if (headless) console.log('DOM_CDP_ONLY: synthetic focus, pointer entry and AppKit samples');
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');
@@ -145,10 +150,11 @@ if (!process.versions.electron) {
width: r.width,
height: r.height,
};
+ const childBounds = await frame.executeJavaScript(
+ `(()=>[...document.querySelectorAll('iframe')].map(e=>{const r=e.getBoundingClientRect();return {url:e.src,x:r.x,y:r.y};}))()`,
+ );
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};})()`,
- );
+ const bounds = childBounds.find((entry) => entry.url === child.url);
if (bounds) {
const found = await find(child, { x: offset.x + bounds.x, y: offset.y + bounds.y });
if (found) return found;
@@ -277,22 +283,51 @@ if (!process.versions.electron) {
);
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});
- });
+ window.events=[];let generation=0;
+ window.bindSurface=element=>{
+ element.dataset.generation=String(generation);
+ for(const type of ['touchstart','touchmove','touchend','touchcancel'])element.addEventListener(type,e=>{e.preventDefault();events.push({type,at:Date.now(),target:element.dataset.generation,connected:element.isConnected,touches:[...e.touches].map(t=>({id:t.identifier,x:t.clientX,y:t.clientY}))});},{passive:false});
+ let count=0;element.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(),target:element.dataset.generation,connected:element.isConnected,touches:f.touches});
+ });
+ };
+ bindSurface(document.querySelector('canvas'));
+ window.replaceSurface=cover=>{
+ const old=[...document.querySelectorAll('canvas')].at(-1),next=old.cloneNode();generation++;bindSurface(next);
+ if(cover)old.after(next);else old.replaceWith(next);
+ };
</script>`);
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
win = new BrowserWindow({
+ show: !headless,
width: 700,
height: 800,
webPreferences: { sandbox: true, contextIsolation: true },
});
const wc = win.webContents;
+ // Explicit DOM/CDP-only tier for a locked/unavailable desktop. The
+ // production focus guards remain unchanged; this mode substitutes their
+ // inputs, so it is not evidence of OS focus or physical AppKit capture.
+ const fixtureProxy = (target, overrides) =>
+ new Proxy(target, {
+ get(object, key) {
+ if (key in overrides) return overrides[key];
+ const value = Reflect.get(object, key);
+ return typeof value === 'function' ? value.bind(object) : value;
+ },
+ });
+ const inputContents = headless ? fixtureProxy(wc, { isFocused: () => true }) : wc;
+ const inputWindow = headless
+ ? fixtureProxy(win, { isFocused: () => true, isVisible: () => true })
+ : win;
+ const commands = [];
+ let pointerEvents = 0;
+ wc.on('before-mouse-event', () => pointerEvents++);
const command = wc.debugger.sendCommand.bind(wc.debugger);
wc.debugger.sendCommand = async (method, ...args) => {
+ commands.push(method);
try {
const result = await command(method, ...args);
if (method === 'Input.dispatchTouchEvent' || method === 'DOM.getBoxModel')
@@ -305,7 +340,7 @@ if (!process.versions.electron) {
};
let callback, armed;
const ready = new Promise((r) => (armed = r));
- installNativeTrackpad(wc, wc, () => true, {
+ installNativeTrackpad(inputContents, inputContents, () => true, {
platform: 'darwin',
load: () => ({
position: () => ({ x: 270, y: 330 }),
@@ -317,19 +352,39 @@ if (!process.versions.electron) {
},
stop: () => {},
}),
- window: () => win,
+ window: () => inputWindow,
});
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++) {
+ if (!headless) {
+ app.focus({ steal: true });
+ win.show();
win.focus();
wc.focus();
- wc.sendInputEvent({ type: 'mouseMove', x: 270, y: 330 });
+ }
+ for (let i = 0; i < 100 && !callback; i++) {
+ if (headless) wc.emit('before-mouse-event', {}, { type: 'mouseMove', x: 270, y: 330 });
+ else {
+ win.focus();
+ wc.focus();
+ wc.sendInputEvent({ type: 'mouseMove', x: 270, y: 330 });
+ }
await new Promise((r) => setTimeout(r, 10));
}
+ if (!callback)
+ console.log(
+ 'ARM_FAILURE',
+ JSON.stringify({
+ windowFocus: win.isFocused(),
+ guestFocus: wc.isFocused(),
+ visible: win.isVisible(),
+ pointerEvents,
+ commands,
+ optIn: await wc.executeJavaScript(
+ 'document.querySelector("meta[name=cindy-native-trackpad]")?.content',
+ ),
+ }),
+ );
assert(callback, 'Native surface not armed after focus/DOM readiness');
await ready;
const frame = wc.mainFrame.frames[0].frames[0];
@@ -402,15 +457,73 @@ if (!process.versions.electron) {
assert.equal(latency.length, 120);
}
emit('change', [points[0]]);
- await until((e) => e.some((v) => v.type === 'touchend' && v.touches.length === 1));
+ const lifted = await until((e) =>
+ e.some((v) => v.type === 'touchend' && v.touches.length === 1),
+ );
+ assert.equal(lifted.findLast((v) => v.type === 'touchend').touches[0].id, start[0].id);
emit('end', []);
await until((e) => e.some((v) => v.type === 'touchend' && v.touches.length === 0));
+ if (process.env.CINDY_TRACKPAD_VERIFY_CONTACTS === '1') {
+ // React can replace a surface without navigation or pointer movement.
+ // The old delivery must cancel, release its object and re-hit-test.
+ const previous = callback;
+ await frame.executeJavaScript('replaceSurface(false)');
+ emit('begin', points);
+ for (let i = 0; i < 100 && callback === previous; i++)
+ await new Promise((r) => setTimeout(r, 10));
+ assert.notEqual(callback, previous, 'Disconnected contacts surface did not rearm');
+ }
emit('begin', points);
await until(
(e) => e.filter((v) => v.type === 'touchstart' && v.touches.length === 2).length === 2,
);
+ if (process.env.CINDY_TRACKPAD_VERIFY_CONTACTS === '1') {
+ let previous = callback;
+ emit('end', []);
+ await until((e) => e.at(-1)?.type === 'touchend' && e.at(-1).touches.length === 0);
+ await frame.executeJavaScript('replaceSurface(true)');
+ emit('begin', points);
+ for (let i = 0; i < 100 && callback === previous; i++)
+ await new Promise((r) => setTimeout(r, 10));
+ assert.notEqual(callback, previous, 'Covered contacts surface did not rearm');
+ emit('begin', points);
+ await until((e) => e.at(-1)?.type === 'touchstart' && e.at(-1).target === '2');
+ previous = callback;
+ await frame.executeJavaScript('replaceSurface(false)');
+ emit('change', points);
+ for (let i = 0; i < 100 && callback === previous; i++)
+ await new Promise((r) => setTimeout(r, 10));
+ assert.notEqual(callback, previous, 'Mid-gesture replacement did not rearm');
+ emit('begin', points);
+ const rebound = await until(
+ (e) => e.at(-1)?.type === 'touchstart' && e.at(-1).target === '3',
+ );
+ assert(rebound.some((e) => e.type === 'touchcancel' && e.connected === false));
+ console.log(
+ 'PASS: disconnected, covered and mid-gesture replaced contacts rearm without pointer movement',
+ );
+ emit('end', []);
+ await until((e) => e.at(-1)?.type === 'touchend' && e.at(-1).touches.length === 0);
+ await frame.executeJavaScript(`(()=>{
+ const canvas=[...document.querySelectorAll('canvas')].at(-1),host=document.createElement('div');
+ host.style.display='contents';canvas.style.cssText='position:absolute;left:20px;top:10px;width:400px;height:500px;touch-action:none';
+ canvas.replaceWith(host);host.attachShadow({mode:'closed'}).append(canvas);
+ })()`);
+ previous = callback;
+ emit('begin', points);
+ await until((e) => e.at(-1)?.type === 'touchstart' && e.at(-1).target === '3');
+ assert.equal(callback, previous, 'A valid shadow-root surface must not be rejected');
+ console.log('PASS: begin hit testing preserves a valid closed-shadow-root surface');
+ }
win.emit('blur');
- await until((e) => e.some((v) => v.type === 'touchcancel'));
+ await until((e) => e.at(-1)?.type === 'touchcancel');
+ for (let i = 0; i < 100 && wc.debugger.isAttached(); i++)
+ await new Promise((r) => setTimeout(r, 10));
+ assert.equal(
+ wc.debugger.isAttached(),
+ false,
+ 'Cleanup must release its object before detaching',
+ );
console.log(
'PASS: native addon loads; nested iframe mapping, stationary finger, independent motion, liftoff and blur cancellation',
);
diff --git a/apps/desktop/src/main/__tests__/nativeTrackpad.test.ts b/apps/desktop/src/main/__tests__/nativeTrackpad.test.ts
index b937198351..706c61f2ec 100644
--- a/apps/desktop/src/main/__tests__/nativeTrackpad.test.ts
+++ b/apps/desktop/src/main/__tests__/nativeTrackpad.test.ts
@@ -33,6 +33,8 @@ function setup({ optIn = true, occupied = false, iframe = false, contacts = fals
});
if (method === 'DOM.getNodeForLocation') return { backendNodeId: 1 };
if (method === 'DOM.resolveNode') return { object: { objectId: 'node' } };
+ if (method === 'Runtime.callFunctionOn' && _args?.arguments)
+ return { result: { value: true } };
if (
method === 'Runtime.callFunctionOn' &&
String(_args?.functionDeclaration).includes('getAttribute')
@@ -218,10 +220,77 @@ test('maps independent contacts without scale hysteresis, including iframe offse
h.emit('end', []);
expect(h.inputs()[4]).toMatchObject({
type: 'touchEnd',
- touchPoints: [{ id: 0, x: 170, y: 330 }],
+ touchPoints: [],
});
});
+// Review regression: a cached contacts element can be replaced without mouse
+// movement or navigation. Its failed delivery must cancel and re-hit-test;
+// existing tests covered navigation, not same-document element replacement.
+test('invalid contacts targets cancel and rearm without requiring another pointer event', async () => {
+ for (const phase of ['begin', 'change']) {
+ const h = setup({ contacts: true });
+ await h.arm();
+ if (phase === 'change') {
+ h.emit('begin');
+ await settle();
+ }
+ const command = h.debug.sendCommand.getMockImplementation()!;
+ let invalid = true;
+ h.debug.sendCommand.mockImplementation(async (method, args, session) => {
+ if (method === 'Runtime.callFunctionOn' && args?.arguments && invalid) {
+ invalid = false;
+ return { result: { value: false } };
+ }
+ return command(method, args, session);
+ });
+ h.emit(phase);
+ await settle();
+ expect(h.native.stop).toHaveBeenCalledWith(1);
+ expect(h.native.start).toHaveBeenCalledTimes(2);
+ expect(h.debug.sendCommand.mock.calls).toContainEqual([
+ 'Runtime.callFunctionOn',
+ expect.objectContaining({
+ arguments: expect.arrayContaining([{ value: { phase: 'cancel', touches: [] } }]),
+ }),
+ undefined,
+ ]);
+ const count = h.debug.sendCommand.mock.calls.length;
+ h.emit('change', h.points, 0);
+ expect(h.debug.sendCommand).toHaveBeenCalledTimes(count);
+ h.emit('begin');
+ await settle();
+ expect(h.native.stop).not.toHaveBeenCalledWith(2);
+ }
+});
+
+test('a late invalid-target response cannot cancel a newer capture after blur', async () => {
+ const h = setup({ contacts: true });
+ await h.arm();
+ const command = h.debug.sendCommand.getMockImplementation()!;
+ let resolve!: (value: any) => void;
+ let pending = true;
+ h.debug.sendCommand.mockImplementation(async (method, args, session) => {
+ if (method === 'Runtime.callFunctionOn' && args?.arguments && pending) {
+ pending = false;
+ return new Promise((done) => {
+ resolve = done;
+ });
+ }
+ return command(method, args, session);
+ });
+ h.emit('begin');
+ h.window.emit('blur');
+ await settle();
+ await h.hover();
+ h.emit('begin');
+ await settle();
+ resolve({ result: { value: false } });
+ await settle();
+ expect(h.native.start).toHaveBeenCalledTimes(2);
+ expect(h.native.stop).not.toHaveBeenCalledWith(2);
+});
+
test('owner revocation cancels active contacts; late frames never cross a navigation', async () => {
const h = setup();
await h.arm();
@@ -277,6 +346,7 @@ test('atomic contacts preserve the pair and cancel before releasing their frame
],
},
},
+ { value: { x: 220, y: 260 } },
],
},
'child-session',
@@ -292,12 +362,22 @@ test('atomic contacts preserve the pair and cancel before releasing their frame
],
},
},
+ { value: { x: 220, y: 260 } },
],
});
expect(h.inputs()).toEqual([]);
+ const command = h.debug.sendCommand.getMockImplementation()!;
+ let release!: () => void;
+ h.debug.sendCommand.mockImplementation(async (method, args, session) => {
+ if (method === 'Runtime.releaseObject' && args?.objectId === 'surface')
+ return new Promise<void>((done) => {
+ release = done;
+ });
+ return command(method, args, session);
+ });
h.window.emit('blur');
expect(packets().at(-1)?.[1]).toMatchObject({
- arguments: [{ value: { phase: 'cancel', touches: [] } }],
+ arguments: [{ value: { phase: 'cancel', touches: [] } }, { value: { x: 220, y: 260 } }],
});
const n = packets().length;
h.emit('change');
@@ -308,6 +388,10 @@ test('atomic contacts preserve the pair and cancel before releasing their frame
{ objectId: 'surface' },
'child-session',
);
+ expect(h.debug.detach).not.toHaveBeenCalled();
+ release();
+ await settle();
+ expect(h.debug.detach).toHaveBeenCalledOnce();
});
test('reversing at a screen edge moves immediately without unwinding offscreen distance', async () => {
diff --git a/apps/desktop/src/main/nativeTrackpad.ts b/apps/desktop/src/main/nativeTrackpad.ts
index 19d66d6c0c..7a535bf363 100644
--- a/apps/desktop/src/main/nativeTrackpad.ts
+++ b/apps/desktop/src/main/nativeTrackpad.ts
@@ -25,9 +25,15 @@ interface Contact extends Point {
}
// 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 deliverContacts = `function(frame, anchor) {
+ if (frame.phase !== 'cancel') {
+ if (!this.isConnected || this.getAttribute('data-cindy-trackpad') !== 'contacts') return false;
+ if (frame.phase === 'begin' &&
+ this.getRootNode().elementFromPoint(anchor.x, anchor.y)?.closest('[data-cindy-trackpad]') !== this)
+ return false;
+ }
+ this.dispatchEvent(new CustomEvent('cindy-trackpad', {detail: frame}));
+ return true;
}`;
const requireNative = createRequire(__filename);
const log = createLogger('nativeTrackpad');
@@ -108,7 +114,7 @@ export function installNativeTrackpad(
const previous = surface;
surface = null;
if (previous && attached && !guest.isDestroyed())
- void cancelled
+ return cancelled
.then(() =>
guest.debugger.sendCommand(
'Runtime.releaseObject',
@@ -116,6 +122,7 @@ export function installNativeTrackpad(
previous.session,
),
)
+ .then(() => {})
.catch(() => {});
return cancelled;
};
@@ -127,6 +134,7 @@ export function installNativeTrackpad(
{
objectId: target.objectId,
functionDeclaration: deliverContacts,
+ returnByValue: true,
arguments: [
{
value: {
@@ -138,11 +146,21 @@ export function installNativeTrackpad(
})),
},
},
+ { value: { x: pointer.x - target.offset.x, y: pointer.y - target.offset.y } },
],
},
target.session,
)
- .then(() => {})
+ .then((reply) => {
+ if (reply.exceptionDetails) throw new Error('Native trackpad target execution failed');
+ if (reply.result?.value !== true && surface === target) {
+ // Same-document replacement, removed opt-in or an overlay can leave
+ // the cached object alive but unable to receive this sequence.
+ // Cancel even on a disconnected node, then reuse normal hit testing.
+ void stop();
+ void locate();
+ }
+ })
.catch(() => {
// Clear the gesture before teardown so a failed cancel cannot recurse.
if (surface === target) {
@@ -210,7 +228,9 @@ export function installNativeTrackpad(
};
});
g.raw = packet.touches;
- // CDP touchEnd names the released contacts, not the remaining ones.
+ // Current Chromium's WebTouch path names released IDs for partial lifts;
+ // an active-point touchMove does not release the missing finger there.
+ // A complete end uses the protocol's empty list (as does cancellation).
const released = g.points.filter((p) => !touchPoints.some((t) => t.id === p.id));
const type =
packet.phase === 'begin'
@@ -227,7 +247,7 @@ export function installNativeTrackpad(
void guest.debugger
.sendCommand('Input.dispatchTouchEvent', {
type,
- touchPoints: type === 'touchEnd' ? released : touchPoints,
+ touchPoints: type === 'touchEnd' && touchPoints.length ? released : touchPoints,
})
.catch(() => {
if (stamp === epoch) detach();
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 1a2018e017..5ecf8f93ca 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -3692,3 +3692,14 @@ AppKit 鼠标位置固定使用窗口内容坐标;嵌入侧栏须先扣除宿
phase 为 begin/change/end/cancel,touches 是仍按下的全部触点。整帧原子投递,避免
Chromium 把双指拆成单指前奏及等待触摸 ACK。空属性仍投递标准 Touch/Pointer 事件;
旧宿主按旧路径工作,插件仍保留标准触摸处理。只有宿主向页面投递数据,没有反向特权桥。
+
+contacts 在每次 begin 投递前核对原元素仍连接、仍声明 contacts,且仍是落指锚点
+命中的元素(在元素所属 Document/ShadowRoot 内检测)。目标被替换、移除或遮挡时,
+向旧元素发送 cancel(断开的旧元素也可接收清理),停止旧采集并重新命中;下一原生采样
+可在新目标开始,不依赖再次移动鼠标。旧目标迟到的失败回复不能撤销后来的目标。
+取消、释放 CDP object 完成后才 detach,沿用现有采集代次,无新队列或持久状态。
+
+标准 Touch 路径完整结束与取消使用空 `touchPoints`。当前打包 Chromium 默认 WebTouch
+路径的部分抬指使用 released IDs;仅发送剩余触点的 touchMove 不会释放缺失手指。
+这与 contacts DOM 事件始终表示「全部仍按下触点」的约定不同;以真实 Electron 的
+部分抬指、完整结束和取消回归核对,不能只靠 CDP mock 推断浏览器行为。