Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(computer): 正确报告窗口观测失败并失效旧快照 (#3937)
Dash0d4b1a368e83
diff --git a/packages/lizi-mcps/src/computer/server.ts b/packages/lizi-mcps/src/computer/server.tsindex b6952a8045..09227c108f 100644--- a/packages/lizi-mcps/src/computer/server.ts+++ b/packages/lizi-mcps/src/computer/server.ts@@ -376,6 +376,22 @@ export function createComputerMcpServer(parsedArgs,callContext,);+ if (+ name === 'get_window_state' &&+ isUnavailableWindowObservation(data, parsedData.capture_mode)+ ) {+ invalidateWindowSnapshot(name, parsedData, sessionId);+ return textResult(+ {+ ok: false,+ tool: name,+ 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,+ },+ true,+ );+ }const snapshotId = recordWindowSnapshot(name as ComputerMcpToolName, parsedData, data, sessionId);return textResult({ok: true,@@ -384,6 +400,7 @@ export function createComputerMcpServer(data,});} catch (err) {+ invalidateWindowSnapshot(name, parsedData, sessionId);return textResult({ok: false,@@ -395,6 +412,20 @@ export function createComputerMcpServer(}}+ function invalidateWindowSnapshot(+ name: string,+ args: Record<string, unknown>,+ sessionId: string | undefined,+ ): void {+ if (+ name === 'get_window_state' &&+ typeof args.pid === 'number' &&+ typeof args.window_id === 'number'+ ) {+ snapshotTracker.invalidate(sessionId, args.pid, args.window_id);+ }+ }+function trajectoryValidationFailedResult(message: string, turn?: string) {return textResult({@@ -959,6 +990,31 @@ export function createComputerMcpServer(return server;}+/** Only explicit driver failure signals override legacy/partial observation success. */+function isUnavailableWindowObservation(+ data: unknown,+ captureMode: unknown,+): boolean {+ 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;const direct = (data as { snapshot_id?: unknown }).snapshot_id;diff --git a/packages/lizi-mcps/src/computer/snapshot-tracker.ts b/packages/lizi-mcps/src/computer/snapshot-tracker.tsindex c1ba714b85..0393a4d1e6 100644--- a/packages/lizi-mcps/src/computer/snapshot-tracker.ts+++ b/packages/lizi-mcps/src/computer/snapshot-tracker.ts@@ -84,6 +84,15 @@ export class WindowSnapshotTracker {return id;}+ /** A failed observation invalidates earlier IDs and aliases without issuing a usable ID. */+ invalidate(+ sessionId: string | undefined,+ pid: number,+ windowId: number,+ ): void {+ this.latestByWindow.delete(this.windowKey(sessionId ?? '', pid, windowId));+ }+/** Register a host/driver snapshot id as an alias for the MCP-level guard id. */registerAlias(snapshotId: string, alias: string): void {const meta = this.metaById.get(snapshotId);diff --git a/packages/lizi-mcps/src/computer/snapshotGuard.test.ts b/packages/lizi-mcps/src/computer/snapshotGuard.test.tsindex e9daac651e..d2748056e0 100644--- a/packages/lizi-mcps/src/computer/snapshotGuard.test.ts+++ b/packages/lizi-mcps/src/computer/snapshotGuard.test.ts@@ -31,6 +31,7 @@ async function makeHarness(deps: ComputerMcpDeps, options?: Parameters<typeof crtextPayload(await client.callTool({ name: 'call_tool', arguments: { name, args } }));return {call,+ client,cleanup: async () => {await client.close();await server.close();@@ -298,8 +299,182 @@ describe('computer snapshot guard', () => {const h = await makeHarness(deps, { sessionId: 'sess-1' });const observed = await h.call('get_window_state', { pid: 100, window_id: 1 });- expect(observed.ok).toBe(true);+ expect(observed.ok).toBe(false);+ expect(observed.errorCode).toBe('CUA_UNAVAILABLE');expect(observed).not.toHaveProperty('snapshot_id');await h.cleanup();});+ const failedCapture = {+ degraded: true,+ degraded_reason: 'ax_window_unresolved',+ elements: [],+ tree_markdown: '',+ screenshot_frame_valid: false,+ screenshot_error: {+ code: 'px_capture_unavailable',+ reason: 'ScreenCaptureKit and shell capture failed',+ },+ background_input: {+ routes: [{ route: 'accessibility', status: 'refused' }],+ },+ };++ it.each(['returned failure', 'thrown failure'])(+ 'invalidates only the failed window and recovers after a fresh observation: %s',+ async (failure) => {+ let fail = false;+ const callTool = vi.fn(async (name: string) => {+ if (name === 'get_window_state') {+ if (fail) {+ if (failure === 'thrown failure') throw new Error('window gone');+ return failedCapture;+ }+ return { elements: [{ element_token: 'driver-first:0' }] };+ }+ return { ok: true };+ });+ let sessionId = 's1';+ const h = await makeHarness(+ { getStatus: vi.fn(), callTool },+ {+ getSessionContext: () => ({+ sessionId,+ workingDir: '',+ agentKind: 'codex',+ }),+ },+ );+ try {+ const first = await h.call('get_window_state', {+ pid: 100,+ window_id: 1,+ });+ const otherWindow = await h.call('get_window_state', {+ pid: 100,+ window_id: 2,+ });+ sessionId = 's2';+ const otherSession = await h.call('get_window_state', {+ pid: 100,+ window_id: 1,+ });+ sessionId = 's1';+ fail = true;+ const result = await h.client.callTool({+ name: 'call_tool',+ arguments: {+ name: 'get_window_state',+ args: { pid: 100, window_id: 1, capture_mode: 'vision' },+ },+ });+ expect(result.isError).toBe(true);+ const payload = textPayload(result);+ expect(payload.ok).toBe(false);+ expect(payload).not.toHaveProperty('snapshot_id');+ if (failure === 'returned failure')+ expect(payload.data).toEqual(failedCapture);+ const dispatchCount = callTool.mock.calls.length;+ for (const snapshot_id of [first.snapshot_id, 'driver-first']) {+ expect(+ await h.call('click', {+ pid: 100,+ window_id: 1,+ element_index: 0,+ snapshot_id,+ }),+ ).toMatchObject({ ok: false, errorCode: 'STALE_SNAPSHOT' });+ }+ expect(callTool).toHaveBeenCalledTimes(dispatchCount);+ expect(+ await h.call('click', {+ pid: 100,+ window_id: 2,+ element_index: 0,+ snapshot_id: otherWindow.snapshot_id,+ }),+ ).toMatchObject({ ok: true });+ sessionId = 's2';+ expect(+ await h.call('click', {+ pid: 100,+ window_id: 1,+ element_index: 0,+ snapshot_id: otherSession.snapshot_id,+ }),+ ).toMatchObject({ ok: true });+ sessionId = 's1';+ fail = false;+ const recovered = await h.call('get_window_state', {+ pid: 100,+ window_id: 1,+ });+ expect(+ await h.call('click', {+ pid: 100,+ window_id: 1,+ element_index: 0,+ snapshot_id: recovered.snapshot_id,+ }),+ ).toMatchObject({ ok: true });+ } finally {+ await h.cleanup();+ }+ },+ );++ it.each([+ { mode: undefined, state: failedCapture, ok: false },+ {+ mode: 'vision',+ state: { ...failedCapture, elements: [{ index: 0 }] },+ ok: false,+ },+ { mode: 'som', state: failedCapture, ok: false },+ {+ mode: 'ax',+ state: { degraded: true, elements: [], tree_markdown: '' },+ ok: false,+ },+ {+ mode: 'ax',+ state: { ...failedCapture, elements: [{ index: 0 }] },+ ok: true,+ },+ {+ mode: undefined,+ state: { ...failedCapture, tree_markdown: 'Button: Save' },+ ok: true,+ },+ {+ mode: 'vision',+ state: {+ degraded: true,+ elements: [],+ screenshot_frame_valid: true,+ screenshot_file_path: 'state.png',+ },+ ok: true,+ },+ { mode: undefined, state: { elements: [] }, ok: true },+ ])(+ 'respects requested observation mode: $mode / ok=$ok',+ async ({ mode, state, ok }) => {+ const callTool = vi.fn(async () => state);+ const h = await makeHarness({ getStatus: vi.fn(), callTool });+ try {+ const observed = await h.call('get_window_state', {+ pid: 100,+ window_id: 1,+ capture_mode: mode,+ });+ 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);+ } finally {+ await h.cleanup();+ }+ },+ );});