Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(computer): 保留驱动错误并有界复核未知结果 (#4591)

Dash8380fe9e6fa0
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/computer-output.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/computer-output.test.ts
new file mode 100644
index 0000000000..6b71117912
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/computer-output.test.ts
@@ -0,0 +1,103 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { Server } from '@modelcontextprotocol/sdk/server/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import {
+ CallToolRequestSchema,
+ ListToolsRequestSchema,
+ type CallToolResult,
+} from '@modelcontextprotocol/sdk/types.js';
+import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
+import { callComputerToolWithOutputValidation } from '../computer-output.js';
+
+const outputSchema = {
+ type: 'object' as const,
+ properties: { windows: { type: 'array' as const } },
+ required: ['windows'],
+};
+const validator = new AjvJsonSchemaValidator().getValidator(outputSchema);
+const cleanup: Array<() => Promise<void>> = [];
+afterEach(async () => {
+ await Promise.all(cleanup.splice(0).map((close) => close()));
+});
+
+async function driver(result: CallToolResult) {
+ const server = new Server(
+ { name: 'driver-fixture', version: '1' },
+ { capabilities: { tools: {} } },
+ );
+ const client = new Client({ name: 'cindy-test', version: '1' });
+ const dispatch = vi.fn(() => result);
+ server.setRequestHandler(ListToolsRequestSchema, () => ({
+ tools: [{ name: 'list_windows', inputSchema: { type: 'object' }, outputSchema }],
+ }));
+ server.setRequestHandler(CallToolRequestSchema, dispatch);
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]);
+ cleanup.push(
+ () => client.close(),
+ () => server.close(),
+ );
+ await client.listTools();
+ return { client, dispatch };
+}
+
+describe('Computer Use driver output boundary (real MCP SDK)', () => {
+ const refusal: CallToolResult = {
+ isError: true,
+ content: [{ type: 'text', text: 'AX window could not be resolved' }],
+ structuredContent: { code: 'ax_window_unresolved', message: 'AX window could not be resolved' },
+ };
+
+ it('reproduces SDK masking of a structured error with a success schema', async () => {
+ const { client } = await driver(refusal);
+ await expect(client.callTool({ name: 'list_windows' })).rejects.toThrow(
+ 'Structured content does not match',
+ );
+ });
+
+ it('preserves the original error envelope with exactly one dispatch', async () => {
+ const { client, dispatch } = await driver(refusal);
+ await expect(
+ callComputerToolWithOutputValidation(client, { name: 'list_windows' }, validator, true),
+ ).resolves.toEqual(refusal);
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ });
+
+ it('still validates successful structured output', async () => {
+ const success = { content: [], structuredContent: { windows: [] } };
+ const { client, dispatch } = await driver(success);
+ await expect(
+ callComputerToolWithOutputValidation(client, { name: 'list_windows' }, validator, true),
+ ).resolves.toEqual(success);
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([true, false])(
+ 'rejects malformed success without replay (readOnly=%s)',
+ async (readOnly) => {
+ const { client, dispatch } = await driver({
+ content: [],
+ structuredContent: { unexpected: true },
+ });
+ await expect(
+ callComputerToolWithOutputValidation(client, { name: 'list_windows' }, validator, readOnly),
+ ).rejects.toMatchObject({
+ code: 'DRIVER_OUTPUT_SCHEMA_MISMATCH',
+ outcomeUnknown: !readOnly,
+ });
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('rejects missing success output without claiming an action failed to execute', async () => {
+ const { client, dispatch } = await driver({ content: [] });
+ await expect(
+ callComputerToolWithOutputValidation(client, { name: 'list_windows' }, validator, false),
+ ).rejects.toMatchObject({
+ code: 'DRIVER_OUTPUT_SCHEMA_MISMATCH',
+ outcomeUnknown: true,
+ });
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ });
+});
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 ee9940ffe4..016b88d734 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
@@ -4,6 +4,7 @@ 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';
+import { readForRecovery } from '../../../../../../packages/lizi-mcps/src/computer/recovery';
import { HumanDesktopInput, HUMAN_INPUT_QUIET_MS } from '../../remote-desktop/inputOwnership';
import * as inputOwnership from '../../remote-desktop/inputOwnership';
@@ -72,6 +73,8 @@ vi.mock('node:fs', async () => {
vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
Client: vi.fn().mockImplementation(() => ({
callTool: mcpCallToolMock,
+ request: (request: { params: unknown }, _schema: unknown, options: unknown) =>
+ mcpCallToolMock(request.params, undefined, options),
close: mcpCloseMock,
connect: mcpConnectMock,
listTools: mcpListToolsMock,
@@ -340,9 +343,16 @@ 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 } })) });
+ 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);
@@ -1308,6 +1318,185 @@ describe('computer mcp integration', () => {
expect(mcpCloseMock).toHaveBeenCalledTimes(1);
});
+ it('preserves a structured driver error after discovering output schemas', async () => {
+ mcpListToolsMock.mockResolvedValue({
+ tools: [
+ {
+ name: 'list_windows',
+ inputSchema: { type: 'object' },
+ outputSchema: { type: 'object', required: ['windows'] },
+ },
+ ],
+ });
+ mcpCallToolMock.mockResolvedValue({
+ isError: true,
+ content: [],
+ structuredContent: {
+ code: 'ax_window_unresolved',
+ message: 'Cannot resolve the target AX window',
+ },
+ });
+ await expect(
+ callComputerDriverTool('list_windows', {}, { sessionId: 'structured-error' }),
+ ).rejects.toMatchObject({
+ code: 'ax_window_unresolved',
+ message: 'Cannot resolve the target AX window',
+ });
+ expect(mcpCallToolMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('marks partial error delivery as unknown and never sends the next input chunk', async () => {
+ mcpCallToolMock.mockResolvedValue({
+ isError: true,
+ content: [{ type: 'text', text: 'type_text incomplete: delivered 12 of 13 characters' }],
+ structuredContent: { code: 'type_text_incomplete', effect: 'partial', delivered_chars: 12, requested_chars: 13 },
+ });
+ await expect(callComputerDriverTool('type_text', { pid: 1, window_id: 2, text: 'a'.repeat(850) }, { sessionId: 'partial-input-error' })).rejects.toMatchObject({
+ code: 'type_text_incomplete',
+ outcomeUnknown: true,
+ });
+ expect(mcpCallToolMock.mock.calls.filter(([request]) => request.name === 'type_text')).toHaveLength(1);
+ });
+
+ it('stops long input on malformed successful output and never sends the next chunk', async () => {
+ mcpListToolsMock.mockResolvedValue({
+ tools: [
+ {
+ name: 'type_text',
+ inputSchema: { type: 'object' },
+ outputSchema: { type: 'object', required: ['effect'] },
+ },
+ ],
+ });
+ mcpCallToolMock.mockResolvedValue({ content: [], structuredContent: { unexpected: true } });
+ await expect(
+ callComputerDriverTool(
+ 'type_text',
+ { pid: 1, window_id: 2, text: 'a'.repeat(850) },
+ { sessionId: 'malformed-input-result' },
+ ),
+ ).rejects.toMatchObject({
+ code: 'DRIVER_OUTPUT_SCHEMA_MISMATCH',
+ outcomeUnknown: true,
+ });
+ expect(mcpCallToolMock).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ ['darwin', undefined, 'foreground'],
+ ['darwin', 'background', 'background'],
+ ['darwin', 'foreground', 'foreground'],
+ ['win32', undefined, undefined],
+ ['linux', undefined, undefined],
+ ] as const)(
+ 'uses the platform drag default without overriding explicit mode: %s/%s',
+ async (platform, mode, expected) => {
+ setPlatform(platform);
+ mcpListToolsMock.mockResolvedValue({
+ tools: [
+ {
+ name: 'drag',
+ inputSchema: {
+ type: 'object',
+ properties: { delivery_mode: {} },
+ additionalProperties: true,
+ },
+ },
+ ],
+ });
+ mcpCallToolMock.mockResolvedValue({
+ content: [],
+ structuredContent: { effect: 'confirmed' },
+ });
+ const args = {
+ pid: 1,
+ window_id: 2,
+ from_x: 1,
+ from_y: 1,
+ to_x: 5,
+ to_y: 5,
+ ...(mode ? { delivery_mode: mode } : {}),
+ };
+ await callComputerDriverTool('drag', args, { sessionId: 'drag-default' });
+ const calls = mcpCallToolMock.mock.calls.filter(([call]) => call.name === 'drag');
+ expect(calls).toHaveLength(1);
+ expect(calls[0]![0].arguments.delivery_mode).toBe(expected);
+ expect(args).toEqual({
+ pid: 1,
+ window_id: 2,
+ from_x: 1,
+ from_y: 1,
+ to_x: 5,
+ to_y: 5,
+ ...(mode ? { delivery_mode: mode } : {}),
+ });
+ },
+ );
+
+ it('does not inject a delivery mode into a legacy driver that does not advertise it', async () => {
+ setPlatform('darwin');
+ const args = { pid: 1, window_id: 2, from_x: 1, from_y: 1, to_x: 5, to_y: 5 };
+ mcpListToolsMock.mockResolvedValue({
+ tools: [
+ {
+ name: 'drag',
+ inputSchema: {
+ type: 'object',
+ properties: Object.fromEntries(Object.keys(args).map((key) => [key, {}])),
+ additionalProperties: false,
+ },
+ },
+ ],
+ });
+ mcpCallToolMock.mockResolvedValue({ content: [], structuredContent: { effect: 'confirmed' } });
+ await callComputerDriverTool('drag', args, { sessionId: 'legacy-drag' });
+ expect(mcpCallToolMock).toHaveBeenCalledTimes(1);
+ expect(mcpCallToolMock.mock.calls[0]![0].arguments).toEqual(args);
+ });
+
+ it('preserves a named driver error stored in the error field', async () => {
+ mcpCallToolMock.mockResolvedValue({
+ isError: true,
+ content: [{ type: 'text', text: "No installed macOS app found for name 'Example'." }],
+ structuredContent: { error: 'APP_NOT_INSTALLED', name: 'Example' },
+ });
+ await expect(
+ callComputerDriverTool('launch_app', { name: 'Example' }, { sessionId: 'app-error-code' }),
+ ).rejects.toMatchObject({ code: 'APP_NOT_INSTALLED' });
+ expect(mcpCallToolMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not escalate or repeat an explicitly refused background drag', async () => {
+ setPlatform('darwin');
+ mcpCallToolMock.mockImplementation(async ({ name }) =>
+ name === 'drag'
+ ? {
+ isError: true,
+ content: [{ type: 'text', text: 'background unavailable' }],
+ structuredContent: { code: 'background_unavailable' },
+ }
+ : { content: [], structuredContent: { ok: true } },
+ );
+ await expect(
+ callComputerDriverTool(
+ 'drag',
+ {
+ pid: 1,
+ window_id: 2,
+ from_x: 1,
+ from_y: 1,
+ to_x: 5,
+ to_y: 5,
+ delivery_mode: 'background',
+ },
+ { sessionId: 'explicit-background' },
+ ),
+ ).rejects.toMatchObject({ code: 'background_unavailable' });
+ const calls = mcpCallToolMock.mock.calls.filter(([call]) => call.name === 'drag');
+ expect(calls).toHaveLength(1);
+ expect(calls[0]![0].arguments.delivery_mode).toBe('background');
+ });
+
it('chunks long type_text calls before sending them to cua-driver', async () => {
const longText = 'a'.repeat(850);
mcpCallToolMock
@@ -1513,6 +1702,104 @@ describe('computer mcp integration', () => {
} finally { human.release(); vi.useRealTimers(); }
});
+ it('keeps remote-input gating after real recovery reads until an explicit window observation', async () => {
+ vi.useFakeTimers();
+ const human = new HumanDesktopInput();
+ const context = { sessionId: 'joint-recovery' };
+ const target = { pid: 123, window_id: 7, include_screenshot: false };
+ try {
+ mcpCallToolMock.mockResolvedValue({ structuredContent: { elements: [], tree_markdown: 'window' } });
+ human.begin([{ kind: 'text', text: 'human' }]).complete();
+ vi.advanceTimersByTime(HUMAN_INPUT_QUIET_MS);
+ const recovery = await readForRecovery({ getStatus: vi.fn(), callTool: callComputerDriverTool }, 'get_window_state', target, context);
+ expect(recovery.ok).toBe(true);
+ await expect(callComputerDriverTool('click', { pid: 123, window_id: 7, x: 1, y: 1 }, context)).rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });
+ await expect(callComputerDriverTool('type_text', { pid: 123, text: 'agent' }, context)).rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });
+ expect(mcpCallToolMock.mock.calls.filter(([call]) => ['click', 'type_text'].includes(call.name))).toHaveLength(0);
+ expect(mcpCallToolMock.mock.calls.every(([call]) => !('observationPurpose' in call.arguments))).toBe(true);
+ await callComputerDriverTool('get_window_state', target, context);
+ await expect(callComputerDriverTool('click', { pid: 123, window_id: 7, x: 1, y: 1 }, context)).resolves.toBeDefined();
+ await expect(callComputerDriverTool('type_text', { pid: 123, text: 'agent' }, context)).resolves.toBeDefined();
+ } finally { human.release(); vi.useRealTimers(); }
+ });
+
+ it.each([
+ { include_screenshot: false, result: { degraded: true, degraded_reason: 'ax_window_unresolved', elements: [] } },
+ { include_screenshot: true, result: { screenshot_frame_valid: false, screenshot_error: 'capture unavailable', elements: [] } },
+ { include_screenshot: false, result: { ok: false, code: 'window_id_not_found' } },
+ ])('revokes previous input authorization when explicit observation fails: $result', async ({ include_screenshot, result }) => {
+ vi.useFakeTimers();
+ const human = new HumanDesktopInput();
+ const context = { sessionId: 'joint-failed-observation' };
+ const target = { pid: 123, window_id: 7, include_screenshot };
+ try {
+ human.begin([{ kind: 'text', text: 'human' }]).complete();
+ vi.advanceTimersByTime(HUMAN_INPUT_QUIET_MS);
+ mcpCallToolMock.mockResolvedValue({ structuredContent: { elements: [], screenshot_frame_valid: true } });
+ await callComputerDriverTool('get_window_state', target, context);
+ mcpCallToolMock.mockResolvedValue({ structuredContent: result });
+ await callComputerDriverTool('get_window_state', target, context);
+ await expect(callComputerDriverTool('click', { pid: 123, window_id: 7, x: 1, y: 1 }, context)).rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });
+ await expect(callComputerDriverTool('type_text', { pid: 123, text: 'agent' }, context)).rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });
+ } finally { human.release(); vi.useRealTimers(); }
+ });
+
+ it('does not authorize input from an observation interrupted by remote input', async () => {
+ vi.useFakeTimers();
+ const human = new HumanDesktopInput();
+ const context = { sessionId: 'joint-interrupted-observation' };
+ const target = { pid: 123, window_id: 7, include_screenshot: false };
+ const pending = createDeferred<unknown>();
+ try {
+ mcpCallToolMock.mockImplementation(({ name }) => name === 'get_window_state' ? pending.promise : { structuredContent: { ok: true } });
+ const read = callComputerDriverTool('get_window_state', target, context);
+ await vi.waitFor(() => expect(mcpCallToolMock.mock.calls.some(([call]) => call.name === 'get_window_state')).toBe(true));
+ human.begin([{ kind: 'text', text: 'human' }]).complete();
+ vi.advanceTimersByTime(HUMAN_INPUT_QUIET_MS);
+ pending.resolve({ structuredContent: { elements: [], tree_markdown: 'window' } });
+ await read;
+ await expect(callComputerDriverTool('click', { pid: 123, window_id: 7, x: 1, y: 1 }, context)).rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });
+ await callComputerDriverTool('get_window_state', target, context);
+ await expect(callComputerDriverTool('click', { pid: 123, window_id: 7, x: 1, y: 1 }, context)).resolves.toBeDefined();
+ } finally { human.release(); vi.useRealTimers(); }
+ });
+
+ it.each([
+ { newerWindow: 7, cancel: false },
+ { newerWindow: 7, cancel: true },
+ { newerWindow: 8, cancel: false },
+ { newerWindow: 8, cancel: true },
+ ])('does not let a late observation undo newer failure: $newerWindow, cancelled=$cancel', async ({ newerWindow, cancel }) => {
+ vi.useFakeTimers();
+ const human = new HumanDesktopInput();
+ const context = { sessionId: 'joint-concurrent-observation' };
+ const target = { pid: 123, window_id: 7, include_screenshot: false };
+ const pending = createDeferred<unknown>();
+ try {
+ human.begin([{ kind: 'text', text: 'human' }]).complete();
+ vi.advanceTimersByTime(HUMAN_INPUT_QUIET_MS);
+ mcpCallToolMock.mockImplementation(({ name }) => name === 'get_window_state' ? pending.promise : { structuredContent: { ok: true } });
+ const older = callComputerDriverTool('get_window_state', target, context);
+ await vi.waitFor(() => expect(mcpCallToolMock.mock.calls.some(([call]) => call.name === 'get_window_state')).toBe(true));
+ mcpCallToolMock.mockResolvedValue({ structuredContent: { ok: false, code: 'window_id_not_found' } });
+ const controller = new AbortController();
+ if (cancel) controller.abort();
+ const newer = callComputerDriverTool('get_window_state', { ...target, window_id: newerWindow }, { ...context, signal: controller.signal });
+ if (cancel) await expect(newer).rejects.toBeDefined();
+ else await newer;
+ pending.resolve({ structuredContent: { elements: [], tree_markdown: 'window' } });
+ await older;
+ await expect(callComputerDriverTool('type_text', { pid: 123, text: 'agent' }, context)).rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });
+ await expect(callComputerDriverTool('click', { pid: 123, window_id: newerWindow, x: 1, y: 1 }, context)).rejects.toMatchObject({ code: 'STALE_SNAPSHOT' });
+ mcpCallToolMock.mockResolvedValue({ structuredContent: { elements: [], tree_markdown: 'window' } });
+ if (newerWindow !== 7) {
+ await expect(callComputerDriverTool('click', { pid: 123, window_id: 7, x: 1, y: 1 }, context)).resolves.toBeDefined();
+ }
+ await callComputerDriverTool('get_window_state', { ...target, window_id: newerWindow }, context);
+ await expect(callComputerDriverTool('type_text', { pid: 123, text: 'agent' }, context)).resolves.toBeDefined();
+ } finally { human.release(); vi.useRealTimers(); }
+ });
+
it('bounds delayed typing chunks while a remote input connection is open', async () => {
const human = new HumanDesktopInput();
try {
diff --git a/apps/desktop/src/main/mcp-integrations/computer-output.ts b/apps/desktop/src/main/mcp-integrations/computer-output.ts
new file mode 100644
index 0000000000..ac6a5fc0fa
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/computer-output.ts
@@ -0,0 +1,45 @@
+import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { CallToolResultSchema, type CallToolRequest } from '@modelcontextprotocol/sdk/types.js';
+import type { JsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/index.js';
+
+export class ComputerOutputSchemaError extends Error {
+ readonly code = 'DRIVER_OUTPUT_SCHEMA_MISMATCH';
+ constructor(
+ message: string,
+ readonly outcomeUnknown: boolean,
+ ) {
+ super(message);
+ this.name = 'ComputerOutputSchemaError';
+ }
+}
+
+/** Preserve explicit driver errors; validate successful results exactly once, without replay. */
+export async function callComputerToolWithOutputValidation(
+ client: Client,
+ params: CallToolRequest['params'],
+ validator: JsonSchemaValidator<unknown> | undefined,
+ readOnly: boolean,
+ signal?: AbortSignal,
+) {
+ if (!validator) return client.callTool(params, undefined, { signal });
+ // SDK callTool validates structured error payloads against the success schema,
+ // unlike its server implementation. Request still validates the MCP envelope.
+ const result = await client.request({ method: 'tools/call', params }, CallToolResultSchema, {
+ signal,
+ });
+ if (result.isError) return result;
+ if (!result.structuredContent) {
+ throw new ComputerOutputSchemaError(
+ `Tool ${params.name} has an output schema but did not return structured content`,
+ !readOnly,
+ );
+ }
+ const validation = validator(result.structuredContent);
+ if (!validation.valid) {
+ throw new ComputerOutputSchemaError(
+ `Structured content does not match the tool's output schema: ${validation.errorMessage}`,
+ !readOnly,
+ );
+ }
+ return result;
+}
diff --git a/apps/desktop/src/main/mcp-integrations/computer.ts b/apps/desktop/src/main/mcp-integrations/computer.ts
index ad5727be2d..2d3dea9a24 100644
--- a/apps/desktop/src/main/mcp-integrations/computer.ts
+++ b/apps/desktop/src/main/mcp-integrations/computer.ts
@@ -10,6 +10,8 @@ import { hasProxyEnvConfig, parseOutboundProxyUrl } from '@cindy/anthropic-compa
import { BRAND_NAME } from '@cindy/maker-shared/branding';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
+import type { JsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/index.js';
import type {
ComputerMcpCallContext,
ComputerDriverPermissionGrant,
@@ -24,6 +26,7 @@ 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, isUnavailableWindowObservation } from '@cindy/mcps/computer';
+import { callComputerToolWithOutputValidation } from './computer-output.js';
const logger = createLogger('mcp/cindy_computer');
const DRIVER_COMMAND = 'cua-driver';
@@ -288,6 +291,7 @@ interface CuaMcpSessionEntry {
ready: Promise<void>;
driverSessionId: string;
toolSchemas: Map<string, ComputerDriverToolSchema>;
+ outputValidators: Map<string, JsonSchemaValidator<unknown>>;
cursorSetup: {
motion: CursorSetupState;
style: CursorSetupState;
@@ -2123,19 +2127,31 @@ function createCuaMcpSession(sessionId: string): CuaMcpSessionEntry {
transport,
driverSessionId: getDriverSessionId(sessionId),
toolSchemas: new Map(),
+ outputValidators: new Map(),
cursorSetup: {
motion: capabilities?.motion === 'unavailable' ? 'unavailable' : 'pending',
style: capabilities?.style === 'unavailable' ? 'unavailable' : 'pending',
},
ready: withTimeout(
client.connect(transport).then(async () => {
+ const outputValidator = new AjvJsonSchemaValidator();
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);
+ for (const tool of page.tools) {
+ entry.toolSchemas.set(tool.name, tool.inputSchema as ComputerDriverToolSchema);
+ // Required-task tools must stay on SDK callTool's task protocol guard.
+ if (tool.outputSchema && tool.execution?.taskSupport !== 'required') {
+ entry.outputValidators.set(
+ tool.name,
+ outputValidator.getValidator(tool.outputSchema),
+ );
+ }
+ }
cursor = page.nextCursor;
- if (cursor && (seen.has(cursor) || seen.size >= 20)) throw new ComputerDriverError('Driver tools/list pagination did not terminate.');
+ 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);
}),
@@ -2207,20 +2223,47 @@ async function callCuaMcpTool(
signal?: AbortSignal,
): Promise<unknown> {
signal?.throwIfAborted();
+ if (
+ name === 'drag' &&
+ process.platform === 'darwin' &&
+ args.delivery_mode === undefined &&
+ Object.hasOwn(entry.toolSchemas.get(name)?.properties ?? {}, 'delivery_mode')
+ ) {
+ // Older drivers may not accept delivery_mode at all; adapt only advertised capabilities.
+ args = { ...args, delivery_mode: 'foreground' };
+ }
const driverArgs = adaptComputerDriverArgs(name, args, entry.toolSchemas);
const result = await withTimeout(
- entry.client.callTool({
- name,
- arguments: driverArgs,
- }, undefined, { signal }),
+ callComputerToolWithOutputValidation(
+ entry.client,
+ {
+ name,
+ arguments: driverArgs,
+ },
+ entry.outputValidators.get(name),
+ getComputerTool(name)?.readOnly === true,
+ signal,
+ ),
timeoutMs,
`cua-driver mcp tool ${name}`,
);
if ((result as { isError?: unknown }).isError) {
const text = firstTextFromMcpResult(result);
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');
+ throw new ComputerDriverError(
+ typeof details?.message === 'string'
+ ? details.message
+ : (text ?? `cua-driver mcp tool ${name} returned an error`),
+ typeof details?.code === 'string'
+ ? details.code
+ : typeof details?.error === 'string' && /^[A-Z][A-Z0-9_]+$/.test(details.error)
+ ? details.error
+ : 'COMPUTER_DRIVER_ERROR',
+ getComputerTool(name)?.readOnly !== true && (
+ details?.effect === 'partial' || details?.effect === 'unverifiable' ||
+ details?.code === 'type_text_incomplete'
+ ),
+ );
}
const parsed = parseMcpToolResult(result);
if (typeof parsed === 'string' && STALE_CUA_SESSION_MARKER_RE.test(parsed)) {
@@ -3379,7 +3422,7 @@ export async function grantComputerDriverPermissions(
// Remote input invalidates previously observed targets even after its short
// ownership window ends. Never resume typing into a stale focus implicitly.
-const inputObservations = new Map<string, { windows: Map<string, number> }>();
+const inputObservations = new Map<string, { windows: Map<string, number | symbol> }>();
export async function callComputerDriverTool(
name: ComputerMcpToolName,
@@ -3396,14 +3439,23 @@ export async function callComputerDriverTool(
const window = `${args.pid}:${args.window_id}`;
if (getComputerTool(name)?.readOnly === true) {
const startedIdle = !isHumanDesktopInputActive();
+ const explicitObservation = name === 'get_window_state' && context?.observationPurpose !== 'recovery';
+ const observation = Symbol('pending observation');
+ const app = `${args.pid}:undefined`;
+ if (explicitObservation) {
+ // Revoke old permission and prevent an older concurrent read from
+ // restoring it after this read fails or is cancelled.
+ observations?.windows.set(window, observation);
+ observations?.windows.set(app, observation);
+ }
const result = await callComputerDriverToolImpl(name, args, context);
- if (name === 'get_window_state' && startedIdle && computerResultOutcome(name, result).ok
- && !isUnavailableWindowObservation(result, args)
+ if (explicitObservation && startedIdle && !context?.signal?.aborted
+ && !isUnavailableWindowObservation(result, args) && computerResultOutcome(name, result).ok
&& revision === desktopInputRevision() && !isHumanDesktopInputActive()) {
- observations?.windows.set(window, revision);
+ if (observations?.windows.get(window) === observation) observations.windows.set(window, revision);
// App-scoped actions may omit window_id; a successful observation of
// that app also refreshes its focus, without refreshing other windows.
- observations?.windows.set(`${args.pid}:undefined`, revision);
+ if (observations?.windows.get(app) === observation) observations.windows.set(app, revision);
}
return result;
}
diff --git a/apps/desktop/src/main/smoke/COMPUTER_USE.md b/apps/desktop/src/main/smoke/COMPUTER_USE.md
index 0b8c2cec72..bec61af78d 100644
--- a/apps/desktop/src/main/smoke/COMPUTER_USE.md
+++ b/apps/desktop/src/main/smoke/COMPUTER_USE.md
@@ -15,10 +15,15 @@ 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
+element credentials, sets long 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.
+After automatic postchecks it explicitly refreshes element credentials. It also
+checks native Chinese/emoji typing with a bounded postcondition, macOS default
+drag selection, missing-app discovery without launching another app, and closed
+window rediscovery without silently selecting a replacement. Installed-bundle
+and already-running-app fallback success remain covered by unit regressions.
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.
diff --git a/apps/desktop/src/main/smoke/computerUseSmoke.ts b/apps/desktop/src/main/smoke/computerUseSmoke.ts
index 07ba83bc56..ecb8431cb6 100644
--- a/apps/desktop/src/main/smoke/computerUseSmoke.ts
+++ b/apps/desktop/src/main/smoke/computerUseSmoke.ts
@@ -186,22 +186,37 @@ export async function runComputerUseSmokeIfRequested(): Promise<void> {
const input = elements?.find(
(item) => item.role === 'AXTextArea' && item.label === 'Smoke message',
);
- const button = elements?.find(
+ let 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 value = 'Cindy smoke 中文🙂\n第二行 123\n'.repeat(30);
const set = await call('set_value', {
...targetArgs,
element_token: input!.element_token,
value,
});
check(set.ok, 'set_value dispatched successfully');
+ if (set.outcome?.status === 'unknown') {
+ check(
+ set.postcheck?.tool === 'get_window_state',
+ 'unknown input receives one state postcheck',
+ );
+ check(set.postcheck?.reusable_snapshot === false, 'automatic observation is evidence only');
+ }
check(
(await window.webContents.executeJavaScript('document.getElementById("message").value')) ===
value,
'independent DOM confirms exact input',
);
+ // An unknown input now triggers a bounded observation and invalidates the
+ // previous credentials. Obtain an explicit fresh snapshot before clicking.
+ state = await call('get_window_state', { ...targetArgs, include_screenshot: false });
+ button = state.data?.elements?.find(
+ (item: { role?: string; label?: string }) =>
+ item.role === 'AXButton' && item.label === 'Increment smoke count',
+ );
+ check(state.ok && button?.element_token, 'fresh button token obtained after input');
const click = await call('click', {
...targetArgs,
element_token: button!.element_token,
@@ -273,6 +288,105 @@ export async function runComputerUseSmokeIfRequested(): Promise<void> {
)) === '1',
'cancelled action leaves fixture unchanged',
);
+ await window.webContents.executeJavaScript('document.getElementById("message").value = ""');
+ state = await call('get_window_state', { ...targetArgs, include_screenshot: false });
+ const freshInput = state.data?.elements?.find(
+ (item: { role?: string; label?: string }) =>
+ item.role === 'AXTextArea' && item.label === 'Smoke message',
+ );
+ check(freshInput?.element_token, 'fresh input token available for native typing');
+ const typedValue = '原生输入测试🙂\n第二行内容';
+ const typed = await call('type_text', {
+ ...targetArgs,
+ element_token: freshInput.element_token,
+ text: typedValue,
+ delivery_mode: 'foreground',
+ postcondition: [
+ {
+ element: {
+ selector: { role: 'AXTextArea', label_contains: 'Smoke message' },
+ value_equals: typedValue,
+ },
+ },
+ ],
+ });
+ const actualTypedValue = await window.webContents.executeJavaScript(
+ 'document.getElementById("message").value',
+ );
+ const nativeTypingPassed =
+ typed.postcheck?.tool === 'verify_state' &&
+ typed.outcome?.status === 'unknown' &&
+ actualTypedValue === typedValue;
+ report.nativeTyping = {
+ errorCode: typed.errorCode,
+ message: typed.data?.message,
+ expected: typedValue,
+ actual: actualTypedValue,
+ passed: nativeTypingPassed,
+ postcheckTool: typed.postcheck?.tool,
+ outcomeUnknown: typed.data?.outcome_unknown,
+ };
+ // Retain the failed input verdict while completing independent recovery cases.
+ if (nativeTypingPassed)
+ checks.push('bounded postcheck and independent DOM confirm multilingual native typing');
+ let dragPassed = true;
+ if (process.platform === 'darwin') {
+ // Fixture setup only; the selection itself must be produced by real drag.
+ const rect = await window.webContents.executeJavaScript(
+ '(()=>{const e=document.getElementById("message");e.value="abcdefghijklmno";e.setSelectionRange(0,0);const r=e.getBoundingClientRect();return {x:r.x,y:r.y}})()',
+ );
+ await call('get_window_state', { ...targetArgs, include_screenshot: false });
+ const bounds = window.getBounds();
+ const content = window.getContentBounds();
+ const fromX = content.x - bounds.x + rect.x + 4;
+ const fromY = content.y - bounds.y + rect.y + 10;
+ const drag = await call('drag', {
+ ...targetArgs,
+ from_x: fromX,
+ from_y: fromY,
+ to_x: fromX + 70,
+ to_y: fromY,
+ duration_ms: 400,
+ });
+ check(
+ drag.ok && drag.data?.effect !== 'refused',
+ 'macOS default drag is not refused as background input',
+ );
+ dragPassed = await window.webContents.executeJavaScript(
+ '(()=>{const e=document.getElementById("message");return e.selectionEnd>e.selectionStart})()',
+ );
+ report.drag = { passed: dragPassed, effect: drag.data?.effect, outcome: drag.outcome };
+ if (dragPassed) checks.push('independent DOM confirms drag selection');
+ }
+ // Exercise safe, real driver failure recovery without launching an unrelated app.
+ const missingApp = await call('launch_app', { name: `Cindy Smoke Missing ${sessionId}` });
+ check(
+ !missingApp.ok && missingApp.errorCode === 'APP_NOT_INSTALLED',
+ 'original app resolution error preserved',
+ );
+ check(
+ missingApp.recovery?.target_selected === false,
+ 'unresolved app discovery never selects another app',
+ );
+ check(
+ missingApp.recovery?.installed_discovery?.tool === 'list_apps',
+ 'failed app name receives installed-app discovery',
+ );
+ window.destroy();
+ const missingWindow = await call('get_window_state', {
+ ...targetArgs,
+ include_screenshot: false,
+ });
+ check(
+ !missingWindow.ok && missingWindow.recovery?.target_selected === false,
+ 'closed window is not silently retargeted',
+ );
+ check(
+ missingWindow.recovery?.discovery?.tool === 'list_windows',
+ 'closed window receives fresh discovery',
+ );
+ check(nativeTypingPassed, 'native typing must pass before accepting the smoke');
+ check(dragPassed, 'drag selection must pass before accepting the smoke');
report.ok = true;
delete report.lastResult;
delete report.observation;
diff --git a/docs/remote-desktop.md b/docs/remote-desktop.md
index 30f62208c7..1d47a30216 100644
--- a/docs/remote-desktop.md
+++ b/docs/remote-desktop.md
@@ -341,7 +341,10 @@ the Agent must successfully observe the target window again with input idle at
both the start and end of the read and no input revision change during the read
before acting on it, including the first action of a new or cleaned-up driver
session. Actions without a window ID accept an observation of the same process;
-an explicit window ID still requires that exact window. Empty connection
+an explicit window ID still requires that exact window. Automatic recovery reads
+are text-only evidence, do not capture screenshots, and do not restore input permission. Failed or cancelled explicit
+reads revoke prior permission, and older concurrent reads cannot restore it.
+Empty connection
heartbeats do not claim input ownership.
The native macOS/Windows helper acknowledges a batch only after posting all its
diff --git a/packages/lizi-mcps/src/computer/recovery.test.ts b/packages/lizi-mcps/src/computer/recovery.test.ts
new file mode 100644
index 0000000000..6c6273a406
--- /dev/null
+++ b/packages/lizi-mcps/src/computer/recovery.test.ts
@@ -0,0 +1,504 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
+import { createComputerMcpServer } from "./server.js";
+import { readForRecovery } from "./recovery.js";
+import type { ComputerMcpDeps } from "../types.js";
+
+const cleanups: Array<() => Promise<void>> = [];
+afterEach(async () => {
+ vi.useRealTimers();
+ await Promise.all(cleanups.splice(0).map((close) => close()));
+});
+
+async function harness(dispatch: ComputerMcpDeps["callTool"]) {
+ const server = createComputerMcpServer(
+ { getStatus: vi.fn(), callTool: dispatch },
+ { sessionId: "recovery-test" },
+ );
+ const client = new Client({ name: "recovery-test", version: "1" });
+ const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
+ await Promise.all([server.connect(serverTx), client.connect(clientTx)]);
+ cleanups.push(
+ () => client.close(),
+ () => server.close(),
+ );
+ return async (name: string, args: Record<string, unknown>) => {
+ const result = await client.callTool({
+ name: "call_tool",
+ arguments: { name, args },
+ });
+ return JSON.parse((result.content as Array<{ text: string }>)[0]!.text);
+ };
+}
+
+describe("bounded Computer Use recovery", () => {
+ it("observes unknown input exactly once, preserving uncertainty and session provenance", async () => {
+ const raw = { effect: "unverifiable", remaining_chars: 450 };
+ const dispatch = vi.fn(async (name: string) =>
+ name === "type_text"
+ ? raw
+ : { elements: [], snapshot_id: "fresh-native" },
+ );
+ const call = await harness(dispatch);
+ const result = await call("type_text", {
+ pid: 1,
+ window_id: 2,
+ text: "hello",
+ });
+ expect(result).toMatchObject({
+ ok: true,
+ outcome: { status: "unknown" },
+ data: raw,
+ postcheck: {
+ tool: "get_window_state",
+ ok: true,
+ reusable_snapshot: false,
+ },
+ });
+ expect(dispatch.mock.calls.map(([name]) => name)).toEqual([
+ "type_text",
+ "get_window_state",
+ ]);
+ expect(dispatch).toHaveBeenLastCalledWith(
+ "get_window_state",
+ {
+ pid: 1,
+ window_id: 2,
+ session: "recovery-test",
+ include_screenshot: false,
+ },
+ expect.objectContaining({
+ sessionId: "recovery-test",
+ observationPurpose: "recovery",
+ signal: expect.any(AbortSignal),
+ }),
+ );
+ });
+
+ it.each([false, true])("does not capture recovery screenshots or accept degraded text evidence (thrown=%s)", async (thrown) => {
+ const dispatch = vi.fn(async (name: string) => {
+ if (name === "click") {
+ if (thrown) throw Object.assign(new Error("unknown delivery"), { outcomeUnknown: true });
+ return { effect: "unverifiable" };
+ }
+ return { degraded: true, elements: [], tree_markdown: "" };
+ });
+ const call = await harness(dispatch);
+ const result = await call("click", { pid: 1, window_id: 2, x: 2, y: 3 });
+ expect(result.postcheck).toMatchObject({ tool: "get_window_state", ok: false });
+ if (thrown) expect(result.data.outcome_unknown).toBe(true);
+ else expect(result.outcome.status).toBe("unknown");
+ expect(dispatch).toHaveBeenLastCalledWith(
+ "get_window_state",
+ { pid: 1, window_id: 2, session: "recovery-test", include_screenshot: false },
+ expect.objectContaining({ observationPurpose: "recovery" }),
+ );
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not let a late automatic observation supersede a newer explicit snapshot", async () => {
+ let reads = 0;
+ let clicks = 0;
+ let finish!: (value: unknown) => void;
+ let began!: () => void;
+ const started = new Promise<void>((resolve) => {
+ began = resolve;
+ });
+ const call = await harness(async (name) => {
+ if (name === "click")
+ return { effect: ++clicks === 1 ? "unverifiable" : "confirmed" };
+ if (++reads === 2) {
+ began();
+ return new Promise((resolve) => {
+ finish = resolve;
+ });
+ }
+ return { snapshot_id: `native-${reads}`, elements: [] };
+ });
+ const first = await call("get_window_state", { pid: 1, window_id: 2 });
+ const pending = call("click", {
+ pid: 1,
+ element_index: 0,
+ snapshot_id: first.snapshot_id,
+ });
+ await started;
+ const fresh = await call("get_window_state", { pid: 1, window_id: 2 });
+ finish({ snapshot_id: "late-auto", elements: [] });
+ expect(await pending).toMatchObject({
+ postcheck: { reusable_snapshot: false },
+ });
+ expect(
+ await call("click", {
+ pid: 1,
+ element_index: 0,
+ snapshot_id: fresh.snapshot_id,
+ }),
+ ).toMatchObject({ ok: true });
+ expect(
+ await call("click", {
+ pid: 1,
+ element_index: 0,
+ snapshot_id: first.snapshot_id,
+ }),
+ ).toMatchObject({ errorCode: "STALE_SNAPSHOT" });
+ });
+
+ it.each(["satisfied", "unsatisfied"])(
+ "checks an explicit postcondition: %s",
+ async (status) => {
+ const dispatch = vi.fn(async (name: string) =>
+ name === "verify_state" ? { status } : { effect: "unverifiable" },
+ );
+ const call = await harness(dispatch);
+ const postcondition = [
+ {
+ element: {
+ selector: { role: "AXTextField", label_contains: "Name" },
+ value_equals: "hello",
+ },
+ },
+ ];
+ const result = await call("type_text", {
+ pid: 1,
+ window_id: 2,
+ text: "hello",
+ postcondition,
+ });
+ expect(result.ok).toBe(status === "satisfied");
+ expect(result.outcome.status === "confirmed").toBe(
+ status === "satisfied",
+ );
+ expect(result.data).toEqual({ effect: "unverifiable" });
+ expect(dispatch).toHaveBeenNthCalledWith(
+ 1,
+ "type_text",
+ { pid: 1, window_id: 2, text: "hello", session: "recovery-test" },
+ expect.anything(),
+ );
+ expect(dispatch).toHaveBeenLastCalledWith(
+ "verify_state",
+ expect.objectContaining({
+ expect: postcondition,
+ timeout_ms: 1500,
+ stable_samples: 2,
+ }),
+ expect.anything(),
+ );
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ it("does not confirm incomplete chunked input even when a weak postcondition matches", async () => {
+ const call = await harness(async (name) =>
+ name === "verify_state"
+ ? { status: "satisfied" }
+ : { effect: "unverifiable", remaining_chars: 400 },
+ );
+ expect(
+ await call("type_text", {
+ pid: 1,
+ window_id: 2,
+ text: "hello",
+ postcondition: [{ window: { exists: true } }],
+ }),
+ ).toMatchObject({
+ outcome: { status: "unknown" },
+ data: { remaining_chars: 400 },
+ });
+ });
+
+ it("rejects unverifiable target/predicate arguments before dispatch", async () => {
+ const dispatch = vi.fn();
+ const call = await harness(dispatch);
+ expect(
+ await call("click", {
+ pid: 1,
+ x: 2,
+ y: 3,
+ postcondition: [{ window: { exists: true } }],
+ }),
+ ).toMatchObject({ errorCode: "INVALID_ARGS" });
+ expect(
+ await call("click", {
+ pid: 1,
+ window_id: 2,
+ x: 2,
+ y: 3,
+ postcondition: [],
+ }),
+ ).toMatchObject({ ok: false });
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it("keeps the original action error if the read-only postcheck fails", async () => {
+ const dispatch = vi.fn(async (name: string) => {
+ if (name === "click")
+ throw Object.assign(new Error("Malformed driver success"), {
+ code: "DRIVER_OUTPUT_SCHEMA_MISMATCH",
+ outcomeUnknown: true,
+ });
+ throw new Error("Capture failed");
+ });
+ const call = await harness(dispatch);
+ expect(
+ await call("click", { pid: 1, window_id: 2, x: 2, y: 3 }),
+ ).toMatchObject({
+ ok: false,
+ errorCode: "DRIVER_OUTPUT_SCHEMA_MISMATCH",
+ data: { message: "Malformed driver success", outcome_unknown: true },
+ postcheck: { ok: false, error: { message: "Capture failed" } },
+ });
+ expect(dispatch.mock.calls.map(([name]) => name)).toEqual([
+ "click",
+ "get_window_state",
+ ]);
+ });
+
+ it("discovers replacement PID/window candidates without selecting or clicking one", async () => {
+ const windows = [{ pid: 99, window_id: 100, app_name: "Cindy" }];
+ const dispatch = vi.fn(async (name: string) => {
+ if (name === "list_windows") return { windows };
+ throw Object.assign(new Error("gone"), { code: "window_id_not_found" });
+ });
+ const call = await harness(dispatch);
+ expect(
+ await call("click", { pid: 1, window_id: 2, x: 2, y: 3 }),
+ ).toMatchObject({
+ ok: false,
+ recovery: {
+ target_selected: false,
+ requested_target: { pid: 1, window_id: 2 },
+ discovery: { data: { windows } },
+ },
+ });
+ expect(dispatch.mock.calls.map(([name]) => name)).toEqual([
+ "click",
+ "list_windows",
+ ]);
+ expect(dispatch).toHaveBeenLastCalledWith(
+ "list_windows",
+ { session: "recovery-test" },
+ expect.anything(),
+ );
+ });
+
+ it.each([1, 2])(
+ "locates only an unambiguous running app (%s matching processes)",
+ async (processes) => {
+ const windows = Array.from({ length: processes }, (_, i) => ({
+ pid: i + 1,
+ window_id: i,
+ app_name: "Simulator",
+ }));
+ const dispatch = vi.fn(async (name: string) => {
+ if (name === "list_apps") return { apps: [] };
+ if (name === "list_windows") return { windows };
+ throw new Error('No installed macOS app found for name "Simulator"');
+ });
+ const call = await harness(dispatch);
+ const result = await call("launch_app", { name: "Simulator" });
+ expect(result.ok).toBe(processes === 1);
+ if (processes === 1)
+ expect(result.data).toMatchObject({
+ located: true,
+ launched: false,
+ pid: 1,
+ });
+ expect(dispatch.mock.calls.map(([name]) => name)).toEqual([
+ "launch_app",
+ "list_apps",
+ "list_windows",
+ ]);
+ },
+ );
+
+ it.each([
+ { urls: ["https://example.test"] },
+ { creates_new_application_instance: true },
+ { additional_arguments: ["--flag"] },
+ { bundle_id: "example.app" },
+ { webkit_inspector_port: 1234 },
+ ])(
+ "does not substitute locating for launch side effects: %j",
+ async (extra) => {
+ const dispatch = vi.fn(async (name: string) => {
+ if (name === "list_apps") return { apps: [] };
+ throw new Error('No installed macOS app found for name "Simulator"');
+ });
+ const call = await harness(dispatch);
+ expect(
+ await call("launch_app", { name: "Simulator", ...extra }),
+ ).toMatchObject({ ok: false });
+ expect(dispatch.mock.calls.map(([name]) => name)).toEqual(
+ "bundle_id" in extra ? ["launch_app"] : ["launch_app", "list_apps"],
+ );
+ },
+ );
+
+ it("resolves a unique installed bundle once while preserving all launch intent", async () => {
+ const dispatch = vi.fn<ComputerMcpDeps["callTool"]>(async (name, args) => {
+ if (name === "list_apps")
+ return { apps: [{ name: "Example", bundle_id: "com.example.app" }] };
+ if (args.bundle_id) return { pid: 12, launched: true };
+ throw Object.assign(
+ new Error('No installed macOS app found for name "Example"'),
+ { code: "APP_NOT_INSTALLED" },
+ );
+ });
+ const call = await harness(dispatch);
+ const args = {
+ name: "Example",
+ urls: ["https://example.test"],
+ additional_arguments: ["--flag"],
+ creates_new_application_instance: true,
+ };
+ expect(await call("launch_app", args)).toMatchObject({
+ ok: true,
+ data: { pid: 12, launched: true },
+ recovery: { resolved_bundle_id: "com.example.app" },
+ });
+ expect(dispatch.mock.calls.map(([name]) => name)).toEqual([
+ "launch_app",
+ "list_apps",
+ "launch_app",
+ ]);
+ expect(dispatch).toHaveBeenLastCalledWith(
+ "launch_app",
+ { ...args, bundle_id: "com.example.app" },
+ expect.objectContaining({ sessionId: "recovery-test" }),
+ );
+ });
+
+ it("does not guess among duplicate installed names or missing bundle IDs", async () => {
+ for (const apps of [
+ [{ name: "Example" }],
+ [
+ { name: "Example", bundle_id: "one" },
+ { name: "Example", bundle_id: "two" },
+ ],
+ ]) {
+ const dispatch = vi.fn(async (name: string) => {
+ if (name === "list_apps") return { apps };
+ if (name === "list_windows") return { windows: [] };
+ throw new Error('No installed macOS app found for name "Example"');
+ });
+ expect(
+ await (
+ await harness(dispatch)
+ )("launch_app", { name: "Example" }),
+ ).toMatchObject({ ok: false });
+ expect(dispatch.mock.calls.map(([name]) => name)).toEqual([
+ "launch_app",
+ "list_apps",
+ "list_windows",
+ ]);
+ }
+ });
+
+ it("stops after one resolved-bundle launch attempt, even on another resolution error", async () => {
+ const dispatch = vi.fn(async (name: string) => {
+ if (name === "list_apps")
+ return { apps: [{ name: "Example", bundle_id: "com.example.app" }] };
+ throw new Error('No installed macOS app found for name "Example"');
+ });
+ expect(
+ await (
+ await harness(dispatch)
+ )("launch_app", { name: "Example" }),
+ ).toMatchObject({ ok: false, recovery: { retry_exhausted: true } });
+ expect(dispatch.mock.calls.map(([name]) => name)).toEqual([
+ "launch_app",
+ "list_apps",
+ "launch_app",
+ ]);
+ });
+
+ it("does not create recovery traffic after the host has closed an action session", async () => {
+ const dispatch = vi.fn(async () => {
+ throw Object.assign(new Error("Closed"), {
+ code: "REQUEST_CANCELLED",
+ outcomeUnknown: true,
+ });
+ });
+ const call = await harness(dispatch);
+ expect(
+ await call("click", { pid: 1, window_id: 2, x: 2, y: 3 }),
+ ).toMatchObject({ errorCode: "REQUEST_CANCELLED" });
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not treat a similar name or a generic launch error as successful discovery", async () => {
+ const call = await harness(async (name) => {
+ if (name === "list_windows")
+ return { windows: [{ pid: 1, app_name: "Simulator Helper" }] };
+ throw new Error('No installed macOS app found for name "Simulator"');
+ });
+ expect(await call("launch_app", { name: "Simulator" })).toMatchObject({
+ ok: false,
+ });
+ const dispatch = vi.fn(async () => {
+ throw new Error("transport closed");
+ });
+ expect(
+ await (
+ await harness(dispatch)
+ )("launch_app", { name: "Simulator" }),
+ ).toMatchObject({ ok: false });
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ });
+
+ it("bounds a stalled read and cancels the underlying request without retry", async () => {
+ vi.useFakeTimers();
+ const dispatch = vi.fn<ComputerMcpDeps["callTool"]>(
+ () => new Promise(() => {}),
+ );
+ const pending = readForRecovery(
+ { getStatus: vi.fn(), callTool: dispatch },
+ "list_windows",
+ {},
+ {},
+ 20,
+ );
+ await vi.advanceTimersByTimeAsync(20);
+ expect(await pending).toMatchObject({
+ ok: false,
+ error: { code: "RECOVERY_TIMEOUT" },
+ });
+ expect(dispatch.mock.calls[0]![2]!.signal!.aborted).toBe(true);
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ });
+
+ it("honors cancellation before and during recovery and ignores late responses", async () => {
+ const controller = new AbortController();
+ let finish!: (data: unknown) => void;
+ const dispatch = vi.fn<ComputerMcpDeps["callTool"]>(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const deps = { getStatus: vi.fn(), callTool: dispatch };
+ const pending = readForRecovery(
+ deps,
+ "list_windows",
+ {},
+ { signal: controller.signal },
+ );
+ controller.abort();
+ expect(await pending).toMatchObject({
+ ok: false,
+ error: { code: "REQUEST_CANCELLED" },
+ });
+ finish({ windows: [] });
+ expect(
+ await readForRecovery(
+ deps,
+ "list_windows",
+ {},
+ { signal: controller.signal },
+ ),
+ ).toMatchObject({ ok: false });
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/lizi-mcps/src/computer/recovery.ts b/packages/lizi-mcps/src/computer/recovery.ts
new file mode 100644
index 0000000000..ca7248c65b
--- /dev/null
+++ b/packages/lizi-mcps/src/computer/recovery.ts
@@ -0,0 +1,175 @@
+import type { ComputerMcpCallContext, ComputerMcpDeps } from "../types.js";
+import { computerResultOutcome } from "./result.js";
+
+/** Recovery may observe, but never replay an action or choose a replacement window. */
+export type RecoveryTool =
+ "list_apps" | "list_windows" | "get_window_state" | "verify_state";
+export type RecoveryRead = {
+ tool: RecoveryTool;
+ ok: boolean;
+ data?: unknown;
+ error?: { code: string; message: string };
+};
+
+export function isWindowIdentityFailure(value: unknown): boolean {
+ if (!value || typeof value !== "object") return false;
+ const result = value as Record<string, unknown>;
+ return [result.code, result.degraded_reason].some(
+ (code) => code === "window_id_not_found" || code === "ax_window_unresolved",
+ );
+}
+
+/** A single best-effort read with its own deadline; failures never replace the primary result. */
+export async function readForRecovery(
+ deps: ComputerMcpDeps,
+ tool: RecoveryTool,
+ args: Record<string, unknown>,
+ context: ComputerMcpCallContext,
+ timeoutMs = 5_000,
+): Promise<RecoveryRead> {
+ const controller = new AbortController();
+ const abort = () => controller.abort(context.signal?.reason);
+ const timer = setTimeout(
+ () => controller.abort(new Error("Computer Use recovery read timed out")),
+ timeoutMs,
+ );
+ context.signal?.addEventListener("abort", abort, { once: true });
+ if (context.signal?.aborted) abort();
+ let onAbort: (() => void) | undefined;
+ try {
+ controller.signal.throwIfAborted();
+ const cancelled = new Promise<never>((_, reject) => {
+ onAbort = () => reject(controller.signal.reason);
+ controller.signal.addEventListener("abort", onAbort, { once: true });
+ });
+ const data = await Promise.race([
+ deps.callTool(tool, args, { ...context, signal: controller.signal, observationPurpose: 'recovery' }),
+ cancelled,
+ ]);
+ controller.signal.throwIfAborted();
+ const object =
+ data && typeof data === "object" && !Array.isArray(data)
+ ? (data as Record<string, unknown>)
+ : undefined;
+ const shapeValid =
+ object &&
+ (tool === "list_apps"
+ ? Array.isArray(object.apps)
+ : tool === "list_windows"
+ ? Array.isArray(object.windows)
+ : tool === "get_window_state"
+ ? Array.isArray(object.elements) ||
+ typeof object.tree_markdown === "string" ||
+ typeof object.screenshot_frame_valid === "boolean"
+ : true);
+ return {
+ tool,
+ ok: Boolean(shapeValid) && computerResultOutcome(tool, data).ok,
+ data,
+ };
+ } catch (error) {
+ return {
+ tool,
+ ok: false,
+ error: {
+ code: controller.signal.aborted
+ ? context.signal?.aborted
+ ? "REQUEST_CANCELLED"
+ : "RECOVERY_TIMEOUT"
+ : "RECOVERY_FAILED",
+ message: error instanceof Error ? error.message : String(error),
+ },
+ };
+ } finally {
+ clearTimeout(timer);
+ context.signal?.removeEventListener("abort", abort);
+ if (onAbort) controller.signal.removeEventListener("abort", onAbort);
+ }
+}
+
+/** This error is emitted before launching; generic failures must never be retried. */
+export function isAppNameResolutionFailure(
+ args: Record<string, unknown>,
+ error: unknown,
+): boolean {
+ const message = error instanceof Error ? error.message : "";
+ return (
+ (/^No installed macOS app found (?:for |with )?name\b/i.test(message) ||
+ (error as { code?: unknown } | null)?.code === "APP_NOT_INSTALLED") &&
+ (error as { outcomeUnknown?: boolean } | null)?.outcomeUnknown !== true &&
+ typeof args.name === "string" &&
+ args.name.trim().length > 0 &&
+ args.bundle_id === undefined
+ );
+}
+
+/** Locating a running process cannot satisfy URLs, launch arguments or new-instance intent. */
+export function canLocateRunningApp(
+ args: Record<string, unknown>,
+ error: unknown,
+): boolean {
+ return (
+ isAppNameResolutionFailure(args, error) &&
+ args.creates_new_application_instance !== true &&
+ args.electron_debugging_port === undefined &&
+ args.webkit_inspector_port === undefined &&
+ (!Array.isArray(args.urls) || args.urls.length === 0) &&
+ (!Array.isArray(args.additional_arguments) ||
+ args.additional_arguments.length === 0)
+ );
+}
+
+export function exactInstalledAppBundle(
+ name: string,
+ data: unknown,
+): string | undefined {
+ if (
+ !data ||
+ typeof data !== "object" ||
+ !Array.isArray((data as { apps?: unknown }).apps)
+ )
+ return;
+ const candidates = (data as { apps: unknown[] }).apps.filter((value) => {
+ if (!value || typeof value !== "object") return false;
+ const app = value as { name?: unknown };
+ return (
+ typeof app.name === "string" &&
+ app.name.trim().toLowerCase() === name.trim().toLowerCase()
+ );
+ });
+ // Do not collapse duplicate names, even if one happens to have a bundle ID.
+ if (candidates.length !== 1) return;
+ const bundleId = (candidates[0] as { bundle_id?: unknown }).bundle_id;
+ return typeof bundleId === "string" && bundleId.trim() ? bundleId : undefined;
+}
+
+export function exactRunningApp(
+ name: string,
+ data: unknown,
+): { pid: number; windows: unknown[] } | undefined {
+ if (
+ !data ||
+ typeof data !== "object" ||
+ !Array.isArray((data as { windows?: unknown }).windows)
+ )
+ return;
+ const windows = (data as { windows: unknown[] }).windows.filter((value) => {
+ if (!value || typeof value !== "object") return false;
+ const window = value as {
+ pid?: unknown;
+ app_name?: unknown;
+ process?: { name?: unknown };
+ };
+ const label = window.process?.name ?? window.app_name;
+ return (
+ Number.isInteger(window.pid) &&
+ Number(window.pid) > 0 &&
+ typeof label === "string" &&
+ label.trim().toLowerCase() === name.trim().toLowerCase()
+ );
+ });
+ const pids = new Set(
+ windows.map((window) => (window as { pid: number }).pid),
+ );
+ if (pids.size === 1) return { pid: [...pids][0]!, windows };
+}
diff --git a/packages/lizi-mcps/src/computer/result.ts b/packages/lizi-mcps/src/computer/result.ts
index 22a0f985b3..e57ded5d28 100644
--- a/packages/lizi-mcps/src/computer/result.ts
+++ b/packages/lizi-mcps/src/computer/result.ts
@@ -1,3 +1,31 @@
+/** Only explicit driver failure signals override legacy/partial observation success. */
+export function isUnavailableWindowObservation(
+ data: 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;
+ const screenshotFailed =
+ state.screenshot_frame_valid === false ||
+ (state.screenshot_error !== undefined && state.screenshot_error !== null);
+ const hasElements =
+ Array.isArray(state.elements) && state.elements.length > 0;
+ const hasTree =
+ typeof state.tree_markdown === 'string' &&
+ state.tree_markdown.trim().length > 0;
+ const axUnavailable = state.degraded === true && !hasElements && !hasTree;
+ // A screenshot explicitly requested by vision/SOM cannot be replaced by an AX tree.
+ // Conversely, a valid vision-only result may have no AX surface or input route.
+ if (captureMode === 'vision' || captureMode === 'som')
+ return screenshotFailed;
+ if (captureMode === 'ax') return axUnavailable;
+ return screenshotFailed && axUnavailable;
+}
+
/** Tool delivery is separate from evidence that a requested postcondition holds. */
export function computerResultOutcome(
name: string,
diff --git a/packages/lizi-mcps/src/computer/server.ts b/packages/lizi-mcps/src/computer/server.ts
index b98d6ae833..637c7fa286 100644
--- a/packages/lizi-mcps/src/computer/server.ts
+++ b/packages/lizi-mcps/src/computer/server.ts
@@ -20,10 +20,19 @@ import {
COMPUTER_TOOLS,
COMPUTER_TOOL_NAMES,
getComputerTool,
-} from './tools.js';
-import { logToolResultErrorCode } from '../tool-error-telemetry.js';
-import { WindowSnapshotTracker } from './snapshot-tracker.js';
-import { computerResultOutcome } from './result.js';
+ POSTCHECK_ACTION_TOOLS,
+} from "./tools.js";
+import { logToolResultErrorCode } from "../tool-error-telemetry.js";
+import { WindowSnapshotTracker } from "./snapshot-tracker.js";
+import { computerResultOutcome, isUnavailableWindowObservation } from "./result.js";
+import {
+ canLocateRunningApp,
+ exactInstalledAppBundle,
+ exactRunningApp,
+ isAppNameResolutionFailure,
+ isWindowIdentityFailure,
+ readForRecovery,
+} from "./recovery.js";
export interface ComputerMcpServerOptions {
sessionId?: string;
@@ -477,10 +486,32 @@ export function createComputerMcpServer(
// 快照代际护栏:element_index 指向"某次 get_window_state 的第几项",观察和
// 动作之间 UI 树变化时会静默作用到错误元素。带 snapshot_id 的动作在此校验
// 它是否仍是目标窗口最新观察;不带的放行(过渡兼容)但打遥测日志。
- const staleResult = checkSnapshotFreshness(name as ComputerMcpToolName, parsedData, sessionId);
+ const staleResult = checkSnapshotFreshness(
+ name as ComputerMcpToolName,
+ parsedData,
+ sessionId,
+ );
if (staleResult) return staleResult;
- if (typeof parsedData.snapshot_id === 'string') {
- const driverId = snapshotTracker.driverSnapshotId(sessionId, parsedData.snapshot_id);
+ const postcondition = parsedData.postcondition;
+ delete parsedData.postcondition; // Cindy-owned verification, never part of driver action args.
+ if (postcondition && typeof parsedData.window_id !== "number") {
+ return textResult(
+ {
+ ok: false,
+ errorCode: "INVALID_ARGS",
+ data: {
+ message:
+ "postcondition requires an exact window_id or a fresh element snapshot identifying the window.",
+ },
+ },
+ true,
+ );
+ }
+ 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.
}
@@ -535,6 +566,9 @@ export function createComputerMcpServer(
isUnavailableWindowObservation(data, parsedData)
) {
invalidateWindowSnapshot(name, parsedData, sessionId);
+ const recovery = isWindowIdentityFailure(data)
+ ? await rediscoverWindow(parsedData, { ...callContext, signal })
+ : undefined;
return textResult(
{
ok: false,
@@ -542,32 +576,231 @@ export function createComputerMcpServer(
errorCode: 'CUA_UNAVAILABLE',
hint: 'The requested window observation failed. Do not reuse earlier snapshot IDs, element indices or coordinates. Check status/check_permissions and refresh list_windows for the target; after the window or capture state recovers, call get_window_state again. Repeated capture failure requires recovery before further actions.',
data,
+ ...(recovery ? { recovery } : {}),
},
true,
);
}
- const outcome = computerResultOutcome(name, data);
- const snapshotId = recordWindowSnapshot(name as ComputerMcpToolName, parsedData, data, sessionId);
- return textResult({
- ...outcome,
- tool: name,
- ...(snapshotId ? { snapshot_id: snapshotId } : {}),
- data,
- }, !outcome.ok);
+ let outcome = computerResultOutcome(name, data);
+ const recovery =
+ name !== "get_window_state" && isWindowIdentityFailure(data)
+ ? await rediscoverWindow(parsedData, { ...callContext, signal })
+ : undefined;
+ const postcheck =
+ !recovery &&
+ POSTCHECK_ACTION_TOOLS.has(name as ComputerMcpToolName) &&
+ outcome.ok &&
+ (postcondition || outcome.outcome?.status === "unknown")
+ ? await checkActionState(parsedData, postcondition, {
+ ...callContext,
+ signal,
+ })
+ : undefined;
+ if (postcondition && postcheck) {
+ const checked = computerResultOutcome("verify_state", postcheck.data);
+ // An interrupted multi-chunk input is not a completed action, even if a
+ // weak predicate happens to match the already-written prefix.
+ const remaining = (data as { remaining_chars?: number } | null)
+ ?.remaining_chars;
+ if (postcheck.ok && !(typeof remaining === "number" && remaining > 0))
+ outcome = checked;
+ else if (!postcheck.ok) outcome = checked;
+ }
+ if (signal?.aborted)
+ throw Object.assign(
+ new Error("Computer Use cancelled during recovery"),
+ { outcomeUnknown: !def.readOnly },
+ );
+ const snapshotId = recovery
+ ? undefined
+ : recordWindowSnapshot(
+ name as ComputerMcpToolName,
+ parsedData,
+ data,
+ sessionId,
+ );
+ return textResult(
+ {
+ ...outcome,
+ tool: name,
+ ...(snapshotId ? { snapshot_id: snapshotId } : {}),
+ data,
+ ...(recovery ? { recovery } : {}),
+ ...(postcheck ? { postcheck } : {}),
+ },
+ !outcome.ok,
+ );
} catch (err) {
+ const errorCode = signal?.aborted
+ ? "REQUEST_CANCELLED"
+ : typeof (err as { code?: unknown })?.code === "string"
+ ? (err as { code: string }).code
+ : "COMPUTER_DRIVER_ERROR";
+ const windowUnresolved = isWindowIdentityFailure(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);
+ if (
+ (windowUnresolved ||
+ signal?.aborted ||
+ (err as { outcomeUnknown?: boolean })?.outcomeUnknown) &&
+ typeof parsedData.pid === "number" &&
+ typeof parsedData.window_id === "number"
+ ) {
+ snapshotTracker.invalidate(
+ sessionId,
+ parsedData.pid,
+ parsedData.window_id,
+ );
+ }
+ const recovery =
+ windowUnresolved && !signal?.aborted
+ ? await rediscoverWindow(parsedData, { ...callContext, signal })
+ : undefined;
+ const postcheck =
+ !recovery &&
+ !signal?.aborted &&
+ errorCode !== "REQUEST_CANCELLED" &&
+ POSTCHECK_ACTION_TOOLS.has(name as ComputerMcpToolName) &&
+ (err as { outcomeUnknown?: boolean })?.outcomeUnknown
+ ? await checkActionState(parsedData, postcondition, {
+ ...callContext,
+ signal,
+ })
+ : undefined;
+ const installedDiscovery =
+ name === "launch_app" &&
+ !signal?.aborted &&
+ isAppNameResolutionFailure(parsedData, err)
+ ? await readForRecovery(
+ deps,
+ "list_apps",
+ {},
+ { ...callContext, signal },
+ )
+ : undefined;
+ const bundleId = installedDiscovery?.ok
+ ? exactInstalledAppBundle(
+ parsedData.name as string,
+ installedDiscovery.data,
+ )
+ : undefined;
+ if (bundleId && !signal?.aborted) {
+ // The first call explicitly failed before launching. Resolve the name
+ // once, preserving URLs/options; no recursive fallback after this call.
+ try {
+ const data = await callComputerTool(
+ deps,
+ "launch_app",
+ { ...parsedData, bundle_id: bundleId },
+ { ...callContext, signal },
+ );
+ if (signal?.aborted)
+ throw Object.assign(new Error("Application launch cancelled"), {
+ code: "REQUEST_CANCELLED",
+ outcomeUnknown: true,
+ });
+ const outcome = computerResultOutcome("launch_app", data);
+ return textResult(
+ {
+ ...outcome,
+ tool: name,
+ data,
+ recovery: {
+ resolved_bundle_id: bundleId,
+ discovery: installedDiscovery,
+ },
+ },
+ !outcome.ok,
+ );
+ } catch (launchError) {
+ return textResult(
+ {
+ ok: false,
+ errorCode:
+ typeof (launchError as { code?: unknown })?.code === "string"
+ ? (launchError as { code: string }).code
+ : "COMPUTER_DRIVER_ERROR",
+ data: {
+ message:
+ launchError instanceof Error
+ ? launchError.message
+ : String(launchError),
+ ...((launchError as { outcomeUnknown?: boolean })
+ ?.outcomeUnknown
+ ? { outcome_unknown: true }
+ : {}),
+ },
+ recovery: {
+ original_error:
+ err instanceof Error ? err.message : String(err),
+ discovery: installedDiscovery,
+ resolved_bundle_id: bundleId,
+ retry_exhausted: true,
+ },
+ },
+ true,
+ );
+ }
+ }
+ const appDiscovery =
+ name === "launch_app" &&
+ !signal?.aborted &&
+ canLocateRunningApp(parsedData, err)
+ ? await readForRecovery(
+ deps,
+ "list_windows",
+ withSessionArg("list_windows", {}, sessionId),
+ { ...callContext, signal },
+ )
+ : undefined;
+ const located = appDiscovery?.ok
+ ? exactRunningApp(parsedData.name as string, appDiscovery.data)
+ : undefined;
+ if (located && !signal?.aborted) {
+ return textResult({
+ ok: true,
+ tool: name,
+ data: {
+ ...located,
+ located: true,
+ launched: false,
+ source: "running_windows",
+ },
+ recovery: {
+ original_error: {
+ code: errorCode,
+ message: err instanceof Error ? err.message : String(err),
+ },
+ discovery: appDiscovery,
+ },
+ });
}
return textResult(
{
ok: false,
- errorCode: signal?.aborted ? 'REQUEST_CANCELLED' :
- typeof (err as { code?: unknown })?.code === 'string' ? (err as { code: string }).code : 'COMPUTER_DRIVER_ERROR',
+ errorCode,
+ ...(recovery ? { recovery } : {}),
+ ...(postcheck ? { postcheck } : {}),
+ ...(appDiscovery || installedDiscovery
+ ? {
+ recovery: {
+ discovery: appDiscovery,
+ installed_discovery: installedDiscovery,
+ next_step: "choose_application",
+ target_selected: false,
+ },
+ }
+ : {}),
data: {
message: err instanceof Error ? err.message : String(err),
- ...((err as { outcomeUnknown?: boolean })?.outcomeUnknown ? { outcome_unknown: true, next_step: 'fresh_state' } : {}),
+ ...((err as { outcomeUnknown?: boolean })?.outcomeUnknown
+ ? { outcome_unknown: true, next_step: "fresh_state" }
+ : {}),
+ ...(windowUnresolved
+ ? {
+ next_step: "list_windows",
+ hint: "Rediscover the target PID/window, then take fresh get_window_state before acting. Do not reuse old element references or automatically switch to a similar window.",
+ }
+ : {}),
},
},
true,
@@ -575,6 +808,77 @@ export function createComputerMcpServer(
}
}
+ async function rediscoverWindow(
+ args: Record<string, unknown>,
+ context: ComputerMcpCallContext,
+ ) {
+ if (typeof args.pid === "number" && typeof args.window_id === "number") {
+ snapshotTracker.invalidate(context.sessionId, args.pid, args.window_id);
+ }
+ // Enumerate afresh without the obsolete PID filter so a dev restart is
+ // visible. Candidates are evidence for the agent, not permission to retarget.
+ const discovery = await readForRecovery(
+ deps,
+ "list_windows",
+ withSessionArg("list_windows", {}, context.sessionId),
+ context,
+ );
+ return {
+ requested_target: { pid: args.pid, window_id: args.window_id },
+ discovery,
+ target_selected: false,
+ next_step: "get_window_state",
+ };
+ }
+
+ async function checkActionState(
+ args: Record<string, unknown>,
+ postcondition: unknown,
+ context: ComputerMcpCallContext,
+ ) {
+ if (typeof args.pid !== "number" || typeof args.window_id !== "number") {
+ return readForRecovery(
+ deps,
+ "list_windows",
+ withSessionArg("list_windows", { pid: args.pid }, context.sessionId),
+ context,
+ );
+ }
+ snapshotTracker.invalidate(context.sessionId, args.pid, args.window_id);
+ const tool = postcondition ? "verify_state" : "get_window_state";
+ const readArgs = {
+ pid: args.pid,
+ window_id: args.window_id,
+ ...(postcondition
+ ? {
+ expect: postcondition,
+ timeout_ms: 1500,
+ stable_samples: 2,
+ include_screenshot: false,
+ }
+ // Automatic evidence must not create unmanaged screenshots of user windows.
+ : { include_screenshot: false }),
+ };
+ const read = await readForRecovery(
+ deps,
+ tool,
+ withSessionArg(tool, readArgs, context.sessionId),
+ context,
+ );
+ if (tool === "get_window_state" && read.ok) {
+ if (isUnavailableWindowObservation(read.data, readArgs))
+ return { ...read, ok: false };
+ // This is post-action evidence, not a reusable element observation. A late
+ // automatic read must not supersede another caller's newer explicit state.
+ return {
+ ...read,
+ reusable_snapshot: false,
+ next_step: "get_window_state",
+ };
+ }
+ return read;
+ }
+
function invalidateWindowSnapshot(
name: string,
args: Record<string, unknown>,
@@ -1227,33 +1531,6 @@ export function createComputerMcpServer(
return server;
}
-/** Only explicit driver failure signals override legacy/partial observation success. */
-export function isUnavailableWindowObservation(
- data: 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;
- const screenshotFailed =
- state.screenshot_frame_valid === false ||
- (state.screenshot_error !== undefined && state.screenshot_error !== null);
- const hasElements =
- Array.isArray(state.elements) && state.elements.length > 0;
- const hasTree =
- typeof state.tree_markdown === 'string' &&
- state.tree_markdown.trim().length > 0;
- const axUnavailable = state.degraded === true && !hasElements && !hasTree;
- // A screenshot explicitly requested by vision/SOM cannot be replaced by an AX tree.
- // Conversely, a valid vision-only result may have no AX surface or input route.
- if (captureMode === 'vision' || captureMode === 'som')
- return screenshotFailed;
- if (captureMode === 'ax') return axUnavailable;
- return screenshotFailed && axUnavailable;
-}
function readDriverSnapshotId(data: unknown): string | null {
if (!data || typeof data !== 'object' || Array.isArray(data)) return null;
diff --git a/packages/lizi-mcps/src/computer/snapshotGuard.test.ts b/packages/lizi-mcps/src/computer/snapshotGuard.test.ts
index 275cb49c5f..b8f5b74d34 100644
--- a/packages/lizi-mcps/src/computer/snapshotGuard.test.ts
+++ b/packages/lizi-mcps/src/computer/snapshotGuard.test.ts
@@ -122,60 +122,208 @@ describe('WindowSnapshotTracker', () => {
});
});
-describe('opaque element credentials', () => {
- it('disambiguates repeated tokens with an explicit fresh observation without reviving old references', async () => {
+describe("opaque element credentials", () => {
+ it.each(["window_id_not_found", "ax_window_unresolved"])(
+ "invalidates stale window credentials after a driver %s error without replay",
+ async (code) => {
+ let failNextAction = true;
+ const dispatch = vi.fn(async (name: string) => {
+ if (name === "get_window_state")
+ return { snapshot_id: "native-id", elements: [] };
+ if (name === "list_windows") return { windows: [] };
+ if (failNextAction) {
+ failNextAction = false;
+ throw Object.assign(new Error(code), { code });
+ }
+ return { effect: "confirmed" };
+ });
+ const h = await makeHarness(
+ { getStatus: vi.fn(), callTool: dispatch },
+ { sessionId: "window-gone" },
+ );
+ try {
+ const state = await h.call("get_window_state", {
+ pid: 1,
+ window_id: 2,
+ });
+ const other = await h.call("get_window_state", {
+ pid: 1,
+ window_id: 3,
+ });
+ const args = {
+ pid: 1,
+ element_index: 0,
+ snapshot_id: state.snapshot_id,
+ };
+ expect(await h.call("click", args)).toMatchObject({
+ ok: false,
+ errorCode: code,
+ data: { next_step: "list_windows" },
+ });
+ expect(await h.call("click", args)).toMatchObject({
+ errorCode: "STALE_SNAPSHOT",
+ });
+ expect(dispatch).toHaveBeenCalledTimes(4);
+ expect(dispatch.mock.calls.map(([name]) => name)).toEqual([
+ "get_window_state",
+ "get_window_state",
+ "click",
+ "list_windows",
+ ]);
+ expect(
+ await h.call("click", { ...args, snapshot_id: other.snapshot_id }),
+ ).toMatchObject({ ok: true });
+ const fresh = await h.call("get_window_state", {
+ pid: 1,
+ window_id: 2,
+ });
+ expect(
+ await h.call("click", { ...args, snapshot_id: fresh.snapshot_id }),
+ ).toMatchObject({ ok: true });
+ } finally {
+ await h.cleanup();
+ }
+ },
+ );
+ 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' });
+ 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 });
+ 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' });
+ 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(
+ 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(); }
+ 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 () => {
+ 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 });
+ 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' });
+ 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 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(); }
+ expect(await h.call("click", args)).toMatchObject({
+ ok: false,
+ data: { outcome_unknown: true },
+ });
+ expect(dispatch).toHaveBeenNthCalledWith(
+ 2,
+ "click",
+ expect.objectContaining({ window_id: 2 }),
+ expect.anything(),
+ );
+ expect(dispatch).toHaveBeenLastCalledWith(
+ "get_window_state",
+ expect.objectContaining({ window_id: 2 }),
+ expect.anything(),
+ );
+ expect(await h.call("click", args)).toMatchObject({
+ errorCode: "STALE_SNAPSHOT",
+ });
+ expect(dispatch).toHaveBeenCalledTimes(3);
+ } 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' });
+ 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' });
+ 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) }));
+ 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(
+ 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(); }
+ } finally {
+ await h.cleanup();
+ }
});
});
@@ -529,14 +677,22 @@ describe('computer snapshot guard', () => {
},
{ mode: undefined, state: { elements: [] }, ok: true },
])(
- 'respects requested observation mode: $mode / ok=$ok',
+ "respects requested observation mode: $mode / ok=$ok",
async ({ mode, args, state, ok }) => {
- const callTool = vi.fn(async () => state);
- const h = await makeHarness({ getStatus: vi.fn(), callTool }, {
- getSessionContext: () => ({ workingDir: process.cwd(), agentKind: 'test' }),
- });
+ const callTool = vi.fn(async (name: string) =>
+ name === "list_windows" ? { windows: [] } : state,
+ );
+ const h = await makeHarness(
+ { getStatus: vi.fn(), callTool },
+ {
+ getSessionContext: () => ({
+ workingDir: process.cwd(),
+ agentKind: "test",
+ }),
+ },
+ );
try {
- const observed = await h.call('get_window_state', {
+ const observed = await h.call("get_window_state", {
pid: 100,
window_id: 1,
capture_mode: mode,
@@ -545,8 +701,17 @@ describe('computer snapshot guard', () => {
expect(observed.ok).toBe(ok);
expect(Boolean(observed.snapshot_id)).toBe(ok);
expect(observed.data).toEqual(state);
- // A failed observation is reported once; the wrapper never replays it or restarts the driver.
- expect(callTool).toHaveBeenCalledTimes(1);
+ // A failed AX observation may discover windows once, but never replays
+ // the observation, switches the target, or restarts the driver.
+ const rediscovered =
+ !ok &&
+ "degraded_reason" in state &&
+ state.degraded_reason === "ax_window_unresolved";
+ expect(callTool.mock.calls.map(([name]) => name)).toEqual(
+ rediscovered
+ ? ["get_window_state", "list_windows"]
+ : ["get_window_state"],
+ );
} finally {
await h.cleanup();
}
diff --git a/packages/lizi-mcps/src/computer/tools.ts b/packages/lizi-mcps/src/computer/tools.ts
index 6afc00081d..508f116ac3 100644
--- a/packages/lizi-mcps/src/computer/tools.ts
+++ b/packages/lizi-mcps/src/computer/tools.ts
@@ -24,6 +24,64 @@ 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.',
);
+const POSTCONDITION = 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);
+
+/** These input actions may be followed by one read-only postcondition check. */
+export const POSTCHECK_ACTION_TOOLS = new Set<ComputerMcpToolName>([
+ "click",
+ "double_click",
+ "right_click",
+ "drag",
+ "type_text",
+ "set_value",
+ "press_key",
+ "hotkey",
+ "scroll",
+]);
+
const COMPUTER_TOOL_DEFINITIONS: readonly ComputerToolDef[] = [
{
name: 'status',
@@ -50,7 +108,7 @@ const COMPUTER_TOOL_DEFINITIONS: readonly ComputerToolDef[] = [
{
name: 'launch_app',
description:
- 'Launch or locate an application without stealing focus. Prefer this over shell open/Start-Process for GUI apps. If an already-running app such as Simulator is not discoverable here, use list_windows with {"process_name":"Simulator"}.',
+ 'Launch or locate an application without stealing focus. Prefer bundle_id when known. On an explicit name-resolution failure, Cindy tries a unique exact-name bundle from list_apps once; for a plain name it can also locate a unique running process through list_windows (e.g. {"process_name":"Simulator"}). Located is not newly launched; URL, launch-option and new-instance requests are never replaced by locating.',
inputShape: {
name: z.string().optional(),
bundle_id: z.string().optional(),
@@ -104,25 +162,13 @@ const COMPUTER_TOOL_DEFINITIONS: readonly ComputerToolDef[] = [
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),
+ expect: POSTCONDITION,
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.'),
+ include_screenshot: z
+ .literal(false)
+ .optional()
+ .describe("Use get_window_state for a host-managed screenshot."),
},
},
{
@@ -180,8 +226,9 @@ const COMPUTER_TOOL_DEFINITIONS: readonly ComputerToolDef[] = [
},
},
{
- name: 'drag',
- description: 'Drag from one window-local coordinate to another. Use after get_window_state or zoom.',
+ name: "drag",
+ description:
+ "Drag from one window-local coordinate to another. Use after get_window_state or zoom. On macOS, omitted delivery_mode defaults to foreground and may bring the target forward; explicit background is never escalated or retried.",
inputShape: {
pid: z.number().int().positive(),
window_id: z.number().int().nonnegative().optional(),
@@ -344,17 +391,33 @@ const COMPUTER_TOOL_DEFINITIONS: readonly ComputerToolDef[] = [
];
/** Name the whole computer-use objective once; the host owns stable routing. */
-export const COMPUTER_TOOLS: readonly ComputerToolDef[] = COMPUTER_TOOL_DEFINITIONS.map((tool) => ({
- ...tool,
- inputShape: !['status', 'check_permissions', 'replay_trajectory'].includes(tool.name)
- ? {
- ...tool.inputShape,
- session_goal: z.string().trim().min(1).max(80).optional().describe(
- 'On your FIRST computer-use call, provide a short English name for the overall goal of this run (e.g. "Submit expense report" or "Configure notifications"), not the current click or typing step. Use English because the native cursor font does not support CJK text. The host sets the driver session name once and keeps it for the run; omit this field on later calls. Never include credentials or internal IDs.',
- ),
- }
- : tool.inputShape,
-}));
+export const COMPUTER_TOOLS: readonly ComputerToolDef[] =
+ COMPUTER_TOOL_DEFINITIONS.map((tool) => ({
+ ...tool,
+ inputShape: !["status", "check_permissions", "replay_trajectory"].includes(
+ tool.name,
+ )
+ ? {
+ ...tool.inputShape,
+ ...(POSTCHECK_ACTION_TOOLS.has(tool.name)
+ ? {
+ postcondition: POSTCONDITION.optional().describe(
+ "Optional expected final state, using verify_state predicates. Cindy checks it once after delivery (requires an exact window). Without it, unknown delivery gets one fresh observation but is never declared successful. Actions are never replayed automatically.",
+ ),
+ }
+ : {}),
+ session_goal: z
+ .string()
+ .trim()
+ .min(1)
+ .max(80)
+ .optional()
+ .describe(
+ 'On your FIRST computer-use call, provide a short English name for the overall goal of this run (e.g. "Submit expense report" or "Configure notifications"), not the current click or typing step. Use English because the native cursor font does not support CJK text. The host sets the driver session name once and keeps it for the run; omit this field on later calls. Never include credentials or internal IDs.',
+ ),
+ }
+ : tool.inputShape,
+ }));
export const COMPUTER_TOOL_NAMES = COMPUTER_TOOLS.map((tool) => tool.name) as [
ComputerMcpToolName,
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index ecbc9bd975..74ef1fcd87 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -632,6 +632,8 @@ export interface ComputerDriverPermissionState {
export interface ComputerMcpCallContext {
sessionId?: string;
+ /** Host-only observation origin; automatic reads must not authorize resumed input. */
+ observationPurpose?: 'recovery';
/** Request cancellation stays on the host side; never serialized to the driver. */
signal?: AbortSignal;
/** Identifies the agent runtime whose MCP server dispatched this call. */