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(computer): 对齐驱动契约并验证操作结果 (#3951)

Dash1857e28e60ef
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 71d0fcb5d1..36b24b0b76 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -952,6 +952,7 @@ import { findCindyFileInArgv } from './cindy-brain/argv.js';
import { handleIncomingCindyFile } from './cindy-brain/openFileInstall.js';
import { registerCindyFileAssociation } from './cindy-brain/fileAssociation.js';
import { runPluginStorageSmoke } from './smoke/pluginStorageSmoke.js';
+import { runComputerUseSmokeIfRequested } from './smoke/computerUseSmoke.js';
import { setMainLocale, t } from './i18n.js';
import { requireObject, throwIpcError } from './utils/ipcValidate.js';
import { pickNativeAtResource } from './nativeAtResourcePicker.js';
@@ -3828,6 +3829,7 @@ const createWindow = () => {
restoreFullscreen: shouldRestoreMacFullscreen,
});
if (!app.isPackaged) markDesktopDevWindowReady();
+ void runComputerUseSmokeIfRequested();
// 资源用量窗口不应与主窗口首帧争 CPU。主窗口可见后再后台完成 BrowserWindow、
// renderer 和首份进程快照预热;回调绑定当代主窗口,重建/退出后不会创建孤儿窗。
resourceUsagePrewarmTimer = setTimeout(() => {
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/computer-contract.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/computer-contract.test.ts
new file mode 100644
index 0000000000..2c5aab28ad
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/computer-contract.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest';
+import fixture from './fixtures/cua-driver-0.23.2.json';
+import { adaptComputerDriverArgs, type ComputerDriverToolSchema } from '../computer-contract.js';
+
+const schemas = new Map(
+ fixture.tools.map((tool) => [tool.name, tool.inputSchema as ComputerDriverToolSchema]),
+);
+describe('installed Computer Use contract', () => {
+ it('preserves driver credentials and rejects missing observation provenance', () => {
+ const args = {
+ pid: 1,
+ window_id: 2,
+ element_index: 3,
+ snapshot_id: 's01234567',
+ element_token: 'opaque:untouched',
+ delivery_mode: 'background',
+ };
+ expect(adaptComputerDriverArgs('click', args, schemas)).toEqual(args);
+ expect(() => adaptComputerDriverArgs('click', { pid: 1, element_index: 3 }, schemas)).toThrow(
+ 'fresh driver snapshot_id',
+ );
+ });
+ it('uses the real screenshot switch and bounded traversal without mutating caller input', () => {
+ const args = { pid: 1, window_id: 2, capture_mode: 'ax' };
+ expect(adaptComputerDriverArgs('get_window_state', args, schemas)).toEqual({
+ pid: 1,
+ window_id: 2,
+ include_screenshot: false,
+ max_elements: 200,
+ max_depth: 15,
+ });
+ expect(args.capture_mode).toBe('ax');
+ expect(
+ adaptComputerDriverArgs(
+ 'get_window_state',
+ { ...args, include_screenshot: true, max_elements: 500 },
+ schemas,
+ ),
+ ).toMatchObject({ include_screenshot: true, max_elements: 500 });
+ });
+ it('preserves legacy SOM and maps an explicit new screenshot flag for old drivers', () => {
+ const legacy = new Map([['get_window_state', { properties: { capture_mode: {} } }]]);
+ expect(adaptComputerDriverArgs('get_window_state', { capture_mode: 'som' }, legacy)).toEqual({
+ capture_mode: 'som',
+ });
+ expect(
+ adaptComputerDriverArgs('get_window_state', { include_screenshot: false }, legacy),
+ ).toEqual({ capture_mode: 'ax' });
+ });
+ it('rejects unavailable tools and incompatible arguments before dispatch', () => {
+ expect(() => adaptComputerDriverArgs('missing', {}, schemas)).toThrow('does not advertise');
+ expect(() => adaptComputerDriverArgs('click', { pid: 1, unsupported: true }, schemas)).toThrow(
+ 'does not accept unsupported',
+ );
+ expect(() =>
+ adaptComputerDriverArgs('verify_state', { pid: 1, window_id: 2 }, schemas),
+ ).toThrow('requires expect');
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
index 3baaa458a4..9355f5a527 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
@@ -3,6 +3,7 @@ import path from 'node:path';
import { PassThrough } from 'node:stream';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { BRAND_NAME } from '@cindy/maker-shared/branding';
+import { COMPUTER_TOOLS } from '@cindy/mcps/computer';
const {
existsSyncMock,
@@ -11,6 +12,7 @@ const {
mcpCallToolMock,
mcpCloseMock,
mcpConnectMock,
+ mcpListToolsMock,
transportCloseMock,
transportCtorMock,
resolveDesktopOutboundProxyMock,
@@ -21,6 +23,7 @@ const {
mcpCallToolMock: vi.fn(),
mcpCloseMock: vi.fn(),
mcpConnectMock: vi.fn(),
+ mcpListToolsMock: vi.fn(),
transportCloseMock: vi.fn(),
transportCtorMock: vi.fn(),
resolveDesktopOutboundProxyMock: vi.fn(),
@@ -69,6 +72,7 @@ vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
callTool: mcpCallToolMock,
close: mcpCloseMock,
connect: mcpConnectMock,
+ listTools: mcpListToolsMock,
})),
}));
@@ -327,6 +331,9 @@ describe('computer mcp integration', () => {
mcpCallToolMock.mockReset();
mcpCloseMock.mockReset().mockResolvedValue(undefined);
mcpConnectMock.mockReset().mockResolvedValue(undefined);
+ mcpListToolsMock.mockReset().mockResolvedValue({ tools: [
+ ...COMPUTER_TOOLS.map((tool) => tool.name), 'set_agent_cursor_motion', 'set_agent_cursor_style', 'end_session',
+ ].map((name) => ({ name, inputSchema: { type: 'object', additionalProperties: true } })) });
transportCloseMock.mockReset().mockResolvedValue(undefined);
transportCtorMock.mockReset();
resolveDesktopOutboundProxyMock.mockReset().mockResolvedValue(null);
@@ -1142,7 +1149,7 @@ describe('computer mcp integration', () => {
.mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
.mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true,"clicked":true}' }] });
- await expect(callComputerDriverTool('click', {
+ await expect(callComputerDriverTool('get_window_state', {
pid: 123,
window_id: 7,
x: 10,
@@ -1152,16 +1159,16 @@ describe('computer mcp integration', () => {
expect(mcpCallToolMock.mock.calls.map((call) => call[0]?.name)).toEqual([
'set_agent_cursor_motion',
'set_agent_cursor_style',
- 'click',
+ 'get_window_state',
'end_session',
'set_agent_cursor_motion',
- 'click',
+ 'get_window_state',
]);
expect(mcpConnectMock).toHaveBeenCalledTimes(2);
expect(mcpCloseMock).toHaveBeenCalledTimes(1);
const clickSessions = mcpCallToolMock.mock.calls
.map((call) => call[0])
- .filter((call) => call?.name === 'click')
+ .filter((call) => call?.name === 'get_window_state')
.map((call) => (call?.arguments as { session: string }).session);
expectDriverSessionGenerations(clickSessions, 'session-style-stale-recovery', [0, 1]);
});
@@ -1297,80 +1304,115 @@ describe('computer mcp integration', () => {
expect(typeCalls.map((call) => (call?.arguments as { text: string }).text.length)).toEqual([400, 400]);
});
- it('retries only the remaining type_text chunks after a stale driver session', async () => {
- const longText = 'a'.repeat(850);
- mcpCallToolMock
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true,"inserted":400}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '"session ended; tool call ignored"' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true,"inserted":400}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true,"inserted":50}' }] });
-
+ it('does not replay remaining text after an interrupted action', async () => {
+ let typed = 0;
+ mcpCallToolMock.mockImplementation(({ name }) => {
+ if (name === 'type_text' && ++typed === 2) throw new Error('session ended; tool call ignored');
+ return { content: [{ type: 'text', text: '{"ok":true,"inserted":400}' }] };
+ });
await expect(callComputerDriverTool('type_text', {
- pid: 123,
- window_id: 7,
- text: longText,
- session: 'caller-supplied',
- }, { sessionId: 'session-type-retry' })).resolves.toEqual({
- ok: true,
- inserted: 850,
- chunks: 3,
- chars: 850,
- lastResult: { ok: true, inserted: 50 },
+ pid: 123, window_id: 7, text: 'a'.repeat(850),
+ }, { sessionId: 'text-interrupted' })).rejects.toMatchObject({
+ code: 'ACTION_OUTCOME_UNKNOWN', outcomeUnknown: true,
});
+ expect(typed).toBe(2);
+ expect(mcpConnectMock).toHaveBeenCalledTimes(1);
+ });
- expect(mcpConnectMock).toHaveBeenCalledTimes(2);
- expect(mcpCloseMock).toHaveBeenCalledTimes(1);
- const typeCalls = mcpCallToolMock.mock.calls
- .map((call) => call[0])
- .filter((call) => call?.name === 'type_text');
- expect(typeCalls.map((call) => (call?.arguments as { text: string }).text.length)).toEqual([400, 400, 400, 50]);
- expectDriverSessionGenerations(
- typeCalls.map((call) => (call?.arguments as { session: string }).session),
- 'session-type-retry',
- [0, 0, 1, 1],
- );
+ it('stops chunked text on unknown effect and preserves the driver evidence', async () => {
+ mcpCallToolMock.mockImplementation(({ name }) => ({ structuredContent: name === 'type_text'
+ ? { effect: 'unverifiable', route: 'synthesized', event_count: 400 } : { ok: true } }));
+ const result = await callComputerDriverTool('type_text', { pid: 123, window_id: 7, text: 'a'.repeat(850) }, { sessionId: 'text-unknown' });
+ expect(result).toMatchObject({ effect: 'unverifiable', event_count: 400, completed_chars: 0, remaining_chars: 450 });
+ expect(mcpCallToolMock.mock.calls.filter(([call]) => call.name === 'type_text')).toHaveLength(1);
});
- it('does not count failed retry type_text chunks as inserted', async () => {
- const longText = 'a'.repeat(850);
- mcpCallToolMock
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true,"inserted":400}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '"session ended; tool call ignored"' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":false,"error":"focused element rejected input"}' }] });
+ it('propagates cancellation and never dispatches the next text chunk', async () => {
+ const controller = new AbortController();
+ mcpCallToolMock.mockImplementation(({ name }, _schema, options) => {
+ if (name === 'type_text') {
+ expect(options.signal).toBe(controller.signal);
+ controller.abort();
+ }
+ return { structuredContent: { ok: true, effect: 'confirmed' } };
+ });
+ await expect(callComputerDriverTool('type_text', { pid: 123, window_id: 7, text: 'a'.repeat(850) }, {
+ sessionId: 'text-cancel', signal: controller.signal,
+ })).rejects.toMatchObject({ code: 'REQUEST_CANCELLED', outcomeUnknown: true });
+ expect(mcpCallToolMock.mock.calls.filter(([call]) => call.name === 'type_text')).toHaveLength(1);
+ });
+
+ it.each(['connect', 'tools/list'] as const)('cancels the caller during %s without interrupting shared startup', async (phase) => {
+ mcpCallToolMock.mockResolvedValue({ structuredContent: { width: 1920, height: 1080 } });
+ let finish!: () => void;
+ const pending = new Promise<void>((resolve) => { finish = resolve; });
+ if (phase === 'connect') mcpConnectMock.mockImplementationOnce(() => pending);
+ else mcpListToolsMock.mockImplementationOnce(async () => {
+ await pending;
+ return { tools: [{ name: 'get_screen_size', inputSchema: { type: 'object' } }] };
+ });
+ const controller = new AbortController();
+ const cancelled = callComputerDriverTool('click', { pid: 123, window_id: 7, x: 1, y: 1 }, {
+ sessionId: 'startup-cancel', signal: controller.signal,
+ });
+ const rejected = expect(cancelled).rejects.toMatchObject({ code: 'REQUEST_CANCELLED' });
+ await vi.waitFor(() => expect(phase === 'connect' ? mcpConnectMock : mcpListToolsMock).toHaveBeenCalledTimes(1));
+ const otherCaller = callComputerDriverTool('get_screen_size', {}, { sessionId: 'startup-cancel' });
+ controller.abort();
+ await rejected; // Must settle before startup finishes, rather than after its timeout.
+ expect(mcpCallToolMock).not.toHaveBeenCalled();
+ expect(mcpCloseMock).not.toHaveBeenCalled();
+ finish();
+ await otherCaller;
+ expect(mcpConnectMock).toHaveBeenCalledTimes(1);
+ expect(mcpCallToolMock.mock.calls.map(([call]) => call.name)).toEqual(['get_screen_size']);
+ });
- await expect(callComputerDriverTool('type_text', {
- pid: 123,
- window_id: 7,
- text: longText,
- session: 'caller-supplied',
- }, { sessionId: 'session-type-retry-failure' })).resolves.toEqual({
- ok: false,
- error: 'focused element rejected input',
- inserted: 400,
- chunks: 2,
- chars: 400,
- lastResult: { ok: false, error: 'focused element rejected input' },
+ it('cancels a fresh-session retry while its connection is still pending', async () => {
+ let finish!: () => void;
+ mcpConnectMock.mockResolvedValueOnce(undefined).mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));
+ mcpCallToolMock.mockImplementation(({ name }) => {
+ if (name === 'get_window_state') throw new Error('Not connected');
+ return { structuredContent: { ok: true } };
+ });
+ const controller = new AbortController();
+ const call = callComputerDriverTool('get_window_state', { pid: 123, window_id: 7 }, {
+ sessionId: 'retry-startup-cancel', signal: controller.signal,
+ });
+ const rejected = expect(call).rejects.toMatchObject({ code: 'REQUEST_CANCELLED' });
+ await vi.waitFor(() => expect(mcpConnectMock).toHaveBeenCalledTimes(2));
+ controller.abort();
+ await rejected;
+ finish();
+ await Promise.resolve();
+ expect(mcpCallToolMock.mock.calls.filter(([tool]) => tool.name === 'get_window_state')).toHaveLength(1);
+ });
+
+ it('stops optional cursor setup as soon as cancellation arrives', async () => {
+ const controller = new AbortController();
+ mcpCallToolMock.mockImplementation(({ name }) => {
+ if (name === 'set_agent_cursor_motion') controller.abort();
+ return { structuredContent: { ok: true } };
});
+ await expect(callComputerDriverTool('click', { pid: 123, window_id: 7, x: 10, y: 20 }, {
+ sessionId: 'setup-cancel', signal: controller.signal,
+ })).rejects.toMatchObject({ code: 'REQUEST_CANCELLED' });
+ expect(mcpCallToolMock.mock.calls.map(([call]) => call.name)).toEqual(['set_agent_cursor_motion', 'end_session']);
+ });
- const typeCalls = mcpCallToolMock.mock.calls
- .map((call) => call[0])
- .filter((call) => call?.name === 'type_text');
- expect(typeCalls.map((call) => (call?.arguments as { text: string }).text.length)).toEqual([400, 400, 400]);
- expectDriverSessionGenerations(
- typeCalls.map((call) => (call?.arguments as { session: string }).session),
- 'session-type-retry-failure',
- [0, 0, 1],
- );
+ it('negotiates paginated tools once per connection and fails unsupported actions locally', async () => {
+ mcpListToolsMock.mockReset();
+ mcpListToolsMock.mockResolvedValueOnce({ tools: [], nextCursor: 'next' }).mockResolvedValueOnce({ tools: [
+ { name: 'list_windows', inputSchema: { type: 'object', additionalProperties: true } },
+ ] });
+ mcpCallToolMock.mockResolvedValue({ structuredContent: { windows: [] } });
+ await callComputerDriverTool('list_windows', {}, { sessionId: 'pagination' });
+ await callComputerDriverTool('list_windows', {}, { sessionId: 'pagination' });
+ await expect(callComputerDriverTool('click', { pid: 123, window_id: 7, x: 1, y: 1 }, { sessionId: 'pagination' }))
+ .rejects.toMatchObject({ code: 'COMPUTER_DRIVER_INCOMPATIBLE' });
+ expect(mcpListToolsMock).toHaveBeenCalledTimes(2);
+ expect(mcpListToolsMock).toHaveBeenLastCalledWith({ cursor: 'next' });
+ expect(mcpCallToolMock.mock.calls.map(([call]) => call.name)).toEqual(['list_windows', 'list_windows']);
});
it('rotates the driver session and retries once when cua-driver reports session ended', async () => {
@@ -2182,51 +2224,16 @@ describe('computer mcp integration', () => {
}
});
- it('retries move_cursor once after a cua-driver MCP timeout and reapplies cursor style', async () => {
+ it('does not replay an overlay mutation after timeout', async () => {
vi.useFakeTimers();
try {
- const timedOutCall = createDeferred<unknown>();
- mcpCallToolMock
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockReturnValueOnce(timedOutCall.promise)
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true}' }] })
- .mockResolvedValueOnce({ content: [{ type: 'text', text: '{"ok":true,"moved":true}' }] });
-
- const call = callComputerDriverTool('move_cursor', { x: 10, y: 20 }, { sessionId: 'session-move-timeout' });
- const assertion = expect(call).resolves.toEqual({
- ok: true,
- moved: true,
- });
+ mcpCallToolMock.mockImplementation(({ name }) => name === 'move_cursor'
+ ? new Promise(() => {}) : { content: [{ type: 'text', text: '{"ok":true}' }] });
+ const call = callComputerDriverTool('move_cursor', { x: 10, y: 20 }, { sessionId: 'move-timeout' });
+ const assertion = expect(call).rejects.toMatchObject({ code: 'ACTION_OUTCOME_UNKNOWN' });
await vi.advanceTimersByTimeAsync(10_000);
await assertion;
-
- expect(mcpConnectMock).toHaveBeenCalledTimes(2);
- expect(mcpCloseMock).toHaveBeenCalledTimes(1);
- const motionCalls = mcpCallToolMock.mock.calls
- .map((mockCall) => mockCall[0])
- .filter((mockCall) => mockCall?.name === 'set_agent_cursor_motion');
- const styleCalls = mcpCallToolMock.mock.calls
- .map((mockCall) => mockCall[0])
- .filter((mockCall) => mockCall?.name === 'set_agent_cursor_style');
- const moveCalls = mcpCallToolMock.mock.calls
- .map((mockCall) => mockCall[0])
- .filter((mockCall) => mockCall?.name === 'move_cursor');
- expect(motionCalls).toHaveLength(2);
- expect(styleCalls).toHaveLength(2);
- expect(moveCalls).toHaveLength(2);
- expectDriverSessionGenerations(
- moveCalls.map((mockCall) => (mockCall?.arguments as { cursor_id: string }).cursor_id),
- 'session-move-timeout',
- [0, 1],
- );
- expectDriverSessionGenerations(
- motionCalls.map((mockCall) => (mockCall?.arguments as { cursor_id: string }).cursor_id),
- 'session-move-timeout',
- [0, 1],
- );
+ expect(mcpCallToolMock.mock.calls.filter(([call]) => call.name === 'move_cursor')).toHaveLength(1);
} finally {
vi.useRealTimers();
}
@@ -2410,7 +2417,7 @@ describe('computer mcp integration', () => {
oldEndSession.resolve({ content: [{ type: 'text', text: '{"ok":true}' }] });
await close;
- await expect(click).rejects.toThrow('session ended; tool call ignored');
+ await expect(click).rejects.toMatchObject({ code: 'ACTION_OUTCOME_UNKNOWN' });
expect(mcpConnectMock).toHaveBeenCalledTimes(1);
expect(mcpCloseMock).toHaveBeenCalledTimes(1);
const clickSessions = mcpCallToolMock.mock.calls
@@ -2435,7 +2442,7 @@ describe('computer mcp integration', () => {
mcpCallToolMock.mockImplementation((call: { name: string; arguments: Record<string, unknown> }) => {
const session = String(call.arguments.session ?? call.arguments.cursor_id);
const generation = driverSessionGeneration(session, 'session-close-before-retry');
- if (call.name === 'click' && generation === 0) {
+ if (call.name === 'get_window_state' && generation === 0) {
return staleClick.promise;
}
if (call.name === 'end_session') {
@@ -2452,12 +2459,12 @@ describe('computer mcp integration', () => {
});
const click = callComputerDriverTool(
- 'click',
+ 'get_window_state',
{ pid: 123, window_id: 7, x: 10, y: 20, session: 'caller-supplied' },
{ sessionId: 'session-close-before-retry' },
);
- await waitForCondition(() => mcpCallToolMock.mock.calls.some((call) => call[0]?.name === 'click'));
+ await waitForCondition(() => mcpCallToolMock.mock.calls.some((call) => call[0]?.name === 'get_window_state'));
staleClick.resolve({ content: [{ type: 'text', text: '"session ended; tool call ignored"' }] });
await waitForCondition(() => mcpCallToolMock.mock.calls.some((call) => call[0]?.name === 'end_session'));
oldEndSession.resolve({ content: [{ type: 'text', text: '{"ok":true}' }] });
@@ -2467,12 +2474,12 @@ describe('computer mcp integration', () => {
freshStyle.resolve({ content: [{ type: 'text', text: '{"ok":true}' }] });
await close;
- await expect(click).rejects.toThrow('session ended; tool call ignored');
+ await expect(click).rejects.toMatchObject({ code: 'REQUEST_CANCELLED' });
expect(mcpConnectMock).toHaveBeenCalledTimes(2);
expect(mcpCloseMock).toHaveBeenCalledTimes(2);
const clickSessions = mcpCallToolMock.mock.calls
.map((call) => call[0])
- .filter((call) => call?.name === 'click')
+ .filter((call) => call?.name === 'get_window_state')
.map((call) => (call?.arguments as { session: string }).session);
expectDriverSessionGenerations(clickSessions, 'session-close-before-retry', [0]);
});
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/fixtures/cua-driver-0.23.2.json b/apps/desktop/src/main/mcp-integrations/__tests__/fixtures/cua-driver-0.23.2.json
new file mode 100644
index 0000000000..c8fdaeba9d
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/fixtures/cua-driver-0.23.2.json
@@ -0,0 +1,366 @@
+{
+ "source": "cua-driver 0.23.2 describe (2026-09-05); descriptions and defaults omitted",
+ "tools": [
+ {
+ "name": "click",
+ "inputSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "action": {
+ "type": "string"
+ },
+ "button": {
+ "enum": ["left", "right", "middle"],
+ "type": "string"
+ },
+ "count": {
+ "type": "integer"
+ },
+ "debug_image_out": {
+ "type": "string"
+ },
+ "delivery_mode": {
+ "enum": ["background", "foreground"],
+ "type": "string"
+ },
+ "element_index": {
+ "type": "integer"
+ },
+ "element_token": {
+ "type": "string"
+ },
+ "from_zoom": {
+ "type": "boolean"
+ },
+ "modifier": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "pid": {
+ "type": "integer"
+ },
+ "scope": {
+ "enum": ["window", "desktop"],
+ "type": "string"
+ },
+ "session": {
+ "type": "string"
+ },
+ "snapshot_id": {
+ "pattern": "^s[0-9a-f]{8}$",
+ "type": "string"
+ },
+ "target": {
+ "anyOf": [
+ {
+ "oneOf": [
+ {
+ "additionalProperties": true,
+ "properties": {
+ "kind": {
+ "const": "window",
+ "type": "string"
+ },
+ "pid": {
+ "format": "uint32",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "window_id": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": ["kind", "pid", "window_id"],
+ "type": "object"
+ },
+ {
+ "additionalProperties": true,
+ "properties": {
+ "display_id": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "desktop",
+ "type": "string"
+ }
+ },
+ "required": ["kind", "display_id"],
+ "type": "object"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "window_id": {
+ "type": "integer"
+ },
+ "x": {
+ "type": "number"
+ },
+ "y": {
+ "type": "number"
+ }
+ },
+ "required": [],
+ "type": "object"
+ }
+ },
+ {
+ "name": "get_window_state",
+ "inputSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "capture_mode": {
+ "enum": ["ax", "vision"],
+ "type": "string"
+ },
+ "include_screenshot": {
+ "type": "boolean"
+ },
+ "max_depth": {
+ "minimum": 1,
+ "type": "integer"
+ },
+ "max_elements": {
+ "minimum": 1,
+ "type": "integer"
+ },
+ "pid": {
+ "type": "integer"
+ },
+ "query": {
+ "type": "string"
+ },
+ "screenshot_out_file": {
+ "type": "string"
+ },
+ "session": {
+ "type": "string"
+ },
+ "window_id": {
+ "type": "integer"
+ }
+ },
+ "required": ["pid", "window_id"],
+ "type": "object"
+ }
+ },
+ {
+ "name": "type_text",
+ "inputSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "delay_ms": {
+ "maximum": 200,
+ "minimum": 0,
+ "type": "integer"
+ },
+ "delivery_mode": {
+ "enum": ["background", "foreground"],
+ "type": "string"
+ },
+ "element_index": {
+ "type": "integer"
+ },
+ "element_token": {
+ "type": "string"
+ },
+ "pid": {
+ "type": "integer"
+ },
+ "scope": {
+ "enum": ["window", "desktop"],
+ "type": "string"
+ },
+ "session": {
+ "type": "string"
+ },
+ "snapshot_id": {
+ "pattern": "^s[0-9a-f]{8}$",
+ "type": "string"
+ },
+ "target": {
+ "anyOf": [
+ {
+ "oneOf": [
+ {
+ "additionalProperties": true,
+ "properties": {
+ "kind": {
+ "const": "window",
+ "type": "string"
+ },
+ "pid": {
+ "format": "uint32",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "window_id": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": ["kind", "pid", "window_id"],
+ "type": "object"
+ },
+ {
+ "additionalProperties": true,
+ "properties": {
+ "display_id": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "desktop",
+ "type": "string"
+ }
+ },
+ "required": ["kind", "display_id"],
+ "type": "object"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "text": {
+ "type": "string"
+ },
+ "window_id": {
+ "type": "integer"
+ },
+ "x": {
+ "type": "number"
+ },
+ "y": {
+ "type": "number"
+ }
+ },
+ "required": ["text"],
+ "type": "object"
+ }
+ },
+ {
+ "name": "verify_state",
+ "inputSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "expect": {
+ "items": {
+ "additionalProperties": false,
+ "properties": {
+ "element": {
+ "additionalProperties": false,
+ "properties": {
+ "enabled": {
+ "type": ["boolean", "null"]
+ },
+ "exists": {
+ "enum": [true],
+ "type": "boolean"
+ },
+ "selected": {
+ "type": ["boolean", "null"]
+ },
+ "selector": {
+ "additionalProperties": false,
+ "properties": {
+ "label_contains": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "role": {
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": [],
+ "type": "object"
+ },
+ "value_equals": {
+ "type": ["string", "null"]
+ }
+ },
+ "required": ["selector"],
+ "type": ["object", "null"]
+ },
+ "window": {
+ "additionalProperties": false,
+ "properties": {
+ "bounds": {
+ "additionalProperties": false,
+ "properties": {
+ "height": {
+ "type": "number"
+ },
+ "tolerance_px": {
+ "maximum": 100,
+ "minimum": 0,
+ "type": "number"
+ },
+ "width": {
+ "type": "number"
+ },
+ "x": {
+ "type": "number"
+ },
+ "y": {
+ "type": "number"
+ }
+ },
+ "required": ["x", "y", "width", "height"],
+ "type": ["object", "null"]
+ },
+ "exists": {
+ "type": ["boolean", "null"]
+ }
+ },
+ "type": ["object", "null"]
+ }
+ },
+ "required": [],
+ "type": "object"
+ },
+ "maxItems": 8,
+ "minItems": 1,
+ "type": "array"
+ },
+ "include_screenshot": {
+ "type": ["boolean", "null"]
+ },
+ "pid": {
+ "minimum": 1,
+ "type": "integer"
+ },
+ "session": {
+ "type": "string"
+ },
+ "stable_samples": {
+ "maximum": 5,
+ "minimum": 1,
+ "type": "integer"
+ },
+ "timeout_ms": {
+ "maximum": 10000,
+ "minimum": 0,
+ "type": "integer"
+ },
+ "window_id": {
+ "type": "integer"
+ }
+ },
+ "required": ["pid", "window_id", "expect"],
+ "type": "object"
+ }
+ }
+ ]
+}
diff --git a/apps/desktop/src/main/mcp-integrations/computer-contract.ts b/apps/desktop/src/main/mcp-integrations/computer-contract.ts
new file mode 100644
index 0000000000..16f4306eed
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/computer-contract.ts
@@ -0,0 +1,70 @@
+/** A session's actual tools/list contract, independent of release version strings. */
+export interface ComputerDriverToolSchema {
+ properties?: Record<string, unknown>;
+ required?: string[];
+ additionalProperties?: boolean;
+}
+
+export class ComputerContractError extends Error {
+ readonly code = 'COMPUTER_DRIVER_INCOMPATIBLE';
+}
+
+export function adaptComputerDriverArgs(
+ name: string,
+ input: Record<string, unknown>,
+ schemas: ReadonlyMap<string, ComputerDriverToolSchema>,
+): Record<string, unknown> {
+ const schema = schemas.get(name);
+ if (!schema)
+ throw new ComputerContractError(
+ `Installed driver does not advertise ${name}. Check the driver installation/version.`,
+ );
+ const props = schema.properties ?? {};
+ const args = { ...input };
+ if (name === 'get_window_state') {
+ const screenshot =
+ typeof args.include_screenshot === 'boolean'
+ ? args.include_screenshot
+ : args.capture_mode !== 'ax';
+ if ('include_screenshot' in props) {
+ args.include_screenshot = screenshot;
+ delete args.capture_mode; // New drivers ignore this legacy option.
+ } else {
+ delete args.include_screenshot;
+ args.capture_mode =
+ typeof input.include_screenshot === 'boolean'
+ ? screenshot
+ ? 'vision'
+ : 'ax'
+ : (input.capture_mode ?? 'vision');
+ }
+ // Bound the actual AX walk, not a lossy re-indexing of its response.
+ if ('max_elements' in props) args.max_elements ??= 200;
+ if ('max_depth' in props) args.max_depth ??= 15;
+ }
+ for (const key of Object.keys(args)) {
+ if (args[key] === undefined) delete args[key];
+ else if (schema.additionalProperties === false && !(key in props)) {
+ throw new ComputerContractError(
+ `Installed driver ${name} does not accept ${key}; no action was dispatched.`,
+ );
+ }
+ }
+ for (const key of schema.required ?? []) {
+ if (!(key in args))
+ throw new ComputerContractError(
+ `Installed driver ${name} requires ${key}; no action was dispatched.`,
+ );
+ }
+ if (
+ 'snapshot_id' in props &&
+ args.element_index !== undefined &&
+ !args.snapshot_id &&
+ !args.element_token
+ ) {
+ throw new ComputerContractError(
+ 'Element actions require a fresh driver snapshot_id or element_token. Call get_window_state first.',
+ );
+ }
+ return args;
+}
diff --git a/apps/desktop/src/main/mcp-integrations/computer.ts b/apps/desktop/src/main/mcp-integrations/computer.ts
index 40c58937ca..86f22e332c 100644
--- a/apps/desktop/src/main/mcp-integrations/computer.ts
+++ b/apps/desktop/src/main/mcp-integrations/computer.ts
@@ -21,6 +21,8 @@ import type {
import { createLogger } from '../logger.js';
import { outboundFetch } from '../maker-host/outbound-fetch.js';
import { resolveDesktopOutboundProxy } from '../maker-host/outbound-proxy-resolver.js';
+import { adaptComputerDriverArgs, type ComputerDriverToolSchema } from './computer-contract.js';
+import { computerResultOutcome, getComputerTool } from '@cindy/mcps/computer';
const logger = createLogger('mcp/cindy_computer');
const DRIVER_COMMAND = 'cua-driver';
@@ -83,6 +85,7 @@ const SCREENSHOT_OUTPUT_TOOL_NAMES = new Set<ComputerMcpToolName>(['get_window_s
const DRIVER_SESSION_ARG_TOOL_NAMES = new Set<ComputerMcpToolName>([
'list_windows',
'get_window_state',
+ 'verify_state',
'click',
'double_click',
'right_click',
@@ -283,6 +286,7 @@ interface CuaMcpSessionEntry {
transport: StdioClientTransport;
ready: Promise<void>;
driverSessionId: string;
+ toolSchemas: Map<string, ComputerDriverToolSchema>;
cursorSetup: {
motion: CursorSetupState;
style: CursorSetupState;
@@ -394,24 +398,12 @@ interface ComputerDriverStatusOptions {
}
class ComputerDriverError extends Error {
- constructor(message: string) {
+ constructor(message: string, readonly code = 'COMPUTER_DRIVER_ERROR', readonly outcomeUnknown = false) {
super(message);
this.name = 'ComputerDriverError';
}
}
-class ComputerDriverTypeTextRetryError extends ComputerDriverError {
- constructor(
- message: string,
- readonly remainingText: string,
- readonly completedChars: number,
- readonly completedChunks: number,
- ) {
- super(message);
- this.name = 'ComputerDriverTypeTextRetryError';
- }
-}
-
let permissionGrantInFlight: Promise<ExecResult> | null = null;
let permissionGrantStartedAt = 0;
let permissionGrantChild: ChildProcess | null = null;
@@ -1889,7 +1881,7 @@ function normalizeToolArgsForDriver(
if (!SCREENSHOT_OUTPUT_TOOL_NAMES.has(name) || typeof args.screenshot_out_file === 'string') {
return args;
}
- if (args.capture_mode === 'ax') {
+ if (args.include_screenshot === false || (args.include_screenshot === undefined && args.capture_mode === 'ax')) {
return args;
}
return {
@@ -1961,25 +1953,19 @@ function applyDriverSessionArgs(
name: ComputerMcpToolName,
args: Record<string, unknown>,
driverSessionId: string,
+ schemas: ReadonlyMap<string, ComputerDriverToolSchema>,
): Record<string, unknown> {
if (!DRIVER_SESSION_ARG_TOOL_NAMES.has(name)) return args;
- if (name === 'get_agent_cursor_state') {
- return {
- ...args,
- cursor_id: driverSessionId,
- };
+ const result = { ...args };
+ const keys = name === 'get_agent_cursor_state' ? ['cursor_id']
+ : name === 'move_cursor' ? ['cursor_id', 'session'] : ['session'];
+ const schema = schemas.get(name);
+ for (const key of keys) {
+ // Host-owned routing metadata is injected only when the installed tool accepts it.
+ if (schema?.additionalProperties === false && !(key in (schema.properties ?? {}))) delete result[key];
+ else result[key] = driverSessionId;
}
- if (name === 'move_cursor') {
- return {
- ...args,
- cursor_id: driverSessionId,
- session: driverSessionId,
- };
- }
- return {
- ...args,
- session: driverSessionId,
- };
+ return result;
}
function splitTypeTextChunks(text: string): string[] {
@@ -2011,10 +1997,10 @@ function shouldCleanupCuaMcpSessionAfterError(err: unknown): boolean {
function shouldRetryWithFreshCuaSession(name: ComputerMcpToolName, err: unknown): boolean {
const message = err instanceof Error ? err.message : String(err);
- return (
+ return (getComputerTool(name)?.readOnly === true && (
STALE_CUA_SESSION_MARKER_RE.test(message) ||
(/timed out after/i.test(message) && LIGHTWEIGHT_TIMEOUT_RETRY_TOOL_NAMES.has(name))
- );
+ ));
}
function getCuaMcpToolTimeoutMs(name: ComputerMcpToolName): number {
@@ -2130,16 +2116,27 @@ function createCuaMcpSession(sessionId: string): CuaMcpSessionEntry {
client,
transport,
driverSessionId: getDriverSessionId(sessionId),
+ toolSchemas: new Map(),
cursorSetup: {
motion: capabilities?.motion === 'unavailable' ? 'unavailable' : 'pending',
style: capabilities?.style === 'unavailable' ? 'unavailable' : 'pending',
},
ready: withTimeout(
- client.connect(transport),
+ client.connect(transport).then(async () => {
+ let cursor: string | undefined;
+ const seen = new Set<string>();
+ do {
+ const page = await client.listTools(cursor ? { cursor } : undefined);
+ for (const tool of page.tools) entry.toolSchemas.set(tool.name, tool.inputSchema as ComputerDriverToolSchema);
+ cursor = page.nextCursor;
+ if (cursor && (seen.has(cursor) || seen.size >= 20)) throw new ComputerDriverError('Driver tools/list pagination did not terminate.');
+ if (cursor) seen.add(cursor);
+ } while (cursor);
+ }),
MCP_STARTUP_TIMEOUT_MS,
`cua-driver mcp session ${sessionId} startup`,
).catch(async (err) => {
- cuaMcpSessions.delete(sessionId);
+ if (cuaMcpSessions.get(sessionId) === entry) cuaMcpSessions.delete(sessionId);
try {
await client.close();
} catch {
@@ -2156,24 +2153,43 @@ function createCuaMcpSession(sessionId: string): CuaMcpSessionEntry {
return entry;
}
-async function getCuaMcpSession(sessionId: string): Promise<CuaMcpSessionEntry> {
+/** Cancel this caller's wait without cancelling shared startup or another caller. */
+async function waitForCuaSession<T>(pending: Promise<T>, signal?: AbortSignal): Promise<T> {
+ if (!signal) return pending;
+ signal.throwIfAborted();
+ return new Promise<T>((resolve, reject) => {
+ const onAbort = () => {
+ signal.removeEventListener('abort', onAbort);
+ reject(new ComputerDriverError('Computer Use cancelled while waiting for the driver.', 'REQUEST_CANCELLED'));
+ };
+ signal.addEventListener('abort', onAbort, { once: true });
+ void pending.then(
+ (value) => { signal.removeEventListener('abort', onAbort); resolve(value); },
+ (error) => { signal.removeEventListener('abort', onAbort); reject(error); },
+ );
+ });
+}
+
+async function getCuaMcpSession(sessionId: string, signal?: AbortSignal): Promise<CuaMcpSessionEntry> {
+ signal?.throwIfAborted();
assertComputerDriverToolDispatchAvailable();
const existing = cuaMcpSessions.get(sessionId);
if (existing) {
- await existing.ready;
+ await waitForCuaSession(existing.ready, signal);
return existing;
}
const cleanup = cuaMcpSessionCleanups.get(sessionId);
if (cleanup) {
- await cleanup.catch(() => undefined);
+ await waitForCuaSession(cleanup.catch(() => undefined), signal);
+ signal?.throwIfAborted();
const next = cuaMcpSessions.get(sessionId);
if (next) {
- await next.ready;
+ await waitForCuaSession(next.ready, signal);
return next;
}
}
const entry = createCuaMcpSession(sessionId);
- await entry.ready;
+ await waitForCuaSession(entry.ready, signal);
return entry;
}
@@ -2182,18 +2198,23 @@ async function callCuaMcpTool(
name: string,
args: Record<string, unknown>,
timeoutMs: number,
+ signal?: AbortSignal,
): Promise<unknown> {
+ signal?.throwIfAborted();
+ const driverArgs = adaptComputerDriverArgs(name, args, entry.toolSchemas);
const result = await withTimeout(
entry.client.callTool({
name,
- arguments: args,
- }),
+ arguments: driverArgs,
+ }, undefined, { signal }),
timeoutMs,
`cua-driver mcp tool ${name}`,
);
if ((result as { isError?: unknown }).isError) {
const text = firstTextFromMcpResult(result);
- throw new ComputerDriverError(text ?? `cua-driver mcp tool ${name} returned an error`);
+ const details = objectValue(parseMcpToolResult(result));
+ throw new ComputerDriverError(text ?? `cua-driver mcp tool ${name} returned an error`,
+ typeof details?.code === 'string' ? details.code : 'COMPUTER_DRIVER_ERROR');
}
const parsed = parseMcpToolResult(result);
if (typeof parsed === 'string' && STALE_CUA_SESSION_MARKER_RE.test(parsed)) {
@@ -2207,14 +2228,18 @@ async function callCuaMcpToolWithTypeTextChunks(
name: ComputerMcpToolName,
args: Record<string, unknown>,
timeoutMs: number,
+ signal?: AbortSignal,
+ assertActive: () => void = () => {},
): Promise<unknown> {
+ signal?.throwIfAborted();
+ assertActive();
if (name !== 'type_text' || typeof args.text !== 'string') {
- return callCuaMcpTool(entry, name, args, timeoutMs);
+ return callCuaMcpTool(entry, name, args, timeoutMs, signal);
}
const chunks = splitTypeTextChunks(args.text);
if (chunks.length === 1) {
- return callCuaMcpTool(entry, name, args, timeoutMs);
+ return callCuaMcpTool(entry, name, args, timeoutMs, signal);
}
let lastResult: unknown = null;
@@ -2222,31 +2247,18 @@ async function callCuaMcpToolWithTypeTextChunks(
let processedChunks = 0;
for (let index = 0; index < chunks.length; index += 1) {
const chunk = chunks[index];
- try {
- lastResult = await callCuaMcpTool(
- entry,
- name,
- {
- ...args,
- text: chunk,
- },
- timeoutMs,
- );
- } catch (err) {
- if (shouldRetryWithFreshCuaSession(name, err)) {
- throw new ComputerDriverTypeTextRetryError(
- err instanceof Error ? err.message : String(err),
- chunks.slice(index).join(''),
- inserted,
- index,
- );
- }
- throw err;
- }
+ signal?.throwIfAborted();
+ assertActive();
+ lastResult = await callCuaMcpTool(entry, name, { ...args, text: chunk }, timeoutMs, signal);
const resultObject = objectValue(lastResult);
processedChunks += 1;
- if (resultObject?.ok === false) {
- if (typeof resultObject.inserted === 'number') {
+ const outcome = computerResultOutcome(name, lastResult);
+ if (resultObject?.effect !== undefined && outcome.outcome?.status !== 'confirmed') {
+ return { ...resultObject, chunks: processedChunks, completed_chars: inserted,
+ attempted_chars: Array.from(chunk).length, remaining_chars: Array.from(chunks.slice(index + 1).join('')).length };
+ }
+ if (!outcome.ok) {
+ if (typeof resultObject?.inserted === 'number') {
inserted += resultObject.inserted;
}
return {
@@ -2280,6 +2292,8 @@ async function initializeDefaultCursorStyle(
entry: CuaMcpSessionEntry,
session: string,
sessionCloseVersion: number,
+ signal?: AbortSignal,
+ assertActive: () => void = () => {},
): Promise<void> {
if (!CURSOR_STYLED_TOOL_NAMES.has(name)) return;
@@ -2308,6 +2322,8 @@ async function initializeDefaultCursorStyle(
];
for (const call of calls) {
+ assertActive();
+ signal?.throwIfAborted();
if (entry.cursorSetup[call.stateKey] !== 'pending') continue;
try {
await callCuaMcpTool(
@@ -2315,11 +2331,15 @@ async function initializeDefaultCursorStyle(
call.tool,
call.args,
STATUS_TIMEOUT_MS,
+ signal,
);
entry.cursorSetup[call.stateKey] = 'applied';
} catch (err) {
+ assertActive();
+ signal?.throwIfAborted();
const message = err instanceof Error ? err.message : String(err);
- if (isCursorSetupUnavailableError(message)) {
+ if (isCursorSetupUnavailableError(message)
+ || (err as { code?: string })?.code === 'COMPUTER_DRIVER_INCOMPATIBLE') {
entry.cursorSetup[call.stateKey] = 'unavailable';
if (getCuaMcpSessionCloseVersion(entry.logicalSessionId) === sessionCloseVersion) {
const capabilities = cuaMcpSessionCursorCapabilities.get(entry.logicalSessionId) ?? {
@@ -3337,22 +3357,30 @@ export async function callComputerDriverTool(
args: Record<string, unknown>,
context?: ComputerMcpCallContext,
): Promise<unknown> {
+ const signal = context?.signal;
+ signal?.throwIfAborted();
assertComputerDriverToolDispatchAvailable();
const sessionId = readSessionIdFromContext(context);
if (!sessionId) {
throw new ComputerDriverError(`Computer Use tool calls require an active ${BRAND_NAME} session.`);
}
const sessionCloseVersion = getCuaMcpSessionCloseVersion(sessionId);
+ const assertActive = () => {
+ signal?.throwIfAborted();
+ assertComputerDriverToolDispatchAvailable();
+ if (getCuaMcpSessionCloseVersion(sessionId) !== sessionCloseVersion) {
+ throw new ComputerDriverError('Computer Use session closed; no further action was dispatched.', 'REQUEST_CANCELLED');
+ }
+ };
const rawArgs = args ?? {};
const driverInputArgs = stripLocalListWindowsArgs(name, rawArgs);
const normalizedArgs = normalizeToolArgsForDriver(name, driverInputArgs);
- const entry = await getCuaMcpSession(sessionId);
- assertComputerDriverToolDispatchAvailable();
- const driverArgs = applyDriverSessionArgs(name, normalizedArgs, entry.driverSessionId);
- await initializeDefaultCursorStyle(name, driverArgs, entry, entry.driverSessionId, sessionCloseVersion);
+ const entry = await getCuaMcpSession(sessionId, signal);
+ const driverArgs = applyDriverSessionArgs(name, normalizedArgs, entry.driverSessionId, entry.toolSchemas);
const timeoutMs = getCuaMcpToolTimeoutMs(name);
try {
- const result = await callCuaMcpToolWithTypeTextChunks(entry, name, driverArgs, timeoutMs);
+ await initializeDefaultCursorStyle(name, driverArgs, entry, entry.driverSessionId, sessionCloseVersion, signal, assertActive);
+ const result = await callCuaMcpToolWithTypeTextChunks(entry, name, driverArgs, timeoutMs, signal, assertActive);
return name === 'list_windows' ? enrichAndFilterListWindowsResult(result, rawArgs) : result;
} catch (err) {
logger.warn('cua-driver MCP tool call failed', {
@@ -3361,8 +3389,16 @@ export async function callComputerDriverTool(
driverSessionId: entry.driverSessionId,
error: err instanceof Error ? err.message : String(err),
});
+ if (signal?.aborted) {
+ await cleanupCuaMcpSessionAfterError(sessionId, entry).catch(() => undefined);
+ throw new ComputerDriverError('Computer Use cancelled. An action already dispatched may have taken effect; observe before acting again.', 'REQUEST_CANCELLED', getComputerTool(name)?.readOnly !== true);
+ }
if (shouldCleanupCuaMcpSessionAfterError(err)) {
const cleanup = cleanupCuaMcpSessionAfterError(sessionId, entry);
+ if (getComputerTool(name)?.readOnly !== true) {
+ await cleanup.catch(() => undefined);
+ throw new ComputerDriverError('Driver connection failed during an action. Its outcome is unknown; the action was not replayed. Take fresh state before continuing.', 'ACTION_OUTCOME_UNKNOWN', true);
+ }
if (shouldUseCliFallbackAfterError(name, err)) {
try {
return await callCuaCliTool(name);
@@ -3377,69 +3413,25 @@ export async function callComputerDriverTool(
}
if (shouldRetryWithFreshCuaSession(name, err)) {
await cleanup.catch(() => undefined);
+ assertActive();
if (getCuaMcpSessionCloseVersion(sessionId) !== sessionCloseVersion) {
throw err;
}
- const freshEntry = await getCuaMcpSession(sessionId);
- assertComputerDriverToolDispatchAvailable();
- if (getCuaMcpSessionCloseVersion(sessionId) !== sessionCloseVersion) {
- await cleanupComputerDriverSessionInternal(sessionId, {
- resetGeneration: false,
- expectedEntry: freshEntry,
- }).catch(() => undefined);
- throw err;
- }
- const retryArgs = err instanceof ComputerDriverTypeTextRetryError
- ? {
- ...normalizedArgs,
- text: err.remainingText,
- }
- : normalizedArgs;
- const freshArgs = applyDriverSessionArgs(name, retryArgs, freshEntry.driverSessionId);
- await initializeDefaultCursorStyle(
- name,
- freshArgs,
- freshEntry,
- freshEntry.driverSessionId,
- sessionCloseVersion,
- );
- if (getCuaMcpSessionCloseVersion(sessionId) !== sessionCloseVersion) {
- await cleanupComputerDriverSessionInternal(sessionId, {
- resetGeneration: false,
- expectedEntry: freshEntry,
- }).catch(() => undefined);
- throw err;
- }
+ const freshEntry = await getCuaMcpSession(sessionId, signal);
let retryResult: unknown;
try {
- retryResult = await callCuaMcpToolWithTypeTextChunks(freshEntry, name, freshArgs, timeoutMs);
+ assertActive();
+ const freshArgs = applyDriverSessionArgs(name, normalizedArgs, freshEntry.driverSessionId, freshEntry.toolSchemas);
+ await initializeDefaultCursorStyle(name, freshArgs, freshEntry, freshEntry.driverSessionId,
+ sessionCloseVersion, signal, assertActive);
+ retryResult = await callCuaMcpToolWithTypeTextChunks(freshEntry, name, freshArgs, timeoutMs, signal, assertActive);
} catch (retryErr) {
- if (shouldCleanupCuaMcpSessionAfterError(retryErr)) {
+ if (signal?.aborted || getCuaMcpSessionCloseVersion(sessionId) !== sessionCloseVersion
+ || shouldCleanupCuaMcpSessionAfterError(retryErr)) {
await cleanupCuaMcpSessionAfterError(sessionId, freshEntry).catch(() => undefined);
}
return tryWindowsWin32Fallback(name, rawArgs, retryErr);
}
- if (err instanceof ComputerDriverTypeTextRetryError) {
- const retryResultObject = objectValue(retryResult);
- const retryInserted = typeof retryResultObject?.inserted === 'number'
- ? retryResultObject.inserted
- : retryResultObject?.ok === false
- ? 0
- : Array.from(err.remainingText).length;
- const retryChars = typeof retryResultObject?.chars === 'number'
- ? retryResultObject.chars
- : retryInserted;
- return {
- ...(retryResultObject ?? {}),
- inserted: err.completedChars + retryInserted,
- chunks: err.completedChunks + (
- typeof retryResultObject?.chunks === 'number'
- ? retryResultObject.chunks
- : 1
- ),
- chars: err.completedChars + retryChars,
- };
- }
return name === 'list_windows' ? enrichAndFilterListWindowsResult(retryResult, rawArgs) : retryResult;
}
void cleanup;
diff --git a/apps/desktop/src/main/smoke/COMPUTER_USE.md b/apps/desktop/src/main/smoke/COMPUTER_USE.md
new file mode 100644
index 0000000000..0b8c2cec72
--- /dev/null
+++ b/apps/desktop/src/main/smoke/COMPUTER_USE.md
@@ -0,0 +1,29 @@
+# Computer Use regression smoke
+
+Run from a task worktree on macOS with an installed, OS-authorized cua-driver and an unlocked desktop:
+
+```sh
+CINDY_CUA_SMOKE=1 XDT_CDP_PORT=9237 pnpm restart:desktop:remote -- --region=global --isolated=@worktree --isolated-auth
+pnpm desktop:whoami --all
+```
+
+Use an unused CDP port when other development instances are running. Startup must
+report `DESKTOP_DEV_VERDICT=ready` and the worktree must match. Separately inspect
+`computer-use-smoke.json` in the isolated instance's reported userData directory:
+only `ok:true` proves the smoke completed. The opt-in is ignored in packaged or
+non-isolated instances and does not change the saved Computer Use preference.
+
+The fixture exercises the public MCP dispatcher, host adapter and actual driver.
+It discovers its own disposable window, reads text-only state, forwards opaque
+element credentials, sets multilingual text, clicks a counter, verifies window
+existence, rejects stale credentials, captures a temporary screenshot and rejects
+a cancelled action. Web AX values remain untrusted and verification must return
+unknown; DOM reads independently check exact text and click count.
+The window and temporary files are removed; the report retains bounded fixture
+evidence, excluding the system menu and recent-items tree. A failure is recorded
+without terminating the development app or stopping other driver sessions.
+
+Unit regressions additionally cover cancellation between text chunks, connection
+loss without mutation replay, paginated driver discovery, legacy capture modes,
+malformed verification results and replay stopping on unknown effects. A successful
+macOS smoke does not certify Windows, every application, or every driver release.
diff --git a/apps/desktop/src/main/smoke/computerUseSmoke.ts b/apps/desktop/src/main/smoke/computerUseSmoke.ts
new file mode 100644
index 0000000000..5d699d582b
--- /dev/null
+++ b/apps/desktop/src/main/smoke/computerUseSmoke.ts
@@ -0,0 +1,261 @@
+import { createHash, randomUUID } from 'node:crypto';
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { app, BrowserWindow } from 'electron';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { createComputerMcpServer } from '@cindy/mcps/computer';
+import { cleanupComputerDriverSession, getComputerMcpDeps } from '../mcp-integrations/computer.js';
+import { createLogger } from '../logger.js';
+
+const logger = createLogger('computer-use-smoke');
+let started = false;
+const requested =
+ !app.isPackaged && process.env.XDT_ISOLATED === '1' && process.env.CINDY_CUA_SMOKE === '1';
+
+/** Explicit, isolated, real-driver smoke. It operates only on its own disposable window. */
+export async function runComputerUseSmokeIfRequested(): Promise<void> {
+ if (started || !requested) return;
+ started = true;
+ const sessionId = `cua-smoke-${randomUUID()}`;
+ const checks: string[] = [];
+ let currentStep = 'setup';
+ let root: string | undefined;
+ let window: BrowserWindow | undefined;
+ let client: Client | undefined;
+ let server: ReturnType<typeof createComputerMcpServer> | undefined;
+ const report: Record<string, unknown> = { ok: false, checks, pid: process.pid };
+ const check = (condition: unknown, message: string) => {
+ if (!condition) throw new Error(message);
+ checks.push(message);
+ };
+ try {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-cua-smoke-'));
+ if (process.platform === 'darwin') {
+ const { stdout } = await promisify(execFile)(
+ '/usr/sbin/ioreg',
+ ['-l', '-n', 'Root', '-d', '1'],
+ { timeout: 5000 },
+ );
+ if (/"IOConsoleLocked"\s*=\s*Yes/.test(stdout))
+ throw new Error('macOS desktop is locked. Unlock it and rerun the isolated smoke.');
+ }
+ app.setAccessibilitySupportEnabled(true);
+ window = new BrowserWindow({
+ width: 680,
+ height: 440,
+ show: false,
+ title: 'Cindy Computer Use Smoke',
+ webPreferences: {
+ partition: sessionId,
+ sandbox: true,
+ contextIsolation: true,
+ webSecurity: true,
+ nodeIntegration: false,
+ nodeIntegrationInSubFrames: false,
+ nodeIntegrationInWorker: false,
+ allowRunningInsecureContent: false,
+ experimentalFeatures: false,
+ plugins: false,
+ navigateOnDragDrop: false,
+ webviewTag: false,
+ },
+ });
+ window.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
+ window.webContents.on('will-navigate', (event) => event.preventDefault());
+ const script = `document.getElementById('increment').addEventListener('click',()=>{const n=document.getElementById('count');n.textContent=String(Number(n.textContent)+1);const b=document.getElementById('increment');b.textContent='Smoke clicked once';b.disabled=true})`;
+ const hash = createHash('sha256').update(script).digest('base64');
+ await window.loadURL(
+ `data:text/html;charset=utf-8,${encodeURIComponent(`<!doctype html><html><head><title>Cindy Computer Use Smoke</title><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-${hash}'"></head><body><h1>Computer Use regression fixture</h1><label for="message">Smoke message</label><textarea id="message" aria-label="Smoke message"></textarea><button id="increment">Increment smoke count</button><output id="count">0</output><script>${script}</script></body></html>`)}`,
+ );
+ window.showInactive();
+ server = createComputerMcpServer(getComputerMcpDeps({ isComputerUseEnabled: () => true }), {
+ sessionId,
+ getSessionContext: () => ({ sessionId, agentKind: 'computer-smoke', workingDir: root! }),
+ });
+ client = new Client({ name: 'cindy-cua-smoke', version: '1.0.0' });
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
+ const call = async (name: string, args: Record<string, unknown>, signal?: AbortSignal) => {
+ currentStep = name;
+ const result = await client!.callTool(
+ { name: 'call_tool', arguments: { name, args } },
+ undefined,
+ { signal, timeout: 60_000 },
+ );
+ const first = (result.content as Array<{ text?: string }>)[0];
+ const payload = JSON.parse(first?.text ?? '{}') as Record<string, any>;
+ // Keep evidence metadata, never retain the system menu / recent-items AX tree.
+ report.lastResult = {
+ ok: payload.ok,
+ errorCode: payload.errorCode,
+ outcome: payload.outcome,
+ effect: payload.data?.effect,
+ status: payload.data?.status,
+ message: payload.data?.message,
+ };
+ if (name === 'verify_state') report.verification = payload.data;
+ return payload;
+ };
+ const catalog = await call('list_windows', { pid: process.pid });
+ const target = catalog.data?.windows?.find(
+ (item: { title?: string }) => item.title === 'Cindy Computer Use Smoke',
+ );
+ check(target && Number.isInteger(target.window_id), 'own fixture window discovered');
+ const targetArgs = { pid: process.pid, window_id: target.window_id };
+ let state = await call('get_window_state', { ...targetArgs, include_screenshot: false });
+ for (
+ let attempt = 0;
+ attempt < 10 &&
+ !state.data?.elements?.some(
+ (item: { role?: string; label?: string }) =>
+ item.role === 'AXTextArea' && item.label === 'Smoke message',
+ );
+ attempt += 1
+ ) {
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ state = await call('get_window_state', { ...targetArgs, include_screenshot: false });
+ }
+ check(
+ state.ok &&
+ !state.data?.screenshot &&
+ !state.data?.screenshot_path &&
+ !state.data?.screenshot_out_file,
+ 'text observation excludes screenshot',
+ );
+ const elements = state.data?.elements as Array<{
+ element_token?: string;
+ role?: string;
+ label?: string;
+ }>;
+ report.observationSummary = {
+ keys: Object.keys(state.data ?? {}),
+ element_count: state.data?.element_count,
+ degraded_reason: state.data?.degraded_reason,
+ roles: elements?.slice(0, 12).map((item) => item.role),
+ window_id: target.window_id,
+ };
+ report.fixtureElements = elements?.filter(
+ (item) => item.label === 'Smoke message' || item.label === 'Increment smoke count',
+ );
+ const input = elements?.find(
+ (item) => item.role === 'AXTextArea' && item.label === 'Smoke message',
+ );
+ const button = elements?.find(
+ (item) => item.role === 'AXButton' && item.label === 'Increment smoke count',
+ );
+ check(input?.element_token && button?.element_token, 'opaque element tokens available');
+ const value = 'Cindy smoke 中文 123';
+ const set = await call('set_value', {
+ ...targetArgs,
+ element_token: input!.element_token,
+ value,
+ });
+ check(set.ok, 'set_value dispatched successfully');
+ check(
+ (await window.webContents.executeJavaScript('document.getElementById("message").value')) ===
+ value,
+ 'independent DOM confirms exact input',
+ );
+ const click = await call('click', {
+ ...targetArgs,
+ element_token: button!.element_token,
+ delivery_mode: 'background',
+ });
+ check(click.ok, 'background click dispatched successfully');
+ check(
+ (await window.webContents.executeJavaScript(
+ 'document.getElementById("count").textContent',
+ )) === '1',
+ 'independent DOM confirms exactly one click',
+ );
+ const textVerification = await call('verify_state', {
+ ...targetArgs,
+ expect: [
+ {
+ element: {
+ selector: { role: 'AXTextArea', label_contains: 'Smoke message' },
+ value_equals: value,
+ },
+ },
+ ],
+ timeout_ms: 2000,
+ });
+ // The driver deliberately does not trust web AXValue. The DOM oracle above
+ // proves the input independently; preserve unknown instead of claiming success.
+ check(
+ !textVerification.ok && textVerification.outcome?.status === 'unknown',
+ 'untrusted web value is not reported as verified',
+ );
+ const verified = await call('verify_state', {
+ ...targetArgs,
+ expect: [{ window: { exists: true } }],
+ timeout_ms: 2000,
+ });
+ check(
+ verified.ok && verified.outcome?.status === 'confirmed',
+ 'bounded window existence verification satisfied',
+ );
+ const stale = await call('click', { ...targetArgs, element_token: button!.element_token });
+ check(stale.errorCode === 'STALE_SNAPSHOT', 'verification invalidates old element credentials');
+ check(
+ (await window.webContents.executeJavaScript(
+ 'document.getElementById("count").textContent',
+ )) === '1',
+ 'stale action never reaches fixture',
+ );
+ const imagePath = path.join(root, 'window.png');
+ const imageState = await call('get_window_state', {
+ ...targetArgs,
+ include_screenshot: true,
+ screenshot_out_file: imagePath,
+ });
+ check(
+ imageState.ok && (await fs.stat(imagePath)).size > 0,
+ 'explicit screenshot written inside temporary workspace',
+ );
+ const controller = new AbortController();
+ controller.abort();
+ await call('click', { ...targetArgs, x: 1, y: 1 }, controller.signal).then(
+ () => {
+ throw new Error('pre-cancelled action unexpectedly returned');
+ },
+ () => checks.push('pre-cancelled action rejected'),
+ );
+ check(
+ (await window.webContents.executeJavaScript(
+ 'document.getElementById("count").textContent',
+ )) === '1',
+ 'cancelled action leaves fixture unchanged',
+ );
+ report.ok = true;
+ delete report.lastResult;
+ delete report.observation;
+ delete report.fixtureElements;
+ delete report.observationSummary;
+ delete report.verification;
+ } catch (error) {
+ report.error = error instanceof Error ? error.message : String(error);
+ report.step = currentStep;
+ } finally {
+ await client?.close().catch(() => undefined);
+ await server?.close().catch(() => undefined);
+ await cleanupComputerDriverSession(sessionId).catch(() => undefined);
+ if (window && !window.isDestroyed()) window.destroy();
+ if (root) await fs.rm(root, { recursive: true, force: true });
+ const reportPath = path.join(app.getPath('userData'), 'computer-use-smoke.json');
+ await fs
+ .writeFile(reportPath, `${JSON.stringify(report, null, 2)}\n`)
+ .catch((error: unknown) =>
+ logger.warn('failed to write smoke report', { error: String(error) }),
+ );
+ logger.info('Computer Use smoke finished', {
+ ok: report.ok,
+ checks: checks.length,
+ reportPath,
+ });
+ }
+}
diff --git a/packages/lizi-mcps/package.json b/packages/lizi-mcps/package.json
index 6539ff75fa..f44770505c 100644
--- a/packages/lizi-mcps/package.json
+++ b/packages/lizi-mcps/package.json
@@ -7,7 +7,8 @@
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./computer": "./src/computer/index.ts"
},
"scripts": {
"build": "tsc --noEmit",
diff --git a/packages/lizi-mcps/src/computer/computerMcpServer.test.ts b/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
index 25fec20b65..5281a47194 100644
--- a/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
+++ b/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
@@ -69,6 +69,20 @@ async function makeHarness(
}
describe('createComputerMcpServer', () => {
+ it('halts replay after an unknown action effect even with stop_on_error false', async () => {
+ const root = await makeWorkingDir();
+ const h = await makeHarness({ getStatus: vi.fn(), callTool: vi.fn(async () => ({ effect: 'unverifiable' })) }, {
+ sessionId: 'replay-unknown', getSessionContext: () => ({ sessionId: 'replay-unknown', agentKind: 'test', workingDir: root }),
+ });
+ try {
+ const dir = await writeTrajectory(root, [
+ { tool: 'click', arguments: { pid: 1, window_id: 2, x: 1, y: 2 } },
+ { tool: 'click', arguments: { pid: 1, window_id: 2, x: 3, y: 4 } },
+ ]);
+ const payload = textPayload(await h.client.callTool({ name: 'call_tool', arguments: { name: 'replay_trajectory', args: { dir, stop_on_error: false } } }));
+ expect(payload).toMatchObject({ data: { attempted: 1, succeeded: 0, failed: 1 } });
+ } finally { await h.cleanup(); await fs.rm(root, { recursive: true, force: true }); }
+ });
it('lists desktop computer-use tools', async () => {
const deps: ComputerMcpDeps = {
getStatus: vi.fn(),
@@ -102,7 +116,7 @@ describe('createComputerMcpServer', () => {
expect(listWindows?.description).toContain('{"process_name":"Simulator"}');
expect(payload.workflow).toContain('{"process_name":"Simulator"}');
expect(payload.tools.find((tool) => tool.name === 'get_window_state')?.description)
- .toContain('{"capture_mode":"vision"}');
+ .toContain('include_screenshot:false');
expect(payload.tools.find((tool) => tool.name === 'click')?.description)
.toContain('Always include pid');
expect(payload.tools.find((tool) => tool.name === 'launch_app')?.description)
@@ -113,7 +127,7 @@ describe('createComputerMcpServer', () => {
.not.toHaveProperty('use_external_ios_workflow');
expect(typeText?.inputSchema?.properties).toHaveProperty('delivery_mode');
expect(payload.workflow).toContain('always for coordinates');
- expect(payload.workflow).toContain('{"capture_mode":"vision"}');
+ expect(payload.workflow).toContain('include_screenshot:false');
await h.cleanup();
});
@@ -193,7 +207,7 @@ describe('createComputerMcpServer', () => {
})) as { ok: boolean };
expect(payload.ok).toBe(true);
- expect(deps.callTool).toHaveBeenCalledWith('get_accessibility_tree', {});
+ expect(deps.callTool).toHaveBeenCalledWith('get_accessibility_tree', {}, { signal: expect.any(AbortSignal) });
await h.cleanup();
});
@@ -222,7 +236,7 @@ describe('createComputerMcpServer', () => {
workspace_root: '/repo',
process_name: 'Electron',
session: 'agent-session-1',
- }, { sessionId: 'agent-session-1' });
+ }, { signal: expect.any(AbortSignal), sessionId: 'agent-session-1' });
await h.cleanup();
});
@@ -245,7 +259,7 @@ describe('createComputerMcpServer', () => {
expect(deps.callTool).toHaveBeenCalledWith('list_windows', {
process_name: 'Simulator',
session: 'agent-session-1',
- }, { sessionId: 'agent-session-1' });
+ }, { signal: expect.any(AbortSignal), sessionId: 'agent-session-1' });
await h.cleanup();
});
@@ -267,7 +281,7 @@ describe('createComputerMcpServer', () => {
expect(payload.ok).toBe(true);
expect(deps.callTool).toHaveBeenCalledWith('list_windows', {
process_name: 'Simulator',
- });
+ }, { signal: expect.any(AbortSignal) });
await h.cleanup();
});
@@ -320,7 +334,7 @@ describe('createComputerMcpServer', () => {
window_id: 7,
capture_mode: 'vision',
session: 'agent-session-1',
- }, { sessionId: 'agent-session-1' });
+ }, { signal: expect.any(AbortSignal), sessionId: 'agent-session-1' });
await h.cleanup();
});
@@ -344,7 +358,7 @@ describe('createComputerMcpServer', () => {
pid: 123,
window_id: 7,
capture_mode: 'vision',
- });
+ }, { signal: expect.any(AbortSignal) });
await h.cleanup();
});
@@ -446,7 +460,7 @@ describe('createComputerMcpServer', () => {
pid: 123,
text: 'hello',
delivery_mode: 'foreground',
- });
+ }, { signal: expect.any(AbortSignal) });
await h.cleanup();
});
@@ -472,7 +486,7 @@ describe('createComputerMcpServer', () => {
y1: 20,
x2: 110,
y2: 120,
- });
+ }, { signal: expect.any(AbortSignal) });
await h.cleanup();
});
@@ -502,7 +516,7 @@ describe('createComputerMcpServer', () => {
creates_new_application_instance: true,
electron_debugging_port: 9222,
additional_arguments: ['--flag'],
- });
+ }, { signal: expect.any(AbortSignal) });
await h.cleanup();
});
@@ -524,7 +538,7 @@ describe('createComputerMcpServer', () => {
expect(payload.ok).toBe(true);
expect(deps.callTool).toHaveBeenCalledWith('launch_app', {
name: 'Simulator',
- });
+ }, { signal: expect.any(AbortSignal) });
await h.cleanup();
});
@@ -552,7 +566,7 @@ describe('createComputerMcpServer', () => {
name: 'Xcode',
bundle_id: 'com.apple.dt.Xcode',
urls: ['file:///repo/App.xcworkspace'],
- });
+ }, { signal: expect.any(AbortSignal) });
await h.cleanup();
});
@@ -580,8 +594,7 @@ describe('createComputerMcpServer', () => {
expect(deps.callTool).toHaveBeenCalledWith(
name,
{ ...args, session: 'agent-session-1' },
- { sessionId: 'agent-session-1' },
- );
+ { signal: expect.any(AbortSignal), sessionId: 'agent-session-1' });
await h.cleanup();
},
);
@@ -656,7 +669,7 @@ describe('createComputerMcpServer', () => {
window_id: 7,
element_index: 2,
value: 'Option',
- });
+ }, { signal: expect.any(AbortSignal) });
await h.cleanup();
});
@@ -703,7 +716,7 @@ describe('createComputerMcpServer', () => {
direction: 'down',
amount: 3,
by: 'page',
- });
+ }, { signal: expect.any(AbortSignal) });
await h.cleanup();
});
@@ -729,7 +742,7 @@ describe('createComputerMcpServer', () => {
x: 10,
y: 20,
session: 'agent-session-1',
- }, { sessionId: 'agent-session-1' });
+ }, { signal: expect.any(AbortSignal), sessionId: 'agent-session-1' });
await h.cleanup();
});
@@ -771,14 +784,14 @@ describe('createComputerMcpServer', () => {
x: 10,
y: 20,
session: 'dynamic-session-1',
- }, { sessionId: 'dynamic-session-1', agentKind: 'codex' });
+ }, { signal: expect.any(AbortSignal), sessionId: 'dynamic-session-1', agentKind: 'codex' });
expect(deps.callTool).toHaveBeenNthCalledWith(2, 'click', {
pid: 123,
window_id: 7,
x: 11,
y: 21,
session: 'dynamic-session-2',
- }, { sessionId: 'dynamic-session-2', agentKind: 'codex' });
+ }, { signal: expect.any(AbortSignal), sessionId: 'dynamic-session-2', agentKind: 'codex' });
await h.cleanup();
});
@@ -803,7 +816,7 @@ describe('createComputerMcpServer', () => {
y: 20,
cursor_id: 'agent-session-1',
session: 'agent-session-1',
- }, { sessionId: 'agent-session-1' });
+ }, { signal: expect.any(AbortSignal), sessionId: 'agent-session-1' });
await h.cleanup();
});
@@ -825,7 +838,7 @@ describe('createComputerMcpServer', () => {
expect(payload.ok).toBe(true);
expect(deps.callTool).toHaveBeenCalledWith('get_agent_cursor_state', {
cursor_id: 'agent-session-1',
- }, { sessionId: 'agent-session-1' });
+ }, { signal: expect.any(AbortSignal), sessionId: 'agent-session-1' });
await h.cleanup();
});
@@ -858,7 +871,7 @@ describe('createComputerMcpServer', () => {
output_dir: path.join(root, 'rec'),
record_video: true,
session: 'recording-session',
- }, { sessionId: 'recording-session', agentKind: 'claude-code' });
+ }, { signal: expect.any(AbortSignal), sessionId: 'recording-session', agentKind: 'claude-code' });
await h.cleanup();
await fs.rm(root, { recursive: true, force: true });
});
@@ -992,8 +1005,7 @@ describe('createComputerMcpServer', () => {
expect(deps.callTool).toHaveBeenCalledWith(
'click',
{ pid: 123, window_id: 7, x: 10, y: 20 },
- { agentKind: 'claude-code' },
- );
+ { signal: expect.any(AbortSignal), agentKind: 'claude-code' });
expect(deps.callTool).not.toHaveBeenCalledWith(
'replay_trajectory',
expect.anything(),
@@ -1052,8 +1064,7 @@ describe('createComputerMcpServer', () => {
window_id: 1,
screenshot_out_file: path.join(realWorkingDir, 'screens', 'state.png'),
},
- { agentKind: 'claude-code' },
- );
+ { signal: expect.any(AbortSignal), agentKind: 'claude-code' });
await h.cleanup();
await fs.rm(container, { recursive: true, force: true });
},
@@ -1089,13 +1100,13 @@ describe('createComputerMcpServer', () => {
1,
'launch_app',
{ name: 'Simulator' },
- { agentKind: 'claude-code' },
+ { signal: expect.any(AbortSignal), agentKind: 'claude-code' },
);
expect(deps.callTool).toHaveBeenNthCalledWith(
2,
'click',
{ pid: 202, window_id: 2, x: 30, y: 40 },
- { agentKind: 'claude-code' },
+ { signal: expect.any(AbortSignal), agentKind: 'claude-code' },
);
await h.cleanup();
await fs.rm(root, { recursive: true, force: true });
@@ -1135,8 +1146,7 @@ describe('createComputerMcpServer', () => {
expect(callTool).toHaveBeenCalledWith(
'type_text',
{ pid: 616, text: 'original text' },
- { agentKind: 'claude-code' },
- );
+ { signal: expect.any(AbortSignal), agentKind: 'claude-code' });
expect(callTool).not.toHaveBeenCalledWith('launch_app', expect.anything());
await h.cleanup();
await fs.rm(root, { recursive: true, force: true });
diff --git a/packages/lizi-mcps/src/computer/index.ts b/packages/lizi-mcps/src/computer/index.ts
index 7d10e54be2..5461616fc9 100644
--- a/packages/lizi-mcps/src/computer/index.ts
+++ b/packages/lizi-mcps/src/computer/index.ts
@@ -1,2 +1,3 @@
export * from './server.js';
export * from './tools.js';
+export * from './result.js';
diff --git a/packages/lizi-mcps/src/computer/result.test.ts b/packages/lizi-mcps/src/computer/result.test.ts
new file mode 100644
index 0000000000..059d548e44
--- /dev/null
+++ b/packages/lizi-mcps/src/computer/result.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+import { computerResultOutcome } from './result.js';
+
+describe('Computer Use result evidence', () => {
+ it.each(['partial', 'unverifiable', 'suspected_noop'])(
+ 'does not report %s as confirmed',
+ (effect) => {
+ expect(computerResultOutcome('click', { effect })).toMatchObject({
+ ok: true,
+ outcome: { status: 'unknown', next_step: 'verify_state' },
+ });
+ },
+ );
+ it.each([{ ok: false }, { isError: true }, { effect: 'refused' }])(
+ 'preserves driver failures: %j',
+ (data) => {
+ expect(computerResultOutcome('click', data)).toMatchObject({
+ ok: false,
+ outcome: { status: 'failed' },
+ });
+ },
+ );
+ it.each([
+ null,
+ 'satisfied',
+ [],
+ {},
+ { status: 'unknown' },
+ { status: 'unsatisfied' },
+ { status: 'satisfied', stable: false },
+ ])('requires interpretable verification evidence: %j', (data) => {
+ expect(computerResultOutcome('verify_state', data)).toMatchObject({
+ ok: false,
+ errorCode: 'POSTCONDITION_NOT_SATISFIED',
+ });
+ });
+ it('confirms only a satisfied verification', () => {
+ expect(computerResultOutcome('verify_state', { status: 'satisfied' })).toEqual({
+ ok: true,
+ outcome: { status: 'confirmed', next_step: 'done' },
+ });
+ });
+});
diff --git a/packages/lizi-mcps/src/computer/result.ts b/packages/lizi-mcps/src/computer/result.ts
new file mode 100644
index 0000000000..22a0f985b3
--- /dev/null
+++ b/packages/lizi-mcps/src/computer/result.ts
@@ -0,0 +1,52 @@
+/** Tool delivery is separate from evidence that a requested postcondition holds. */
+export function computerResultOutcome(
+ name: string,
+ data: unknown,
+): {
+ ok: boolean;
+ errorCode?: string;
+ outcome?: {
+ status: 'confirmed' | 'unknown' | 'failed';
+ next_step: 'verify_state' | 'fresh_state' | 'done';
+ };
+} {
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
+ return name === 'verify_state'
+ ? {
+ ok: false,
+ errorCode: 'POSTCONDITION_NOT_SATISFIED',
+ outcome: { status: 'unknown', next_step: 'fresh_state' },
+ }
+ : { ok: true };
+ }
+ const result = data as Record<string, unknown>;
+ const failure = result.ok === false || result.isError === true || result.effect === 'refused';
+ if (failure) {
+ return {
+ ok: false,
+ errorCode: typeof result.code === 'string' ? result.code : 'COMPUTER_DRIVER_ERROR',
+ outcome: { status: 'failed', next_step: 'fresh_state' },
+ };
+ }
+ if (name === 'verify_state') {
+ const satisfied = result.status === 'satisfied' && result.stable !== false;
+ return {
+ ok: satisfied,
+ ...(!satisfied ? { errorCode: 'POSTCONDITION_NOT_SATISFIED' } : {}),
+ outcome: {
+ status: satisfied ? 'confirmed' : result.status === 'unsatisfied' ? 'failed' : 'unknown',
+ next_step: satisfied ? 'done' : 'fresh_state',
+ },
+ };
+ }
+ if (typeof result.effect === 'string') {
+ return {
+ ok: true,
+ outcome: {
+ status: result.effect === 'confirmed' ? 'confirmed' : 'unknown',
+ next_step: 'verify_state',
+ },
+ };
+ }
+ return { ok: true };
+}
diff --git a/packages/lizi-mcps/src/computer/server.ts b/packages/lizi-mcps/src/computer/server.ts
index 09227c108f..c98349aa0e 100644
--- a/packages/lizi-mcps/src/computer/server.ts
+++ b/packages/lizi-mcps/src/computer/server.ts
@@ -18,6 +18,7 @@ import {
} from './tools.js';
import { logToolResultErrorCode } from '../tool-error-telemetry.js';
import { WindowSnapshotTracker } from './snapshot-tracker.js';
+import { computerResultOutcome } from './result.js';
export interface ComputerMcpServerOptions {
sessionId?: string;
@@ -46,6 +47,7 @@ function textResult(value: unknown, isError?: boolean) {
const SESSION_AWARE_TOOLS = new Set<ComputerMcpToolName>([
'list_windows',
'get_window_state',
+ 'verify_state',
'click',
'double_click',
'right_click',
@@ -290,7 +292,7 @@ export function createComputerMcpServer(
inputSchema: z.toJSONSchema(z.object(tool.inputShape).strict()),
})),
workflow:
- 'Start with status and check_permissions. Use get_accessibility_tree/list_windows, optionally narrow list_windows with query/workspace_root/process_name (for example, {"process_name":"Simulator"}), inspect a target with get_window_state, perform one action, and call get_window_state again to verify. Targeted actions such as click/type_text require pid; include window_id whenever the target window is known, and always for coordinates. Use get_window_state with {"capture_mode":"vision"} for screenshots and normally omit screenshot_out_file. Element indices are only valid for the latest snapshot of the same pid/window_id: pass the snapshot_id from get_window_state along with element_index, and re-observe when an action is rejected with STALE_SNAPSHOT. Use start_recording/stop_recording/replay_trajectory only when the user explicitly asks for recording or replay.',
+ 'Start with status and check_permissions. Use get_accessibility_tree/list_windows, optionally narrow list_windows with query/workspace_root/process_name (for example, {"process_name":"Simulator"}), inspect a target with get_window_state, perform one action, and call get_window_state again to verify. Targeted actions such as click/type_text require pid; include window_id whenever the target window is known, and always for coordinates. Use get_window_state with include_screenshot:false for bounded text observations; request an image for visual grounding and normally omit screenshot_out_file. Prefer the exact element_token returned by the latest observation, or pass snapshot_id with element_index. Re-observe on STALE_SNAPSHOT. After an action, verify its intended postcondition with verify_state or a fresh observation; a delivered or unverifiable action does not prove completion. Never replay a mutation automatically after cancellation or a connection failure. Use start_recording/stop_recording/replay_trajectory only when the user explicitly asks for recording or replay.',
}),
);
@@ -360,8 +362,18 @@ export function createComputerMcpServer(
// 它是否仍是目标窗口最新观察;不带的放行(过渡兼容)但打遥测日志。
const staleResult = checkSnapshotFreshness(name as ComputerMcpToolName, parsedData, sessionId);
if (staleResult) return staleResult;
- // snapshot_id 是 MCP 层的护栏参数,driver 不认识,派发前剥掉。
- delete parsedData.snapshot_id;
+ if (typeof parsedData.snapshot_id === 'string') {
+ const driverId = snapshotTracker.driverSnapshotId(sessionId, parsedData.snapshot_id);
+ if (driverId) parsedData.snapshot_id = driverId;
+ else delete parsedData.snapshot_id; // Legacy drivers have no native snapshot ids.
+ }
+ if (name === 'set_value' && parsedData.element_index === undefined && parsedData.element_token === undefined) {
+ return textResult({ ok: false, errorCode: 'INVALID_ARGS', data: { message: 'set_value requires element_token or element_index.' } }, true);
+ }
+ if (name === 'verify_state' || name === 'get_window_state') {
+ snapshotTracker.invalidate(sessionId, parsedData.pid as number, parsedData.window_id as number);
+ }
+ if (signal?.aborted) return replayCancelledResult();
const parsedArgs = withSessionArg(
name as ComputerMcpToolName,
@@ -374,11 +386,11 @@ export function createComputerMcpServer(
deps,
name as ComputerMcpToolName,
parsedArgs,
- callContext,
+ { ...callContext, signal },
);
if (
name === 'get_window_state' &&
- isUnavailableWindowObservation(data, parsedData.capture_mode)
+ isUnavailableWindowObservation(data, parsedData)
) {
invalidateWindowSnapshot(name, parsedData, sessionId);
return textResult(
@@ -392,20 +404,29 @@ export function createComputerMcpServer(
true,
);
}
+ const outcome = computerResultOutcome(name, data);
const snapshotId = recordWindowSnapshot(name as ComputerMcpToolName, parsedData, data, sessionId);
return textResult({
- ok: true,
+ ...outcome,
tool: name,
...(snapshotId ? { snapshot_id: snapshotId } : {}),
data,
- });
+ }, !outcome.ok);
} catch (err) {
invalidateWindowSnapshot(name, parsedData, sessionId);
+ if ((signal?.aborted || (err as { outcomeUnknown?: boolean })?.outcomeUnknown)
+ && typeof parsedData.pid === 'number' && typeof parsedData.window_id === 'number') {
+ snapshotTracker.invalidate(sessionId, parsedData.pid, parsedData.window_id);
+ }
return textResult(
{
ok: false,
- errorCode: 'COMPUTER_DRIVER_ERROR',
- data: { message: err instanceof Error ? err.message : String(err) },
+ errorCode: signal?.aborted ? 'REQUEST_CANCELLED' :
+ typeof (err as { code?: unknown })?.code === 'string' ? (err as { code: string }).code : 'COMPUTER_DRIVER_ERROR',
+ data: {
+ message: err instanceof Error ? err.message : String(err),
+ ...((err as { outcomeUnknown?: boolean })?.outcomeUnknown ? { outcome_unknown: true, next_step: 'fresh_state' } : {}),
+ },
},
true,
);
@@ -815,7 +836,9 @@ export function createComputerMcpServer(
pathWorkingDirOverride: prepared.workingRoot,
});
if (signal?.aborted) return replayCancelledResult();
- const isError = result.isError === true;
+ const payload = JSON.parse(result.content[0].text) as { outcome?: { status?: string }; data?: { outcome_unknown?: boolean } };
+ const outcomeUnknown = payload.outcome?.status === 'unknown' || payload.data?.outcome_unknown === true;
+ const isError = result.isError === true || outcomeUnknown;
const summaryBudget = Math.max(
0,
Math.min(
@@ -838,7 +861,7 @@ export function createComputerMcpServer(
tool: action.tool,
error: summary,
};
- if (prepared.stopOnError) break;
+ if (prepared.stopOnError || outcomeUnknown) break;
} else {
succeeded += 1;
}
@@ -931,11 +954,20 @@ export function createComputerMcpServer(
sessionId: string | undefined,
) {
if (!ELEMENT_INDEX_ACTION_TOOLS.has(name)) return null;
- if (typeof parsedData.element_index !== 'number') return null;
+ if (typeof parsedData.element_index !== 'number' && typeof parsedData.element_token !== 'string') return null;
const pid = parsedData.pid as number;
const windowId = typeof parsedData.window_id === 'number' ? parsedData.window_id : undefined;
- const snapshotId = typeof parsedData.snapshot_id === 'string' ? parsedData.snapshot_id : undefined;
+ let snapshotId = typeof parsedData.snapshot_id === 'string' ? parsedData.snapshot_id : undefined;
+ if (typeof parsedData.element_token === 'string') {
+ const ref = snapshotTracker.elementReference(sessionId, parsedData.element_token, snapshotId);
+ if (!ref || (typeof parsedData.element_index === 'number' && ref.index !== parsedData.element_index)
+ || (snapshotId && !snapshotTracker.sameSnapshot(sessionId, snapshotId, ref.snapshotId))) {
+ return textResult({ ok: false, errorCode: 'STALE_SNAPSHOT', data: { message: 'Unknown or conflicting element token. Call get_window_state again.' } }, true);
+ }
+ snapshotId = ref.snapshotId;
+ if (windowId === undefined) parsedData.window_id = ref.windowId;
+ }
if (!snapshotId) {
// 过渡兼容:老调用方 / 未升级的 agent 不带 snapshot_id,放行但留痕,
// 后续可据此评估何时收紧为强制。
@@ -948,7 +980,10 @@ export function createComputerMcpServer(
}
const verdict = snapshotTracker.validate(sessionId, snapshotId, pid, windowId);
- if (verdict.ok) return null;
+ if (verdict.ok) {
+ parsedData.window_id ??= snapshotTracker.windowId(sessionId, snapshotId);
+ return null;
+ }
return textResult(
{
ok: false,
@@ -958,7 +993,7 @@ export function createComputerMcpServer(
snapshot_id: snapshotId,
reason: verdict.reason,
hint:
- 'The element_index comes from a window snapshot that is no longer the latest observation of this window, so the target element may have moved or changed. Call get_window_state again for this pid/window_id, then retry with the fresh snapshot_id and element_index.',
+ 'The element reference does not identify the latest observation of this window. Call get_window_state again, then use its top-level snapshot_id with element_index or element_token. Supplying that snapshot_id is required when the driver reuses tokens between observations.',
},
},
true,
@@ -975,8 +1010,7 @@ export function createComputerMcpServer(
if (name !== 'get_window_state') return null;
if (typeof parsedData.pid !== 'number' || typeof parsedData.window_id !== 'number') return null;
// driver 层失败(data.ok === false)不算一次有效观察,不发新代。
- if (data && typeof data === 'object' && !Array.isArray(data)
- && (data as { ok?: unknown }).ok === false) {
+ if (!data || typeof data !== 'object' || Array.isArray(data) || !computerResultOutcome(name, data).ok) {
return null;
}
const snapshotId = snapshotTracker.record(sessionId, parsedData.pid, parsedData.window_id);
@@ -984,6 +1018,7 @@ export function createComputerMcpServer(
if (driverSnapshotId) {
snapshotTracker.registerAlias(snapshotId, driverSnapshotId);
}
+ snapshotTracker.recordElements(snapshotId, (data as { elements?: unknown })?.elements);
return snapshotId;
}
@@ -993,8 +1028,11 @@ export function createComputerMcpServer(
/** Only explicit driver failure signals override legacy/partial observation success. */
function isUnavailableWindowObservation(
data: unknown,
- captureMode: unknown,
+ args: Record<string, unknown>,
): boolean {
+ const captureMode = typeof args.screenshot_out_file === 'string' || args.include_screenshot === true
+ ? 'vision'
+ : args.include_screenshot === false ? 'ax' : args.capture_mode;
if (!data || typeof data !== 'object' || Array.isArray(data)) return false;
const state = data as Record<string, unknown>;
if (state.ok === false || state.isError === true) return true;
diff --git a/packages/lizi-mcps/src/computer/snapshot-tracker.ts b/packages/lizi-mcps/src/computer/snapshot-tracker.ts
index 0393a4d1e6..ae01edf0b4 100644
--- a/packages/lizi-mcps/src/computer/snapshot-tracker.ts
+++ b/packages/lizi-mcps/src/computer/snapshot-tracker.ts
@@ -38,6 +38,8 @@ interface SnapshotMeta {
sessionKey: string;
pid: number;
windowId: number;
+ driverSnapshotId?: string;
+ elements?: Map<string, number>;
}
/** 保留的窗口数与历史快照数上限(FIFO 淘汰)。 */
@@ -97,6 +99,7 @@ export class WindowSnapshotTracker {
registerAlias(snapshotId: string, alias: string): void {
const meta = this.metaById.get(snapshotId);
if (alias.length === 0 || alias === snapshotId || !meta) return;
+ meta.driverSnapshotId = alias;
const key = this.aliasKey(meta.sessionKey, alias);
// Some drivers may expose a stable per-window id instead of a per-observation id.
// Never overwrite an existing alias, otherwise an old element_index paired with
@@ -109,6 +112,54 @@ export class WindowSnapshotTracker {
this.aliasToId.set(key, snapshotId);
}
+ /** Resolve host ids to the driver's original id; never send a ws-* id to a driver. */
+ driverSnapshotId(sessionId: string | undefined, snapshotId: string): string | undefined {
+ const sessionKey = sessionId ?? '';
+ const id = this.aliasToId.get(this.aliasKey(sessionKey, snapshotId)) ?? snapshotId;
+ const meta = this.metaById.get(id);
+ return meta?.sessionKey === sessionKey ? meta.driverSnapshotId : undefined;
+ }
+
+ sameSnapshot(sessionId: string | undefined, left: string, right: string): boolean {
+ const key = sessionId ?? '';
+ const a = this.aliasToId.get(this.aliasKey(key, left)) ?? left;
+ const b = this.aliasToId.get(this.aliasKey(key, right)) ?? right;
+ return a === b && this.metaById.get(a)?.sessionKey === key;
+ }
+
+ windowId(sessionId: string | undefined, snapshotId: string): number | undefined {
+ const key = sessionId ?? '';
+ const id = this.aliasToId.get(this.aliasKey(key, snapshotId)) ?? snapshotId;
+ const meta = this.metaById.get(id);
+ return meta?.sessionKey === key ? meta.windowId : undefined;
+ }
+
+ recordElements(snapshotId: string, elements: unknown): void {
+ const meta = this.metaById.get(snapshotId);
+ if (!meta || !Array.isArray(elements)) return;
+ meta.elements = new Map();
+ for (const element of elements.slice(0, 2000)) {
+ if (typeof element?.element_token === 'string' && typeof element?.element_index === 'number') {
+ meta.elements.set(element.element_token, element.element_index);
+ }
+ }
+ }
+
+ elementReference(sessionId: string | undefined, token: string, observationId?: string) {
+ // A repeated token is ambiguous without an explicit observation. Never silently
+ // promote an old reference to the newest generation just because its text matches.
+ const canonicalId = observationId === undefined ? undefined
+ : this.aliasToId.get(this.aliasKey(sessionId ?? '', observationId)) ?? observationId;
+ for (const [snapshotId, meta] of this.metaById) {
+ if (canonicalId !== undefined && snapshotId !== canonicalId) continue;
+ const index = meta.elements?.get(token);
+ if (meta.sessionKey === (sessionId ?? '') && index !== undefined) {
+ return { snapshotId, index, windowId: meta.windowId };
+ }
+ }
+ return undefined;
+ }
+
/**
* 动作携带快照 id 时调用:校验它是否仍是目标窗口的最新观察。
* windowId 缺省(动作允许省略 window_id)时只对 pid 做窗口一致性校验。
diff --git a/packages/lizi-mcps/src/computer/snapshotGuard.test.ts b/packages/lizi-mcps/src/computer/snapshotGuard.test.ts
index d2748056e0..275cb49c5f 100644
--- a/packages/lizi-mcps/src/computer/snapshotGuard.test.ts
+++ b/packages/lizi-mcps/src/computer/snapshotGuard.test.ts
@@ -40,6 +40,14 @@ async function makeHarness(deps: ComputerMcpDeps, options?: Parameters<typeof cr
}
describe('WindowSnapshotTracker', () => {
+ it('matches canonical aliases but never treats two unknown ids as equal', () => {
+ const tracker = new WindowSnapshotTracker();
+ const id = tracker.record('s', 1, 2);
+ tracker.registerAlias(id, 's01234567');
+ expect(tracker.sameSnapshot('s', id, 's01234567')).toBe(true);
+ expect(tracker.sameSnapshot('s', 'unknown', id)).toBe(false);
+ expect(tracker.sameSnapshot('s', 'unknown', 'unknown')).toBe(false);
+ });
it('treats only the latest recorded snapshot per window as fresh', () => {
const tracker = new WindowSnapshotTracker();
const first = tracker.record('s1', 100, 1);
@@ -103,6 +111,7 @@ describe('WindowSnapshotTracker', () => {
const second = tracker.record('s1', 100, 1);
tracker.registerAlias(second, 'stable-window-alias');
+ expect(tracker.driverSnapshotId('s1', second)).toBe('stable-window-alias');
expect(tracker.validate('s1', 'stable-window-alias', 100, 1)).toEqual({
ok: false,
@@ -113,6 +122,63 @@ describe('WindowSnapshotTracker', () => {
});
});
+describe('opaque element credentials', () => {
+ it('disambiguates repeated tokens with an explicit fresh observation without reviving old references', async () => {
+ let index = 3;
+ const dispatch = vi.fn(async (name: string) => name === 'get_window_state'
+ ? { snapshot_id: 'stable-window', elements: [{ element_index: index, element_token: 'reused-token' }] }
+ : { effect: 'confirmed' });
+ const h = await makeHarness({ getStatus: vi.fn(), callTool: dispatch }, { sessionId: 'reused' });
+ try {
+ const first = await h.call('get_window_state', { pid: 1, window_id: 2 });
+ index = 4;
+ const second = await h.call('get_window_state', { pid: 1, window_id: 2 });
+ const args = { pid: 1, window_id: 2, element_token: 'reused-token' };
+ for (const snapshot_id of [undefined, first.snapshot_id, 'stable-window', 'unknown']) {
+ expect(await h.call('click', { ...args, snapshot_id })).toMatchObject({ errorCode: 'STALE_SNAPSHOT' });
+ }
+ expect(await h.call('click', { ...args, snapshot_id: second.snapshot_id, element_index: 3 })).toMatchObject({ errorCode: 'STALE_SNAPSHOT' });
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ expect(await h.call('click', { ...args, snapshot_id: second.snapshot_id, element_index: 4 })).toMatchObject({ ok: true });
+ expect(dispatch).toHaveBeenLastCalledWith('click', expect.objectContaining({ snapshot_id: 'stable-window', element_token: 'reused-token', element_index: 4 }), expect.anything());
+ } finally { await h.cleanup(); }
+ });
+ it('invalidates an interrupted index action even when window_id was omitted', async () => {
+ const dispatch = vi.fn(async (name: string) => {
+ if (name === 'get_window_state') return { snapshot_id: 'native-id', elements: [] };
+ throw Object.assign(new Error('connection closed'), { outcomeUnknown: true });
+ });
+ const h = await makeHarness({ getStatus: vi.fn(), callTool: dispatch }, { sessionId: 'interrupted' });
+ try {
+ const state = await h.call('get_window_state', { pid: 1, window_id: 2 });
+ const args = { pid: 1, element_index: 0, snapshot_id: state.snapshot_id };
+ expect(await h.call('click', args)).toMatchObject({ ok: false, data: { outcome_unknown: true } });
+ expect(dispatch).toHaveBeenLastCalledWith('click', expect.objectContaining({ window_id: 2 }), expect.anything());
+ expect(await h.call('click', args)).toMatchObject({ errorCode: 'STALE_SNAPSHOT' });
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ } finally { await h.cleanup(); }
+ });
+ it('forwards exact tokens and native ids, rejects conflicts and invalidates on failed observation', async () => {
+ let observation: unknown = { snapshot_id: 's01234567', elements: [{ element_index: 3, element_token: 'opaque-token' }] };
+ const dispatch = vi.fn(async (name: string) => name === 'get_window_state' ? observation : { effect: 'confirmed' });
+ const h = await makeHarness({ getStatus: vi.fn(), callTool: dispatch }, { sessionId: 'tokens' });
+ try {
+ const state = await h.call('get_window_state', { pid: 1, window_id: 2 });
+ const action = { pid: 1, window_id: 2, element_token: 'opaque-token' };
+ expect(await h.call('click', { ...action, snapshot_id: 'unknown' })).toMatchObject({ errorCode: 'STALE_SNAPSHOT' });
+ expect(await h.call('click', { ...action, element_index: 4 })).toMatchObject({ errorCode: 'STALE_SNAPSHOT' });
+ expect(await h.call('click', { ...action, pid: 9 })).toMatchObject({ errorCode: 'STALE_SNAPSHOT' });
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ expect(await h.call('click', { ...action, snapshot_id: state.snapshot_id })).toMatchObject({ ok: true });
+ expect(dispatch).toHaveBeenLastCalledWith('click', { ...action, snapshot_id: 's01234567', session: 'tokens' }, expect.objectContaining({ signal: expect.any(AbortSignal) }));
+ observation = { isError: true };
+ expect(await h.call('get_window_state', { pid: 1, window_id: 2 })).toMatchObject({ ok: false });
+ expect(await h.call('click', action)).toMatchObject({ errorCode: 'STALE_SNAPSHOT' });
+ expect(dispatch).toHaveBeenCalledTimes(3);
+ } finally { await h.cleanup(); }
+ });
+});
+
describe('computer snapshot guard', () => {
const windowState = { ok: true, elements: [{ index: 0 }, { index: 1 }] };
@@ -181,8 +247,9 @@ describe('computer snapshot guard', () => {
pid: 100,
window_id: 1,
element_index: 1,
+ snapshot_id: 's000c',
session: 'sess-1',
- }, { sessionId: 'sess-1' });
+ }, { signal: expect.any(AbortSignal), sessionId: 'sess-1' });
await h.cleanup();
});
@@ -210,8 +277,9 @@ describe('computer snapshot guard', () => {
pid: 100,
window_id: 1,
element_index: 1,
+ snapshot_id: 's000c',
session: 'sess-1',
- }, { sessionId: 'sess-1' });
+ }, { signal: expect.any(AbortSignal), sessionId: 'sess-1' });
await h.cleanup();
});
@@ -423,6 +491,10 @@ describe('computer snapshot guard', () => {
);
it.each([
+ { args: { include_screenshot: false }, state: { ...failedCapture, elements: [{ index: 0 }] }, ok: true },
+ { args: { include_screenshot: false }, state: { degraded: true, elements: [] }, ok: false },
+ { args: { include_screenshot: true }, state: { ...failedCapture, elements: [{ index: 0 }] }, ok: false },
+ { args: { include_screenshot: false, screenshot_out_file: 'state.png' }, state: { ...failedCapture, elements: [{ index: 0 }] }, ok: false },
{ mode: undefined, state: failedCapture, ok: false },
{
mode: 'vision',
@@ -458,14 +530,17 @@ describe('computer snapshot guard', () => {
{ mode: undefined, state: { elements: [] }, ok: true },
])(
'respects requested observation mode: $mode / ok=$ok',
- async ({ mode, state, ok }) => {
+ async ({ mode, args, state, ok }) => {
const callTool = vi.fn(async () => state);
- const h = await makeHarness({ getStatus: vi.fn(), callTool });
+ const h = await makeHarness({ getStatus: vi.fn(), callTool }, {
+ getSessionContext: () => ({ workingDir: process.cwd(), agentKind: 'test' }),
+ });
try {
const observed = await h.call('get_window_state', {
pid: 100,
window_id: 1,
capture_mode: mode,
+ ...args,
});
expect(observed.ok).toBe(ok);
expect(Boolean(observed.snapshot_id)).toBe(ok);
diff --git a/packages/lizi-mcps/src/computer/tools.ts b/packages/lizi-mcps/src/computer/tools.ts
index cc2bc4de28..8ed8f39f8b 100644
--- a/packages/lizi-mcps/src/computer/tools.ts
+++ b/packages/lizi-mcps/src/computer/tools.ts
@@ -20,6 +20,10 @@ const SNAPSHOT_ID_ARG = z
'snapshot_id returned by the get_window_state call this element_index comes from. Recommended whenever element_index is used: if the window has been observed again since, the action is rejected with STALE_SNAPSHOT so you can re-observe instead of acting on the wrong element.',
);
+const ELEMENT_TOKEN_ARG = z.string().min(1).optional().describe(
+ 'Opaque element_token from the latest get_window_state. Prefer this over element_index; never invent or reuse it after another observation.',
+);
+
export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
{
name: 'status',
@@ -79,19 +83,48 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
{
name: 'get_window_state',
description:
- 'Inspect one window and return its accessibility tree/screenshot state. Use {"capture_mode":"vision"} for a screenshot and normally omit screenshot_out_file so the driver uses its default path. Call before element-indexed actions. The result carries a snapshot_id; pass it to element-indexed actions so actions taken on an outdated view of the window are rejected as STALE_SNAPSHOT instead of hitting the wrong element.',
+ 'Inspect one exact window before acting. Prefer elements[].element_token for actions, or pass snapshot_id with element_index. include_screenshot:false returns only the accessibility tree; request an image when visual grounding is needed. query, max_elements and max_depth bound the observation. Omit screenshot_out_file for a host-managed temporary image.',
readOnly: true,
inputShape: {
pid: z.number().int().positive(),
window_id: z.number().int().nonnegative(),
capture_mode: z.enum(['som', 'vision', 'ax']).optional(),
+ include_screenshot: z.boolean().optional(),
query: z.string().optional(),
screenshot_out_file: z.string().optional(),
session: z.string().optional(),
- max_elements: z.number().int().positive().optional().describe("Maximum number of accessibility tree elements to return. Use to limit context size for complex windows like Chrome."),
+ max_elements: z.number().int().positive().max(2000).optional().describe("Maximum number of accessibility tree elements to return (up to 2000; host default 200). Narrow with query for larger windows."),
max_depth: z.number().int().positive().optional().describe("Maximum depth of the accessibility tree to traverse. Use to limit tree depth for complex windows."),
},
},
+ {
+ name: 'verify_state',
+ description: 'Verify a bounded postcondition against an exact window after an action. Only status:satisfied proves the condition; unknown is not success. This observation invalidates previous element references: get_window_state again before the next element action.',
+ readOnly: true,
+ inputShape: {
+ pid: z.number().int().positive(),
+ window_id: z.number().int().nonnegative(),
+ expect: z.array(z.object({
+ element: z.object({
+ selector: z.object({ role: z.string().min(1).optional(), label_contains: z.string().min(1).optional() }).strict(),
+ exists: z.literal(true).optional(),
+ enabled: z.boolean().optional(),
+ selected: z.boolean().optional(),
+ value_equals: z.string().optional(),
+ }).strict().optional(),
+ window: z.object({
+ exists: z.boolean().optional(),
+ bounds: z.object({
+ x: z.number(), y: z.number(), width: z.number(), height: z.number(),
+ tolerance_px: z.number().min(0).max(100).optional(),
+ }).strict().optional(),
+ }).strict().optional(),
+ }).strict().refine((value) => Boolean(value.element) !== Boolean(value.window), 'Specify one element or window predicate')).min(1).max(8),
+ stable_samples: z.number().int().min(1).max(5).optional(),
+ timeout_ms: z.number().int().min(0).max(10000).optional(),
+ include_screenshot: z.literal(false).optional().describe('Use get_window_state for a host-managed screenshot.'),
+ },
+ },
{
name: 'click',
description:
@@ -101,6 +134,8 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
window_id: z.number().int().nonnegative().optional(),
element_index: z.number().int().nonnegative().optional(),
x: z.number().optional(),
+ element_token: ELEMENT_TOKEN_ARG,
+ delivery_mode: z.enum(['background', 'foreground']).optional(),
y: z.number().optional(),
action: z.string().optional(),
count: z.number().int().positive().optional(),
@@ -119,6 +154,8 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
pid: z.number().int().positive(),
window_id: z.number().int().nonnegative().optional(),
element_index: z.number().int().nonnegative().optional(),
+ element_token: ELEMENT_TOKEN_ARG,
+ delivery_mode: z.enum(['background', 'foreground']).optional(),
x: z.number().optional(),
y: z.number().optional(),
snapshot_id: SNAPSHOT_ID_ARG,
@@ -133,6 +170,8 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
pid: z.number().int().positive(),
window_id: z.number().int().nonnegative().optional(),
element_index: z.number().int().nonnegative().optional(),
+ element_token: ELEMENT_TOKEN_ARG,
+ delivery_mode: z.enum(['background', 'foreground']).optional(),
x: z.number().optional(),
y: z.number().optional(),
modifier: z.array(z.string()).optional(),
@@ -146,6 +185,7 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
inputShape: {
pid: z.number().int().positive(),
window_id: z.number().int().nonnegative().optional(),
+ delivery_mode: z.enum(['background', 'foreground']).optional(),
from_x: z.number(),
from_y: z.number(),
to_x: z.number(),
@@ -167,6 +207,7 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
text: z.string(),
delivery_mode: z.enum(['background', 'foreground']).optional(),
element_index: z.number().int().nonnegative().optional(),
+ element_token: ELEMENT_TOKEN_ARG,
window_id: z.number().int().nonnegative().optional(),
delay_ms: z.number().int().min(0).max(200).optional(),
snapshot_id: SNAPSHOT_ID_ARG,
@@ -180,7 +221,8 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
inputShape: {
pid: z.number().int().positive(),
window_id: z.number().int().nonnegative(),
- element_index: z.number().int().nonnegative(),
+ element_index: z.number().int().nonnegative().optional(),
+ element_token: ELEMENT_TOKEN_ARG,
value: z.string(),
snapshot_id: SNAPSHOT_ID_ARG,
session: z.string().optional(),
@@ -194,6 +236,8 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
key: z.string(),
modifiers: z.array(z.string()).optional(),
element_index: z.number().int().nonnegative().optional(),
+ element_token: ELEMENT_TOKEN_ARG,
+ delivery_mode: z.enum(['background', 'foreground']).optional(),
window_id: z.number().int().nonnegative().optional(),
snapshot_id: SNAPSHOT_ID_ARG,
session: z.string().optional(),
@@ -205,6 +249,7 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
inputShape: {
pid: z.number().int().positive(),
keys: z.array(z.string()).min(2),
+ delivery_mode: z.enum(['background', 'foreground']).optional(),
window_id: z.number().int().nonnegative().optional(),
session: z.string().optional(),
},
@@ -216,6 +261,8 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
pid: z.number().int().positive(),
window_id: z.number().int().nonnegative().optional(),
element_index: z.number().int().nonnegative().optional(),
+ element_token: ELEMENT_TOKEN_ARG,
+ delivery_mode: z.enum(['background', 'foreground']).optional(),
direction: z.enum(['up', 'down', 'left', 'right']),
amount: z.number().int().min(1).max(50).optional(),
by: z.enum(['line', 'page']).optional(),
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index 0cdbfd70a5..9e2e662862 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -552,6 +552,7 @@ export type ComputerMcpToolName =
| 'list_apps'
| 'list_windows'
| 'get_window_state'
+ | 'verify_state'
| 'click'
| 'double_click'
| 'right_click'
@@ -604,6 +605,8 @@ export interface ComputerDriverPermissionState {
export interface ComputerMcpCallContext {
sessionId?: string;
+ /** Request cancellation stays on the host side; never serialized to the driver. */
+ signal?: AbortSignal;
/** Identifies the agent runtime whose MCP server dispatched this call. */
agentKind?: string;
}
diff --git a/scripts/restart-desktop-remote.mjs b/scripts/restart-desktop-remote.mjs
index 29fbab5fb9..8525d9690c 100644
--- a/scripts/restart-desktop-remote.mjs
+++ b/scripts/restart-desktop-remote.mjs
@@ -877,6 +877,7 @@ export function devEnvPrefix(env = process.env, platform = process.platform) {
['XDT_ISOLATED_AUTH_PROOF', env.XDT_ISOLATED_AUTH_PROOF],
// CDP 端口覆写(bootstrap-electron 消费): 并行多开沙箱时给后起实例换端口。
['XDT_CDP_PORT', env.XDT_CDP_PORT],
+ ['CINDY_CUA_SMOKE', env.CINDY_CUA_SMOKE],
// 一次性 Grok wire 归因探针(dev-only;正常环境不设置,不产生额外日志)。
['XDT_WIRE_DIAGNOSTICS', env.XDT_WIRE_DIAGNOSTICS],
// 一次性 Grok strict tool spike(dev-only;必须与 wire probe 一起显式开启)。