Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): guard simulator replay and access races

JiangJiahaoade6d8ede6b9
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 eeb74d6fcd..a8d7f0ba21 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
@@ -2464,6 +2464,36 @@ describe('computer mcp integration', () => {
expect(spawnMock).toHaveBeenCalledTimes(1);
});
+ it('bypasses the process snapshot cache when a routing guard requests fresh provenance', async () => {
+ const deps = getComputerMcpDeps();
+ mockProcessSnapshotSpawn([{
+ pid: 687,
+ parentPid: 1,
+ name: 'Code',
+ command: '/Applications/Visual Studio Code.app/Contents/MacOS/Electron',
+ }]);
+ mockProcessSnapshotSpawn([{
+ pid: 687,
+ parentPid: 1,
+ name: 'Simulator',
+ command:
+ '/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator',
+ }]);
+
+ await expect(deps.resolveProcessIdentity?.(687)).resolves.toMatchObject({
+ pid: 687,
+ command: '/Applications/Visual Studio Code.app/Contents/MacOS/Electron',
+ });
+ await expect(
+ deps.resolveProcessIdentity?.(687, { forceFresh: true }),
+ ).resolves.toMatchObject({
+ pid: 687,
+ command:
+ '/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator',
+ });
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+ });
+
it('closes active MCP sessions and blocks tool dispatch while permission onboarding is paused', async () => {
setPlatform('darwin');
mcpCallToolMock
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-renderer-access.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-renderer-access.test.ts
index c856d141e6..fc4fdf1aed 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-renderer-access.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-renderer-access.test.ts
@@ -178,6 +178,35 @@ describe('IOSSimulatorRendererAccessRegistry', () => {
expect(registry.hasAccess(sidebar.target, 'session-b')).toBe(false);
});
+ it('does not let an older sidebar confirmation overwrite a newly inherited Host grant', async () => {
+ const registry = new IOSSimulatorRendererAccessRegistry();
+ const main = fakeWebContents(53);
+ const sidebar = fakeWebContents(54);
+ const deferred: { resolve?: (confirmed: boolean) => void } = {};
+ registry.configureResolver(() => ({ grantTargets: [main.target], focusTarget: main.target }));
+ registry.grantAndFocus('session-b');
+ registry.configureResolver(() => ({
+ grantTargets: [main.target, sidebar.target],
+ focusTarget: sidebar.target,
+ }));
+ registry.configureConfirmation(
+ () =>
+ new Promise<boolean>((resolve) => {
+ deferred.resolve = resolve;
+ }),
+ );
+
+ const pending = registry.requestAccess('session-a', sidebar.target);
+ expect(registry.inheritAccess(main.target, sidebar.target)).toBe(true);
+ deferred.resolve?.(true);
+
+ await expect(pending).resolves.toBe(false);
+ expect(registry.hasAccess(main.target, 'session-a')).toBe(false);
+ expect(registry.hasAccess(sidebar.target, 'session-a')).toBe(false);
+ expect(registry.hasAccess(main.target, 'session-b')).toBe(true);
+ expect(registry.hasAccess(sidebar.target, 'session-b')).toBe(true);
+ });
+
it('requires the exact WebContents object even when a numeric id is reused', () => {
const registry = new IOSSimulatorRendererAccessRegistry();
const original = fakeWebContents(61);
diff --git a/apps/desktop/src/main/mcp-integrations/computer.ts b/apps/desktop/src/main/mcp-integrations/computer.ts
index bcfcd7e40c..571a9d2af7 100644
--- a/apps/desktop/src/main/mcp-integrations/computer.ts
+++ b/apps/desktop/src/main/mcp-integrations/computer.ts
@@ -3462,10 +3462,11 @@ export function getComputerMcpDeps(options: ComputerMcpDepsOptions = {}): Comput
await ensureRuntime();
return getComputerDriverStatus();
},
- resolveProcessIdentity: async (pid) => {
- let processSnapshot = await readProcessSnapshotResult();
+ resolveProcessIdentity: async (pid, resolveOptions) => {
+ const forceFresh = resolveOptions?.forceFresh === true;
+ let processSnapshot = await readProcessSnapshotResult({ forceFresh });
let processInfo = processSnapshot.processes.get(pid);
- if (!processInfo) {
+ if (!processInfo && !forceFresh) {
processSnapshot = await readProcessSnapshotResult({ forceFresh: true });
processInfo = processSnapshot.processes.get(pid);
}
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-renderer-access.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-renderer-access.ts
index 7ed964dc95..c005179b1b 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator-renderer-access.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-renderer-access.ts
@@ -175,6 +175,10 @@ export class IOSSimulatorRendererAccessRegistry {
}
const existing = this.grants.get(target.id);
if (existing?.target === target && existing.generation === source.generation) return true;
+ // Inheritance is an authoritative Host decision just like grantTargets.
+ // Invalidate a manual confirmation that started before this detached
+ // target was bound, including its first inherited grant.
+ this.bumpTargetEpoch(target.id);
const revoked = existing ? this.removeGeneration(existing.generation) : [];
this.grants.set(target.id, {
sessionId: source.sessionId,
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx
index 6c6442476b..cc385c2f19 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx
@@ -2292,7 +2292,13 @@ function ActionButton({
aria-describedby={describedBy}
className="inline-flex h-8 shrink-0 select-none items-center gap-1.5 rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 text-[11px] text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-default disabled:opacity-50"
>
- <Icon size={12} className={spinning ? 'animate-spin' : undefined} aria-hidden="true" />
+ {spinning ? (
+ <span className="inline-flex animate-spin motion-reduce:animate-none" aria-hidden="true">
+ <Icon size={12} />
+ </span>
+ ) : (
+ <Icon size={12} aria-hidden="true" />
+ )}
{label}
</button>
);
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx
index c3e431e724..554c7caec6 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx
@@ -329,6 +329,35 @@ describe('IOSSimulatorTabBody', () => {
expect(screen.queryByText('rightSidebar.iosSimulator.accessRequiredTitle')).toBeNull();
});
+ it('animates the access loader on an HTML wrapper instead of the SVG', async () => {
+ const api = installStatus(readyStatus());
+ api.status.mockRejectedValueOnce(
+ new Error(
+ 'Error invoking remote method: Error: [PERMISSION_DENIED] iOS Simulator access is limited to the current task',
+ ),
+ );
+ api.requestAccess.mockImplementationOnce(
+ () => new Promise<IOSSimulatorAccessRequestResult>(() => undefined),
+ );
+
+ render(<IOSSimulatorTabBody state={{ instanceId: null }} ctx={ctx} />);
+ fireEvent.click(
+ await screen.findByRole('button', {
+ name: 'rightSidebar.iosSimulator.allowTaskAccess',
+ }),
+ );
+
+ const button = await screen.findByRole('button', {
+ name: 'rightSidebar.iosSimulator.requestingAccess',
+ });
+ const wrapper = button.querySelector('span.animate-spin');
+ const icon = wrapper?.querySelector('svg');
+ expect(wrapper).toBeTruthy();
+ expect(wrapper?.classList.contains('motion-reduce:animate-none')).toBe(true);
+ expect(icon).toBeTruthy();
+ expect(icon?.classList.contains('animate-spin')).toBe(false);
+ });
+
it('keeps the access action visible when native confirmation is cancelled', async () => {
const api = installStatus(readyStatus());
api.status.mockRejectedValueOnce(
diff --git a/packages/lizi-mcps/src/computer/computerMcpServer.test.ts b/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
index 258cc0620a..1f47265f19 100644
--- a/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
+++ b/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
@@ -13,6 +13,22 @@ async function makeWorkingDir(): Promise<string> {
return fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'computer-wd-')));
}
+async function writeTrajectory(
+ root: string,
+ actions: Array<{ tool: string; arguments?: Record<string, unknown> }>,
+ directoryName = 'rec',
+): Promise<string> {
+ const directory = path.join(root, directoryName);
+ await Promise.all(
+ actions.map(async (action, index) => {
+ const turn = path.join(directory, `turn-${String(index + 1).padStart(5, '0')}`);
+ await fs.mkdir(turn, { recursive: true });
+ await fs.writeFile(path.join(turn, 'action.json'), JSON.stringify(action), 'utf8');
+ }),
+ );
+ return directory;
+}
+
function textPayload(result: unknown): unknown {
const content = (result as { content: Array<{ type: string; text?: string }> }).content;
const first = content[0];
@@ -1087,29 +1103,657 @@ describe('createComputerMcpServer', () => {
await h.cleanup();
});
- it('dispatches replay trajectory tool (dir constrained to workingDir)', async () => {
+ it('replays a validated trajectory through Cindy action dispatch', async () => {
const deps: ComputerMcpDeps = {
getStatus: vi.fn(),
callTool: vi.fn(async () => ({ ok: true })),
};
const root = await makeWorkingDir();
+ await writeTrajectory(root, [
+ {
+ tool: 'click',
+ arguments: { pid: 123, window_id: 7, x: 10, y: 20 },
+ },
+ ]);
const h = await makeHarness(deps, {
getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
});
- await h.client.callTool({
+ const payload = textPayload(
+ await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'rec', delay_ms: 0, stop_on_error: false },
+ },
+ }),
+ ) as {
+ ok: boolean;
+ data: { attempted: number; succeeded: number; failed: number };
+ };
+
+ expect(payload).toMatchObject({
+ ok: true,
+ data: { attempted: 1, succeeded: 1, failed: 0 },
+ });
+ expect(deps.callTool).toHaveBeenCalledWith(
+ 'click',
+ { pid: 123, window_id: 7, x: 10, y: 20 },
+ { agentKind: 'claude-code' },
+ );
+ expect(deps.callTool).not.toHaveBeenCalledWith(
+ 'replay_trajectory',
+ expect.anything(),
+ expect.anything(),
+ );
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it.skipIf(process.platform === 'win32')(
+ 'replays inside a workingDir reached through a symbolic link',
+ async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const container = await makeWorkingDir();
+ const realWorkingDir = path.join(container, 'real-workspace');
+ const linkedWorkingDir = path.join(container, 'linked-workspace');
+ await fs.mkdir(realWorkingDir);
+ await fs.symlink(realWorkingDir, linkedWorkingDir, 'dir');
+ await writeTrajectory(realWorkingDir, [
+ {
+ tool: 'get_window_state',
+ arguments: {
+ pid: 121,
+ window_id: 1,
+ screenshot_out_file: 'screens/state.png',
+ },
+ },
+ ]);
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({
+ agentKind: 'claude-code',
+ workingDir: linkedWorkingDir,
+ }),
+ });
+
+ const payload = textPayload(await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'rec', delay_ms: 0 },
+ },
+ })) as { ok: boolean; data: { succeeded: number } };
+
+ expect(payload).toMatchObject({ ok: true, data: { succeeded: 1 } });
+ expect(deps.callTool).toHaveBeenCalledWith(
+ 'get_window_state',
+ {
+ pid: 121,
+ window_id: 1,
+ screenshot_out_file: path.join(realWorkingDir, 'screens', 'state.png'),
+ },
+ { agentKind: 'claude-code' },
+ );
+ await h.cleanup();
+ await fs.rm(container, { recursive: true, force: true });
+ },
+ );
+
+ it('preflights every turn before replay and blocks a later Simulator action', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ resolveProcessIdentity: vi.fn(async (pid) =>
+ pid === 202
+ ? {
+ pid,
+ command:
+ '/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator',
+ }
+ : { pid, name: 'Code' },
+ ),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ await writeTrajectory(root, [
+ { tool: 'click', arguments: { pid: 101, window_id: 1, x: 10, y: 20 } },
+ { tool: 'click', arguments: { pid: 202, window_id: 2, x: 30, y: 40 } },
+ ]);
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
+ });
+
+ const result = await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'rec', delay_ms: 0, stop_on_error: false },
+ },
+ });
+
+ expect(textPayload(result)).toMatchObject({
+ ok: false,
+ errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',
+ data: { blocked_target: 'Simulator.app' },
+ });
+ expect(result.isError).toBe(true);
+ expect(deps.callTool).not.toHaveBeenCalled();
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it.each([
+ [
+ 'Xcode hotkey',
+ { tool: 'hotkey', arguments: { pid: 303, keys: ['cmd', 'r'] } },
+ { pid: 303, name: 'Xcode' },
+ 'Xcode',
+ ],
+ [
+ 'Simulator launch',
+ { tool: 'launch_app', arguments: { name: 'Simulator' } },
+ { pid: 404, name: 'Code' },
+ 'Simulator.app',
+ ],
+ ])(
+ 'blocks %s embedded in a manually authored trajectory',
+ async (_label, action, identity, target) => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ resolveProcessIdentity: vi.fn(async () => identity),
+ callTool: vi.fn(),
+ };
+ const root = await makeWorkingDir();
+ await writeTrajectory(root, [action]);
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({
+ agentKind: 'claude-code',
+ workingDir: root,
+ }),
+ });
+
+ const result = await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'rec', delay_ms: 0 },
+ },
+ });
+
+ expect(textPayload(result)).toMatchObject({
+ ok: false,
+ errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',
+ data: { blocked_target: target },
+ });
+ expect(deps.callTool).not.toHaveBeenCalled();
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ },
+ );
+
+ it('does not classify trajectory paths or typed text as an external Simulator target', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ resolveProcessIdentity: vi.fn(async (pid) => ({ pid, name: 'Code' })),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ await writeTrajectory(
+ root,
+ [
+ {
+ tool: 'type_text',
+ arguments: { pid: 505, text: 'Simulator.app is text only' },
+ },
+ ],
+ 'Simulator-recording',
+ );
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
+ });
+
+ const payload = textPayload(
+ await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'Simulator-recording', delay_ms: 0 },
+ },
+ }),
+ ) as { ok: boolean; data: { succeeded: number } };
+
+ expect(payload).toMatchObject({ ok: true, data: { succeeded: 1 } });
+ expect(deps.callTool).toHaveBeenCalledWith(
+ 'type_text',
+ {
+ pid: 505,
+ text: 'Simulator.app is text only',
+ },
+ { agentKind: 'claude-code' },
+ );
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it('re-resolves process identity immediately before each recorded action', async () => {
+ const resolveProcessIdentity = vi
+ .fn()
+ .mockResolvedValueOnce({ pid: 606, name: 'Code' })
+ .mockResolvedValueOnce({
+ pid: 606,
+ bundleId: 'com.apple.iphonesimulator',
+ });
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ resolveProcessIdentity,
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ await writeTrajectory(root, [
+ { tool: 'click', arguments: { pid: 606, window_id: 6, x: 10, y: 20 } },
+ ]);
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
+ });
+
+ const payload = textPayload(
+ await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'rec', delay_ms: 0 },
+ },
+ }),
+ ) as {
+ ok: boolean;
+ data: {
+ attempted: number;
+ failed: number;
+ first_failure?: { error?: string };
+ };
+ };
+
+ expect(payload).toMatchObject({
+ ok: true,
+ data: { attempted: 1, failed: 1 },
+ });
+ expect(payload.data.first_failure?.error).toContain('EMBEDDED_IOS_SIMULATOR_PREFERRED');
+ expect(resolveProcessIdentity).toHaveBeenCalledTimes(2);
+ expect(resolveProcessIdentity).toHaveBeenNthCalledWith(1, 606);
+ expect(resolveProcessIdentity).toHaveBeenNthCalledWith(2, 606, { forceFresh: true });
+ expect(deps.callTool).not.toHaveBeenCalled();
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it('executes the immutable preflight snapshot when the action file changes later', async () => {
+ const root = await makeWorkingDir();
+ const trajectory = await writeTrajectory(root, [
+ { tool: 'type_text', arguments: { pid: 616, text: 'original text' } },
+ ]);
+ const actionPath = path.join(trajectory, 'turn-00001', 'action.json');
+ const resolveProcessIdentity = vi.fn(async (pid: number) => {
+ if (resolveProcessIdentity.mock.calls.length === 1) {
+ await fs.writeFile(
+ actionPath,
+ JSON.stringify({ tool: 'launch_app', arguments: { name: 'Simulator' } }),
+ 'utf8',
+ );
+ }
+ return { pid, name: 'Code' };
+ });
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ resolveProcessIdentity,
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
+ });
+
+ const payload = textPayload(await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'rec', delay_ms: 0 },
+ },
+ })) as { ok: boolean; data: { succeeded: number } };
+
+ expect(payload).toMatchObject({ ok: true, data: { succeeded: 1 } });
+ expect(deps.callTool).toHaveBeenCalledWith(
+ 'type_text',
+ { pid: 616, text: 'original text' },
+ { agentKind: 'claude-code' },
+ );
+ expect(deps.callTool).not.toHaveBeenCalledWith('launch_app', expect.anything());
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it('fails replay closed when host process provenance is unavailable', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ await writeTrajectory(root, [
+ { tool: 'click', arguments: { pid: 707, window_id: 7, x: 10, y: 20 } },
+ ]);
+ const h = await makeHarness(
+ deps,
+ {
+ getSessionContext: () => ({
+ agentKind: 'claude-code',
+ workingDir: root,
+ }),
+ },
+ { injectDefaultProcessResolver: false },
+ );
+
+ const result = await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'rec', delay_ms: 0, stop_on_error: false },
+ },
+ });
+
+ expect(textPayload(result)).toMatchObject({
+ ok: false,
+ errorCode: 'TARGET_PROVENANCE_UNAVAILABLE',
+ });
+ expect(result.isError).toBe(true);
+ expect(deps.callTool).not.toHaveBeenCalled();
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it.skipIf(process.platform === 'win32')(
+ 'rejects a recorded turn that escapes through a symlink',
+ async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ const outside = await makeWorkingDir();
+ await fs.mkdir(path.join(root, 'rec'), { recursive: true });
+ await fs.writeFile(
+ path.join(outside, 'action.json'),
+ JSON.stringify({ tool: 'get_screen_size', arguments: {} }),
+ 'utf8',
+ );
+ await fs.symlink(outside, path.join(root, 'rec', 'turn-00001'), 'dir');
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({
+ agentKind: 'claude-code',
+ workingDir: root,
+ }),
+ });
+
+ const result = await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'rec', delay_ms: 0 },
+ },
+ });
+
+ expect(textPayload(result)).toMatchObject({
+ ok: false,
+ errorCode: 'TRAJECTORY_VALIDATION_FAILED',
+ data: { turn: 'turn-00001' },
+ });
+ expect(deps.callTool).not.toHaveBeenCalled();
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ await fs.rm(outside, { recursive: true, force: true });
+ },
+ );
+
+ it.skipIf(process.platform === 'win32')(
+ 'rejects a symbolic-link action file even when its target stays in the task',
+ async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ const turn = path.join(root, 'rec', 'turn-00001');
+ await fs.mkdir(turn, { recursive: true });
+ await fs.writeFile(
+ path.join(root, 'safe-action.json'),
+ JSON.stringify({ tool: 'get_screen_size', arguments: {} }),
+ 'utf8',
+ );
+ await fs.symlink(path.join(root, 'safe-action.json'), path.join(turn, 'action.json'));
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
+ });
+
+ const result = await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'rec', delay_ms: 0 },
+ },
+ });
+
+ expect(textPayload(result)).toMatchObject({
+ ok: false,
+ errorCode: 'TRAJECTORY_VALIDATION_FAILED',
+ data: { turn: 'turn-00001' },
+ });
+ expect(deps.callTool).not.toHaveBeenCalled();
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ },
+ );
+
+ it('rejects trajectories whose aggregate action files exceed the memory budget', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ resolveProcessIdentity: vi.fn(async (pid) => ({ pid, name: 'Code' })),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ await writeTrajectory(
+ root,
+ Array.from({ length: 9 }, (_, index) => ({
+ tool: 'type_text',
+ arguments: { pid: 800 + index, text: 'x'.repeat(240_000) },
+ })),
+ );
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
+ });
+
+ const result = await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'rec', delay_ms: 0, stop_on_error: false },
+ },
+ });
+
+ expect(textPayload(result)).toMatchObject({
+ ok: false,
+ errorCode: 'TRAJECTORY_VALIDATION_FAILED',
+ data: { turn: 'turn-00009' },
+ });
+ expect(deps.callTool).not.toHaveBeenCalled();
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it('bounds accumulated replay result summaries', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => 'x'.repeat(10_000)),
+ };
+ const root = await makeWorkingDir();
+ await writeTrajectory(
+ root,
+ Array.from({ length: 40 }, () => ({ tool: 'get_screen_size', arguments: {} })),
+ );
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
+ });
+
+ const payload = textPayload(await h.client.callTool({
name: 'call_tool',
arguments: {
name: 'replay_trajectory',
- args: { dir: 'rec', delay_ms: 100, stop_on_error: false },
+ args: { dir: 'rec', delay_ms: 0 },
},
+ })) as { data: { turns: Array<{ result_summary: string }> } };
+
+ expect(payload.data.turns).toHaveLength(40);
+ expect(payload.data.turns.every((turn) => turn.result_summary.length <= 2_048)).toBe(true);
+ expect(
+ payload.data.turns.reduce((total, turn) => total + turn.result_summary.length, 0),
+ ).toBeLessThanOrEqual(64 * 1024);
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it('preserves recorded tool summaries instead of exposing Cindy envelopes', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi
+ .fn()
+ .mockResolvedValueOnce('screen is 1440x900')
+ .mockRejectedValueOnce(new Error('driver capture failed')),
+ };
+ const root = await makeWorkingDir();
+ await writeTrajectory(root, [
+ { tool: 'get_screen_size', arguments: {} },
+ { tool: 'get_screen_size', arguments: {} },
+ ]);
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
+ });
+
+ const payload = textPayload(await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'rec', delay_ms: 0, stop_on_error: false },
+ },
+ })) as {
+ data: {
+ turns: Array<{ result_summary: string }>;
+ first_failure: { error: string };
+ };
+ };
+
+ expect(payload.data.turns.map((turn) => turn.result_summary)).toEqual([
+ 'screen is 1440x900',
+ 'driver capture failed',
+ ]);
+ expect(payload.data.first_failure.error).toBe('driver capture failed');
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it('stops dispatching recorded actions after the MCP request is cancelled', async () => {
+ const controller = new AbortController();
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => {
+ controller.abort();
+ return { ok: true };
+ }),
+ };
+ const root = await makeWorkingDir();
+ await writeTrajectory(root, [
+ { tool: 'get_screen_size', arguments: {} },
+ { tool: 'get_screen_size', arguments: {} },
+ ]);
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
});
- expect(deps.callTool).toHaveBeenCalledWith('replay_trajectory', {
- dir: path.join(root, 'rec'),
- delay_ms: 100,
- stop_on_error: false,
- }, { agentKind: 'claude-code' });
+ await expect(
+ h.client.callTool(
+ {
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'rec', delay_ms: 100, stop_on_error: false },
+ },
+ },
+ undefined,
+ { signal: controller.signal },
+ ),
+ ).rejects.toThrow();
+ await new Promise((resolve) => setTimeout(resolve, 150));
+
+ expect(deps.callTool).toHaveBeenCalledTimes(1);
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it('rejects nested trajectory replay before any action is dispatched', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
+ };
+ const root = await makeWorkingDir();
+ await writeTrajectory(root, [
+ { tool: 'replay_trajectory', arguments: { dir: 'another-recording' } },
+ ]);
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
+ });
+
+ const result = await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'rec', delay_ms: 0 },
+ },
+ });
+
+ expect(textPayload(result)).toMatchObject({
+ ok: false,
+ errorCode: 'TRAJECTORY_VALIDATION_FAILED',
+ data: { turn: 'turn-00001' },
+ });
+ expect(deps.callTool).not.toHaveBeenCalled();
+ await h.cleanup();
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it('fails closed before replay when a recorded action is malformed', async () => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(),
+ };
+ const root = await makeWorkingDir();
+ const turn = path.join(root, 'rec', 'turn-00001');
+ await fs.mkdir(turn, { recursive: true });
+ await fs.writeFile(path.join(turn, 'action.json'), '{not-json', 'utf8');
+ const h = await makeHarness(deps, {
+ getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
+ });
+
+ const result = await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'replay_trajectory',
+ args: { dir: 'rec', delay_ms: 0 },
+ },
+ });
+
+ expect(textPayload(result)).toMatchObject({
+ ok: false,
+ errorCode: 'TRAJECTORY_VALIDATION_FAILED',
+ data: { turn: 'turn-00001' },
+ });
+ expect(deps.callTool).not.toHaveBeenCalled();
await h.cleanup();
await fs.rm(root, { recursive: true, force: true });
});
diff --git a/packages/lizi-mcps/src/computer/server.ts b/packages/lizi-mcps/src/computer/server.ts
index 6cff8f3d4b..e490e80246 100644
--- a/packages/lizi-mcps/src/computer/server.ts
+++ b/packages/lizi-mcps/src/computer/server.ts
@@ -1,3 +1,5 @@
+import { constants as fsConstants, promises as fs } from 'node:fs';
+import path from 'node:path';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { jsonObjectArg } from '../json-object-arg.js';
@@ -100,6 +102,43 @@ const TARGETED_MUTATING_TOOLS = new Set<ComputerMcpToolName>([
'scroll',
]);
+const MAX_REPLAY_TURNS = 1_000;
+const MAX_REPLAY_DIRECTORY_ENTRIES = 10_000;
+const MAX_REPLAY_ACTION_BYTES = 256 * 1024;
+const MAX_REPLAY_TOTAL_ACTION_BYTES = 2 * 1024 * 1024;
+const MAX_REPLAY_TOTAL_DELAY_MS = 5 * 60 * 1_000;
+const MAX_REPLAY_WALL_CLOCK_MS = 10 * 60 * 1_000;
+const MAX_REPLAY_RESULT_SUMMARY_CHARS = 2_048;
+const MAX_REPLAY_TOTAL_RESULT_CHARS = 64 * 1024;
+const REPLAY_READ_FLAGS =
+ fsConstants.O_RDONLY |
+ (process.platform === 'win32'
+ ? 0
+ : (fsConstants.O_NONBLOCK ?? 0) | (fsConstants.O_NOFOLLOW ?? 0));
+
+interface ReplayTrajectoryAction {
+ turn: string;
+ tool: ComputerMcpToolName;
+ args: Record<string, unknown>;
+}
+
+interface ComputerDispatchOptions {
+ forceFreshProcessIdentity?: boolean;
+ pathWorkingDirOverride?: string;
+}
+
+type ComputerMcpTextResult = ReturnType<typeof textResult>;
+
+type ReplayTrajectoryPreparation =
+ | { error: ComputerMcpTextResult }
+ | {
+ directory: string;
+ workingRoot: string;
+ actions: ReplayTrajectoryAction[];
+ delayMs: number;
+ stopOnError: boolean;
+ };
+
function serializeJsonSchema(schema: z.ZodObject<z.ZodRawShape>): unknown {
try {
return z.toJSONSchema(schema);
@@ -277,8 +316,8 @@ export function createComputerMcpServer(
name: z.enum(COMPUTER_TOOL_NAMES).describe('Tool name from list_tools'),
args: jsonObjectArg('Arguments object for the selected tool'),
},
- async ({ name, args }) => {
- const result = await handleCallTool(name, args);
+ async ({ name, args }, extra) => {
+ const result = await handleCallTool(name, args, extra.signal);
// errorCode 遥测:UNKNOWN_TOOL / INVALID_ARGS / COMPUTER_DRIVER_ERROR 返回给
// 模型自纠之前在这里落一条日志(见 tool-error-telemetry.ts)。
logToolResultErrorCode({
@@ -292,7 +331,12 @@ export function createComputerMcpServer(
},
);
- async function handleCallTool(name: string, args: Record<string, unknown> | undefined) {
+ async function handleCallTool(
+ name: string,
+ args: Record<string, unknown> | undefined,
+ signal?: AbortSignal,
+ dispatchOptions?: ComputerDispatchOptions,
+ ) {
const def = getComputerTool(name);
if (!def) {
return textResult({ ok: false, errorCode: 'UNKNOWN_TOOL', data: { requested: name } }, true);
@@ -307,13 +351,29 @@ export function createComputerMcpServer(
if (!parsed.success) {
return validationError(name, schema, parsed.error);
}
+ if (signal?.aborted) return replayCancelledResult();
const callContext = readCallContext(options);
const sessionId = callContext?.sessionId;
const parsedData = parsed.data as Record<string, unknown>;
+ // Resolve every local path before a guard reads it. In particular,
+ // trajectory inspection must never follow a model-supplied path outside
+ // the current task working directory.
+ const pathGuardError = await guardPathArgs(
+ name as ComputerMcpToolName,
+ parsedData,
+ dispatchOptions?.pathWorkingDirOverride,
+ );
+ if (pathGuardError) return pathGuardError;
+
+ if (name === 'replay_trajectory') {
+ return replayTrajectoryWithGuards(parsedData, signal);
+ }
+
const externalIosGuard = await guardExternalIosDesktopWorkflow(
name as ComputerMcpToolName,
parsedData,
+ dispatchOptions?.forceFreshProcessIdentity === true,
);
if (externalIosGuard) return externalIosGuard;
@@ -325,11 +385,6 @@ export function createComputerMcpServer(
// snapshot_id 是 MCP 层的护栏参数,driver 不认识,派发前剥掉。
delete parsedData.snapshot_id;
- // 路径边界护栏:把 LLM 指定的本地文件路径(截图 / 调试图 / 录制目录等)
- // 约束到当前 session workingDir,阻断 prompt 注入的任意写/读(见 COMPUTER_PATH_ARGS)。
- const pathGuardError = await guardPathArgs(name as ComputerMcpToolName, parsedData);
- if (pathGuardError) return pathGuardError;
-
const parsedArgs = withSessionArg(
name as ComputerMcpToolName,
parsedData,
@@ -370,6 +425,7 @@ export function createComputerMcpServer(
async function guardExternalIosDesktopWorkflow(
name: ComputerMcpToolName,
parsedData: Record<string, unknown>,
+ forceFreshProcessIdentity = false,
) {
if (name === 'launch_app') {
const target = classifyExternalIosTarget({
@@ -392,22 +448,32 @@ export function createComputerMcpServer(
) {
return null;
}
+ return guardMutatingProcessTarget(parsedData.pid, name, forceFreshProcessIdentity);
+ }
+
+ async function guardMutatingProcessTarget(
+ pid: number,
+ tool: ComputerMcpToolName,
+ forceFreshProcessIdentity = false,
+ ) {
if (!deps.resolveProcessIdentity) return targetProvenanceUnavailableResult();
let identity;
try {
- identity = await deps.resolveProcessIdentity(parsedData.pid);
+ identity = forceFreshProcessIdentity
+ ? await deps.resolveProcessIdentity(pid, { forceFresh: true })
+ : await deps.resolveProcessIdentity(pid);
} catch (err) {
deps.logger?.warn('failed to resolve Computer Use target process for iOS routing guard', {
- pid: parsedData.pid,
- tool: name,
+ pid,
+ tool,
error: err instanceof Error ? err.message : String(err),
});
return targetProvenanceUnavailableResult();
}
if (
!identity ||
- identity.pid !== parsedData.pid ||
+ identity.pid !== pid ||
![identity.name, identity.command, identity.executable, identity.bundleId].some(
(value) => typeof value === 'string' && value.trim().length > 0,
)
@@ -420,6 +486,446 @@ export function createComputerMcpServer(
return embeddedIosSimulatorPreferredResult(target === 'xcode' ? 'Xcode' : 'Simulator.app');
}
+ function trajectoryValidationFailedResult(message: string, turn?: string) {
+ return textResult(
+ {
+ ok: false,
+ errorCode: 'TRAJECTORY_VALIDATION_FAILED',
+ data: {
+ message,
+ ...(turn ? { turn } : {}),
+ },
+ },
+ true,
+ );
+ }
+
+ function replayCancelledResult() {
+ return textResult(
+ {
+ ok: false,
+ errorCode: 'REQUEST_CANCELLED',
+ data: { message: 'Trajectory replay stopped because the request was cancelled.' },
+ },
+ true,
+ );
+ }
+
+ function replayBudgetExceededResult() {
+ return textResult(
+ {
+ ok: false,
+ errorCode: 'REPLAY_BUDGET_EXCEEDED',
+ data: { message: 'Trajectory replay exceeded Cindy\'s bounded execution budget.' },
+ },
+ true,
+ );
+ }
+
+ async function readBoundedReplayAction(
+ actionFile: Awaited<ReturnType<typeof fs.open>>,
+ signal?: AbortSignal,
+ ): Promise<{ text: string; bytes: number }> {
+ const chunks: Buffer[] = [];
+ let position = 0;
+ while (position <= MAX_REPLAY_ACTION_BYTES) {
+ if (signal?.aborted) throw new DOMException('Replay cancelled', 'AbortError');
+ const remaining = MAX_REPLAY_ACTION_BYTES + 1 - position;
+ const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, remaining));
+ const { bytesRead } = await actionFile.read(chunk, 0, chunk.length, position);
+ if (bytesRead === 0) break;
+ chunks.push(chunk.subarray(0, bytesRead));
+ position += bytesRead;
+ }
+ if (position > MAX_REPLAY_ACTION_BYTES) {
+ throw new Error('Recorded action exceeds the per-action byte limit.');
+ }
+ return {
+ text: Buffer.concat(chunks, position).toString('utf8'),
+ bytes: position,
+ };
+ }
+
+ async function waitForReplayDelay(delayMs: number, signal?: AbortSignal): Promise<boolean> {
+ if (delayMs <= 0) return signal?.aborted !== true;
+ return new Promise((resolve) => {
+ if (signal?.aborted) {
+ resolve(false);
+ return;
+ }
+ const timer = setTimeout(() => {
+ signal?.removeEventListener('abort', onAbort);
+ resolve(true);
+ }, delayMs);
+ const onAbort = () => {
+ clearTimeout(timer);
+ resolve(false);
+ };
+ signal?.addEventListener('abort', onAbort, { once: true });
+ });
+ }
+
+ async function prepareReplayTrajectory(
+ parsedData: Record<string, unknown>,
+ signal?: AbortSignal,
+ ): Promise<ReplayTrajectoryPreparation> {
+ const directory = parsedData.dir;
+ const workingDir = options.getSessionContext?.().workingDir ?? '';
+ if (typeof directory !== 'string' || !workingDir) {
+ return {
+ error: trajectoryValidationFailedResult(
+ 'Cindy could not safely resolve the trajectory directory.',
+ ),
+ };
+ }
+
+ let workingRoot: string;
+ let trajectoryRoot: string;
+ const candidates: string[] = [];
+ try {
+ workingRoot = await fs.realpath(workingDir);
+ // handleCallTool already constrained `directory` against the original
+ // workingDir spelling. Canonicalize both sides before comparing again so
+ // a legitimate symlinked workspace (including macOS /var -> /private/var)
+ // is not rejected by a lexical alias mismatch.
+ trajectoryRoot = await fs.realpath(directory);
+ await resolvePathInsideRoot(workingRoot, trajectoryRoot);
+
+ let entryCount = 0;
+ const trajectoryDirectory = await fs.opendir(trajectoryRoot);
+ for await (const entry of trajectoryDirectory) {
+ if (signal?.aborted) return { error: replayCancelledResult() };
+ entryCount += 1;
+ if (entryCount > MAX_REPLAY_DIRECTORY_ENTRIES) {
+ return {
+ error: trajectoryValidationFailedResult(
+ `Trajectory directory exceeds the ${MAX_REPLAY_DIRECTORY_ENTRIES}-entry safety limit.`,
+ ),
+ };
+ }
+ if (!entry.name.startsWith('turn-')) continue;
+ candidates.push(entry.name);
+ if (candidates.length > MAX_REPLAY_TURNS) {
+ return {
+ error: trajectoryValidationFailedResult(
+ `Trajectory exceeds the ${MAX_REPLAY_TURNS}-turn safety limit.`,
+ ),
+ };
+ }
+ }
+ candidates.sort();
+ } catch (error) {
+ if (signal?.aborted) return { error: replayCancelledResult() };
+ deps.logger?.warn('failed to inspect Computer Use trajectory directory', {
+ directory,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return {
+ error: trajectoryValidationFailedResult(
+ 'Cindy could not read the trajectory directory before replay.',
+ ),
+ };
+ }
+
+ const actions: ReplayTrajectoryAction[] = [];
+ let totalActionBytes = 0;
+ for (const turn of candidates) {
+ try {
+ if (signal?.aborted) return { error: replayCancelledResult() };
+ const turnPath = await resolvePathInsideRoot(
+ workingRoot,
+ path.join(trajectoryRoot, turn),
+ );
+ if (!(await fs.lstat(turnPath)).isDirectory()) {
+ return {
+ error: trajectoryValidationFailedResult(
+ 'Recorded turn must be a real directory, not a file or symbolic link.',
+ turn,
+ ),
+ };
+ }
+
+ const actionPath = await resolvePathInsideRoot(
+ workingRoot,
+ path.join(turnPath, 'action.json'),
+ );
+ if ((await fs.lstat(actionPath)).isSymbolicLink()) {
+ return {
+ error: trajectoryValidationFailedResult(
+ 'Recorded action must be a real file, not a symbolic link.',
+ turn,
+ ),
+ };
+ }
+ const canonicalActionPath = await fs.realpath(actionPath);
+ await resolvePathInsideRoot(workingRoot, canonicalActionPath);
+ const actionFile = await fs.open(actionPath, REPLAY_READ_FLAGS);
+ let actionText: string;
+ try {
+ const stat = await actionFile.stat();
+ if (!stat.isFile() || stat.size > MAX_REPLAY_ACTION_BYTES) {
+ return {
+ error: trajectoryValidationFailedResult(
+ 'The recorded action is not a bounded regular JSON file.',
+ turn,
+ ),
+ };
+ }
+ const currentCanonicalPath = await fs.realpath(actionPath);
+ await resolvePathInsideRoot(workingRoot, currentCanonicalPath);
+ const currentStat = await fs.stat(currentCanonicalPath);
+ if (currentStat.dev !== stat.dev || currentStat.ino !== stat.ino) {
+ return {
+ error: trajectoryValidationFailedResult(
+ 'The recorded action changed while Cindy was opening it.',
+ turn,
+ ),
+ };
+ }
+ const boundedAction = await readBoundedReplayAction(actionFile, signal);
+ totalActionBytes += boundedAction.bytes;
+ if (totalActionBytes > MAX_REPLAY_TOTAL_ACTION_BYTES) {
+ return {
+ error: trajectoryValidationFailedResult(
+ `Trajectory exceeds the ${MAX_REPLAY_TOTAL_ACTION_BYTES}-byte aggregate safety limit.`,
+ turn,
+ ),
+ };
+ }
+ actionText = boundedAction.text;
+ } finally {
+ await actionFile.close();
+ }
+
+ const rawAction: unknown = JSON.parse(actionText);
+ if (!rawAction || typeof rawAction !== 'object' || Array.isArray(rawAction)) {
+ return {
+ error: trajectoryValidationFailedResult(
+ 'The recorded action must be a JSON object.',
+ turn,
+ ),
+ };
+ }
+ const action = rawAction as Record<string, unknown>;
+ const tool = action.tool;
+ if (typeof tool !== 'string' || tool === 'replay_trajectory') {
+ return {
+ error: trajectoryValidationFailedResult(
+ 'Nested or unnamed trajectory replay actions are not allowed.',
+ turn,
+ ),
+ };
+ }
+ const definition = getComputerTool(tool);
+ if (!definition) {
+ return {
+ error: trajectoryValidationFailedResult(
+ `Recorded tool ${tool} is not exposed by this Cindy version.`,
+ turn,
+ ),
+ };
+ }
+ const toolName = tool as ComputerMcpToolName;
+ const rawArgs = action.arguments ?? {};
+ if (!rawArgs || typeof rawArgs !== 'object' || Array.isArray(rawArgs)) {
+ return {
+ error: trajectoryValidationFailedResult(
+ 'Recorded tool arguments must be a JSON object.',
+ turn,
+ ),
+ };
+ }
+ const normalized = normalizeCompatibilityArgs(tool, rawArgs as Record<string, unknown>);
+ if (normalized.conflict) {
+ return {
+ error: trajectoryValidationFailedResult(
+ `Recorded tool ${tool} contains conflicting compatibility arguments.`,
+ turn,
+ ),
+ };
+ }
+ const parsed = z.object(definition.inputShape).strict().safeParse(normalized.args);
+ if (!parsed.success) {
+ return {
+ error: trajectoryValidationFailedResult(
+ `Recorded tool ${tool} does not match the current Cindy schema.`,
+ turn,
+ ),
+ };
+ }
+ const args = parsed.data as Record<string, unknown>;
+ const nestedPathError = await guardPathArgs(toolName, args, workingRoot);
+ if (nestedPathError) return { error: nestedPathError };
+ const externalIosGuard = await guardExternalIosDesktopWorkflow(toolName, args);
+ if (externalIosGuard) return { error: externalIosGuard };
+ actions.push({ turn, tool: toolName, args });
+ } catch (error) {
+ if (signal?.aborted) return { error: replayCancelledResult() };
+ deps.logger?.warn('failed to validate Computer Use trajectory action', {
+ directory,
+ turn,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return {
+ error: trajectoryValidationFailedResult(
+ 'Cindy could not safely validate this recorded action.',
+ turn,
+ ),
+ };
+ }
+ }
+
+ if (actions.length === 0) {
+ return {
+ error: trajectoryValidationFailedResult(
+ 'No replayable turn directories were found in the trajectory.',
+ ),
+ };
+ }
+ const delayMs = typeof parsedData.delay_ms === 'number' ? parsedData.delay_ms : 500;
+ if (delayMs * Math.max(actions.length - 1, 0) > MAX_REPLAY_TOTAL_DELAY_MS) {
+ return {
+ error: trajectoryValidationFailedResult(
+ `Trajectory exceeds the ${MAX_REPLAY_TOTAL_DELAY_MS}-millisecond aggregate delay limit.`,
+ ),
+ };
+ }
+ return {
+ directory,
+ workingRoot,
+ actions,
+ delayMs,
+ stopOnError: parsedData.stop_on_error !== false,
+ };
+ }
+
+ function serializeReplaySummaryValue(value: unknown): string {
+ if (typeof value === 'string') return value;
+ try {
+ return JSON.stringify(value) ?? '';
+ } catch {
+ return String(value);
+ }
+ }
+
+ function replayResultSummary(result: ComputerMcpTextResult, maxChars: number): string {
+ const raw = result.content.find((block) => block.type === 'text')?.text ?? '';
+ let summary = raw;
+ try {
+ const payload: unknown = JSON.parse(raw);
+ if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
+ const envelope = payload as Record<string, unknown>;
+ const data = envelope.data;
+ if (envelope.ok === true && Object.hasOwn(envelope, 'data')) {
+ // Match the driver's replay contract: summarize the recorded tool's
+ // own result, not Cindy's surrounding { ok, tool, data } envelope.
+ summary = serializeReplaySummaryValue(data);
+ } else if (typeof envelope.errorCode === 'string') {
+ const message = data && typeof data === 'object' && !Array.isArray(data)
+ ? (data as Record<string, unknown>).message
+ : undefined;
+ if (envelope.errorCode === 'COMPUTER_DRIVER_ERROR' && typeof message === 'string') {
+ summary = message;
+ } else {
+ summary = typeof message === 'string'
+ ? `${envelope.errorCode}: ${message}`
+ : envelope.errorCode;
+ }
+ }
+ }
+ } catch {
+ // Preserve non-JSON text returned by an older or custom host.
+ }
+ if (summary.length <= maxChars) return summary;
+ if (maxChars <= 1) return summary.slice(0, maxChars);
+ return `${summary.slice(0, maxChars - 1)}…`;
+ }
+
+ async function replayTrajectoryWithGuards(
+ parsedData: Record<string, unknown>,
+ signal?: AbortSignal,
+ ) {
+ const prepared = await prepareReplayTrajectory(parsedData, signal);
+ if ('error' in prepared) return prepared.error;
+
+ const startedAt = Date.now();
+ let attempted = 0;
+ let succeeded = 0;
+ let failed = 0;
+ let resultSummaryChars = 0;
+ const turns: Array<{
+ turn: string;
+ tool: ComputerMcpToolName;
+ ok: boolean;
+ result_summary: string;
+ }> = [];
+ let firstFailure: { turn: string; tool: ComputerMcpToolName; error: string } | undefined;
+
+ for (const [index, action] of prepared.actions.entries()) {
+ if (signal?.aborted) return replayCancelledResult();
+ if (Date.now() - startedAt >= MAX_REPLAY_WALL_CLOCK_MS) {
+ return replayBudgetExceededResult();
+ }
+ attempted += 1;
+ // Re-enter Cindy's normal dispatch path immediately before every action.
+ // This closes both PID-reuse and mutable-action-file races that a single
+ // preflight followed by the driver's nested replay would leave open.
+ const result = await handleCallTool(action.tool, action.args, signal, {
+ forceFreshProcessIdentity: true,
+ // Preflight normalized nested path arguments against this canonical
+ // root. Reuse it so a symlink spelling of the session workingDir does
+ // not make those immutable absolute paths look lexically out of scope.
+ pathWorkingDirOverride: prepared.workingRoot,
+ });
+ if (signal?.aborted) return replayCancelledResult();
+ const isError = result.isError === true;
+ const summaryBudget = Math.max(
+ 0,
+ Math.min(
+ MAX_REPLAY_RESULT_SUMMARY_CHARS,
+ MAX_REPLAY_TOTAL_RESULT_CHARS - resultSummaryChars,
+ ),
+ );
+ const summary = replayResultSummary(result, summaryBudget);
+ resultSummaryChars += summary.length;
+ turns.push({
+ turn: action.turn,
+ tool: action.tool,
+ ok: !isError,
+ result_summary: summary,
+ });
+ if (isError) {
+ failed += 1;
+ firstFailure ??= {
+ turn: action.turn,
+ tool: action.tool,
+ error: summary,
+ };
+ if (prepared.stopOnError) break;
+ } else {
+ succeeded += 1;
+ }
+ if (index < prepared.actions.length - 1) {
+ const completedDelay = await waitForReplayDelay(prepared.delayMs, signal);
+ if (!completedDelay) return replayCancelledResult();
+ }
+ }
+
+ return textResult({
+ ok: true,
+ tool: 'replay_trajectory',
+ data: {
+ directory: prepared.directory,
+ attempted,
+ succeeded,
+ failed,
+ stop_on_error: prepared.stopOnError,
+ turns,
+ ...(firstFailure ? { first_failure: firstFailure } : {}),
+ },
+ });
+ }
+
function classifyExternalIosTarget(input: {
name?: unknown;
bundleId?: unknown;
@@ -488,10 +994,11 @@ export function createComputerMcpServer(
async function guardPathArgs(
name: ComputerMcpToolName,
parsedData: Record<string, unknown>,
+ workingDirOverride?: string,
) {
const argNames = COMPUTER_PATH_ARGS[name];
if (!argNames) return null;
- const workingDir = options.getSessionContext?.().workingDir ?? '';
+ const workingDir = workingDirOverride ?? options.getSessionContext?.().workingDir ?? '';
for (const key of argNames) {
const value = parsedData[key];
if (typeof value !== 'string' || value.length === 0) continue;
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index 460dd5880b..3d2aebfb35 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -604,10 +604,18 @@ export interface ComputerProcessIdentity {
bundleId?: string;
}
+export interface ComputerProcessIdentityResolveOptions {
+ /** Bypass any host-side process snapshot cache before a side effect. */
+ forceFresh?: boolean;
+}
+
export interface ComputerMcpDeps {
getStatus(): Promise<ComputerDriverStatus>;
/** Resolve process provenance without trusting model-supplied app labels. */
- resolveProcessIdentity?(pid: number): Promise<ComputerProcessIdentity | null>;
+ resolveProcessIdentity?(
+ pid: number,
+ options?: ComputerProcessIdentityResolveOptions,
+ ): Promise<ComputerProcessIdentity | null>;
callTool(
name: ComputerMcpToolName,
args: Record<string, unknown>,