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): preserve observations after uncertain actions and invalidation

Dashc138b9ab25e8
diff --git a/packages/lizi-mcps/src/computer/README.md b/packages/lizi-mcps/src/computer/README.md
index b78e1da6e7..3a569b2489 100644
--- a/packages/lizi-mcps/src/computer/README.md
+++ b/packages/lizi-mcps/src/computer/README.md
@@ -27,11 +27,18 @@ that session/window. Override them only when the target is outside the current
scope. The returned `observation` uses the ordinary read result envelope and
registers fresh element tokens and secure-field frames. It is mutually exclusive
with `postcondition`, which checks an explicit assertion instead.
+Invalidating element references does not discard that scope: automatic evidence,
+failed reads and failed verification keep the last successful explicit read's
+bounds, while old tokens remain stale. A successful later read replaces the scope.
Delivery and observation have separate outcomes: inspect `observation.ok` and
the returned state before continuing. Failed reads do not undo delivery, and
unknown delivery is not proof that the goal succeeded. Input is never replayed
automatically. Refused actions do not trigger the optional observation.
+An action exception marked `outcomeUnknown` also honors `observe`, preserving
+its error code and partial-input progress alongside the new observation. A failed
+observation does not replace the original action error. Cancelled actions and
+unresolved window identities do not trigger this follow-up read.
Cindy MCP supplies the task's stable driver session. When using the native CLI
instead, pass the **same non-default `session` on every read and action**, then
diff --git a/packages/lizi-mcps/src/computer/recovery.test.ts b/packages/lizi-mcps/src/computer/recovery.test.ts
index 963fb3b226..7df21c586d 100644
--- a/packages/lizi-mcps/src/computer/recovery.test.ts
+++ b/packages/lizi-mcps/src/computer/recovery.test.ts
@@ -130,6 +130,67 @@ describe("bounded Computer Use recovery", () => {
expect(dispatch.mock.calls.map(([name]) => name)).toEqual(["type_text", "get_window_state"]);
});
+ // PR #6811 P1: unlike returned uncertainty, a thrown partial input skipped
+ // explicit observe. Unit MCP entry: assert usable tokens AND preserved failure.
+ it.each([false, true])('honors observe after partial input without replay, even if observation fails (failedRead=%s)', async (failedRead) => {
+ let reads = 0;
+ const inputProgress = { completed_chars: 2, remaining_chars: 3 };
+ const dispatch = vi.fn(async (name: string) => {
+ if (name === 'type_text') throw Object.assign(new Error('Agent yielded'), {
+ code: 'DESKTOP_INPUT_YIELDED', outcomeUnknown: true, inputProgress,
+ });
+ if (name !== 'get_window_state') return { effect: 'confirmed' };
+ if (++reads === 2 && failedRead) throw new Error('Capture unavailable');
+ return { snapshot_id: `s${reads}`, elements: [{ element_index: 0, element_token: `s${reads}:0` }] };
+ });
+ const call = await harness(dispatch);
+ await call('get_window_state', { pid: 1, window_id: 2, query: 'Next', max_elements: 70, max_depth: 6 });
+ const result = await call('type_text', { pid: 1, element_token: 's1:0', text: 'hello', observe: {} });
+ expect(result).toMatchObject({
+ ok: false, errorCode: 'DESKTOP_INPUT_YIELDED',
+ data: { outcome_unknown: true, input_progress: inputProgress },
+ observation: failedRead
+ ? { ok: false, errorCode: 'COMPUTER_DRIVER_ERROR' }
+ : { ok: true, snapshot_id: expect.any(String), data: { snapshot_id: 's2' } },
+ });
+ expect(result).not.toHaveProperty('postcheck');
+ expect(dispatch).toHaveBeenLastCalledWith('get_window_state', {
+ pid: 1, window_id: 2, session: 'recovery-test', query: 'Next', max_elements: 70, max_depth: 6, include_screenshot: false,
+ }, expect.objectContaining({ sessionId: 'recovery-test' }));
+ expect(dispatch.mock.calls.map(([name]) => name)).toEqual(['get_window_state', 'type_text', 'get_window_state']);
+ expect(await call('click', { pid: 1, element_token: 's1:0' })).toMatchObject({ errorCode: 'STALE_SNAPSHOT' });
+ expect(await call('click', { pid: 1, element_token: 's2:0' })).toMatchObject(failedRead
+ ? { errorCode: 'STALE_SNAPSHOT' }
+ : { ok: true });
+ });
+
+ // PR #6811 P2: recovery and failed reads invalidated both tokens and scope.
+ // Existing unit tests only observed immediately after a successful read.
+ it.each(['automatic evidence', 'failed read', 'failed verification'])('inherits the last successful scope after %s while keeping old tokens stale', async (invalidation) => {
+ let reads = 0;
+ const dispatch = vi.fn(async (name: string) => {
+ if (name === 'click') return { effect: 'unverifiable' };
+ if (++reads === 2 && invalidation !== 'automatic evidence') throw new Error('Capture unavailable');
+ return { snapshot_id: `s${reads}`, elements: [{ element_index: 0, element_token: `s${reads}:0` }] };
+ });
+ const call = await harness(dispatch);
+ await call('get_window_state', { pid: 1, window_id: 2, query: 'Next', max_elements: 70, max_depth: 6 });
+ if (invalidation === 'automatic evidence') {
+ await call('click', { pid: 1, element_token: 's1:0' });
+ } else if (invalidation === 'failed verification') {
+ await call('verify_state', { pid: 1, window_id: 2, expect: [{ window: { exists: true } }] });
+ } else {
+ await call('get_window_state', { pid: 1, window_id: 2, query: 'Failed override' });
+ }
+ expect(await call('click', { pid: 1, element_token: 's1:0' })).toMatchObject({ errorCode: 'STALE_SNAPSHOT' });
+ expect(await call('click', { pid: 1, window_id: 2, x: 1, y: 2, observe: { max_elements: 90 } }))
+ .toMatchObject({ observation: { ok: true, data: { snapshot_id: 's3' } } });
+ expect(dispatch).toHaveBeenLastCalledWith('get_window_state', {
+ pid: 1, window_id: 2, session: 'recovery-test', query: 'Next', max_elements: 90, max_depth: 6, include_screenshot: false,
+ }, expect.any(Object));
+ expect(await call('click', { pid: 1, element_token: 's3:0' })).toMatchObject({ ok: true });
+ });
+
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) =>
@@ -512,7 +573,7 @@ describe("bounded Computer Use recovery", () => {
]);
});
- it("does not create recovery traffic after the host has closed an action session", async () => {
+ it.each([false, true])("does not create recovery traffic after the host has closed an action session (observe=%s)", async (observe) => {
const dispatch = vi.fn(async () => {
throw Object.assign(new Error("Closed"), {
code: "REQUEST_CANCELLED",
@@ -521,7 +582,7 @@ describe("bounded Computer Use recovery", () => {
});
const call = await harness(dispatch);
expect(
- await call("click", { pid: 1, window_id: 2, x: 2, y: 3 }),
+ await call("click", { pid: 1, window_id: 2, x: 2, y: 3, ...(observe ? { observe: {} } : {}) }),
).toMatchObject({ errorCode: "REQUEST_CANCELLED" });
expect(dispatch).toHaveBeenCalledTimes(1);
});
diff --git a/packages/lizi-mcps/src/computer/server.ts b/packages/lizi-mcps/src/computer/server.ts
index 1bde3ab5a4..a445de9638 100644
--- a/packages/lizi-mcps/src/computer/server.ts
+++ b/packages/lizi-mcps/src/computer/server.ts
@@ -565,6 +565,19 @@ export function createComputerMcpServer(
parsedData,
sessionId,
);
+ // Both delivered and uncertain actions honor an explicit observation request.
+ // Keep its normal read guards and registration in one path; never replay input.
+ const readActionObservation = async () => {
+ const read = await handleCallTool('get_window_state', {
+ ...observationScope,
+ ...observe,
+ pid: parsedData.pid,
+ window_id: parsedData.window_id,
+ include_screenshot: observe?.include_screenshot ?? false,
+ ...(typeof parsedData.session === 'string' ? { session: parsedData.session } : {}),
+ }, signal, dispatchOptions);
+ return JSON.parse(read.content[0].text) as Record<string, unknown>;
+ };
try {
const data = await callComputerTool(
@@ -613,14 +626,7 @@ export function createComputerMcpServer(
// frames, output handling and fresh element registration remain identical.
// A returned observation is evidence, never a reason to replay the input.
const observation = observe && !recovery && outcome.ok && !signal?.aborted
- ? JSON.parse((await handleCallTool('get_window_state', {
- ...observationScope,
- ...observe,
- pid: parsedData.pid,
- window_id: parsedData.window_id,
- include_screenshot: observe.include_screenshot ?? false,
- ...(typeof parsedData.session === 'string' ? { session: parsedData.session } : {}),
- }, signal, dispatchOptions)).content[0].text) as Record<string, unknown>
+ ? await readActionObservation()
: undefined;
if (postcondition && postcheck) {
const checked = computerResultOutcome("verify_state", postcheck.data);
@@ -682,17 +688,21 @@ export function createComputerMcpServer(
windowUnresolved && !signal?.aborted
? await rediscoverWindow(parsedData, { ...callContext, signal })
: undefined;
- const postcheck =
+ const shouldObserveUnknownAction =
!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;
+ (err as { outcomeUnknown?: boolean })?.outcomeUnknown;
+ const observation = observe && shouldObserveUnknownAction
+ ? await readActionObservation()
+ : undefined;
+ const postcheck = !observe && shouldObserveUnknownAction
+ ? await checkActionState(parsedData, postcondition, {
+ ...callContext,
+ signal,
+ })
+ : undefined;
const installedDiscovery =
name === "launch_app" &&
!signal?.aborted &&
@@ -807,6 +817,7 @@ export function createComputerMcpServer(
errorCode,
...(recovery ? { recovery } : {}),
...(postcheck ? { postcheck } : {}),
+ ...(observation ? { observation } : {}),
...(appDiscovery || installedDiscovery
? {
recovery: {
diff --git a/packages/lizi-mcps/src/computer/snapshot-tracker.ts b/packages/lizi-mcps/src/computer/snapshot-tracker.ts
index ec6bf69b96..93e5967c35 100644
--- a/packages/lizi-mcps/src/computer/snapshot-tracker.ts
+++ b/packages/lizi-mcps/src/computer/snapshot-tracker.ts
@@ -42,7 +42,6 @@ interface SnapshotMeta {
elements?: Map<string, number>;
/** Screen frames by element_index, to ask the OS what an action would land on. */
frames?: Map<number, ElementFrame>;
- scope?: WindowObservationScope;
}
export interface WindowObservationScope {
@@ -56,8 +55,11 @@ const MAX_TRACKED_WINDOWS = 256;
const MAX_TRACKED_SNAPSHOTS = 1024;
export class WindowSnapshotTracker {
- /** (session, pid, window_id) → 最新一代快照 id。 */
- private readonly latestByWindow = new Map<string, string>();
+ /** Scope survives invalidation; only snapshotId authorizes element reuse. */
+ private readonly latestByWindow = new Map<string, {
+ snapshotId?: string;
+ scope?: WindowObservationScope;
+ }>();
/** 快照 id → 元信息;保留近期历史以便区分 superseded 和 unknown。 */
private readonly metaById = new Map<string, SnapshotMeta>();
/** driver 观察 id / element_token 前缀 → 本层快照 id。 */
@@ -90,15 +92,14 @@ export class WindowSnapshotTracker {
}
this.seq += 1;
const id = `ws-${this.seq.toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
- this.latestByWindow.set(windowKey, id);
- this.metaById.set(id, { windowKey, sessionKey, pid, windowId, scope });
+ this.latestByWindow.set(windowKey, { snapshotId: id, scope });
+ this.metaById.set(id, { windowKey, sessionKey, pid, windowId });
return id;
}
/** Only the latest successful explicit read supplies a follow-up's traversal scope. */
observationScope(sessionId: string | undefined, pid: number, windowId: number): WindowObservationScope | undefined {
- const id = this.latestByWindow.get(this.windowKey(sessionId ?? '', pid, windowId));
- return id ? this.metaById.get(id)?.scope : undefined;
+ return this.latestByWindow.get(this.windowKey(sessionId ?? '', pid, windowId))?.scope;
}
/** A failed observation invalidates earlier IDs and aliases without issuing a usable ID. */
@@ -107,7 +108,8 @@ export class WindowSnapshotTracker {
pid: number,
windowId: number,
): void {
- this.latestByWindow.delete(this.windowKey(sessionId ?? '', pid, windowId));
+ const window = this.latestByWindow.get(this.windowKey(sessionId ?? '', pid, windowId));
+ if (window) window.snapshotId = undefined;
}
/** Register a host/driver snapshot id as an alias for the MCP-level guard id. */
@@ -173,7 +175,7 @@ export class WindowSnapshotTracker {
const key = sessionId ?? '';
const id = snapshotId !== undefined
? this.aliasToId.get(this.aliasKey(key, snapshotId)) ?? snapshotId
- : windowId !== undefined ? this.latestByWindow.get(this.windowKey(key, pid, windowId)) : undefined;
+ : windowId !== undefined ? this.latestByWindow.get(this.windowKey(key, pid, windowId))?.snapshotId : undefined;
const meta = id === undefined ? undefined : this.metaById.get(id);
return meta?.sessionKey === key && meta.pid === pid ? meta.frames?.get(index) : undefined;
}
@@ -213,10 +215,10 @@ export class WindowSnapshotTracker {
return {
ok: false,
reason: 'window_mismatch',
- latestSnapshotId: this.latestByWindow.get(meta.windowKey),
+ latestSnapshotId: this.latestByWindow.get(meta.windowKey)?.snapshotId,
};
}
- const latest = this.latestByWindow.get(meta.windowKey);
+ const latest = this.latestByWindow.get(meta.windowKey)?.snapshotId;
if (latest !== canonicalSnapshotId) {
return { ok: false, reason: 'superseded', latestSnapshotId: latest };
}