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(ios-simulator): harden shell and WDA cancellation

JiangJiahao0fb8fa0adaf1
diff --git a/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts b/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts
index a52351d0f2..b6c88db7a3 100644
--- a/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts
@@ -71,6 +71,18 @@ describeMac('embedded iOS Simulator shell policy', () => {
'$(/usr/bin/xcrun --find simctl) shutdown DEVICE',
'/usr/bin/xc[r]un simctl shutdown DEVICE',
'TOOL=simctl; /usr/bin/xcrun "$TOOL" shutdown DEVICE',
+ 'A=sim; B=ctl; xcrun "$A$B" shutdown DEVICE',
+ 'A=sim; B=ctl; xcrun --sdk iphonesimulator "${A}${B}" erase DEVICE',
+ 'xcrun s{imc,foo}tl shutdown DEVICE',
+ 'A="default simctl"; xcrun --toolchain ${=A} shutdown DEVICE',
+ `bash -lc 'A="default simctl"; xcrun --toolchain $A shutdown DEVICE'`,
+ 'A=(default simctl); xcrun --toolchain "${(@)A}" shutdown DEVICE',
+ 'A="default simctl"; xcrun --toolchain "$=A" shutdown DEVICE',
+ 'A=(default simctl); xcrun --toolchain "$A[@]" shutdown DEVICE',
+ `bash -O extglob -lc 'xcrun @(simctl) shutdown DEVICE'`,
+ `zsh -o extendedglob -c 'xcrun ^foo shutdown DEVICE'`,
+ 'xcrun --sdk "$SDK" simctl list devices',
+ 'A=default; xcrun --toolchain "$A" swift --version',
'xargs /usr/bin/xcrun simctl shutdown DEVICE',
"find . -maxdepth 0 -exec /usr/bin/xcrun simctl shutdown DEVICE ';'",
`printf 'simctl shutdown DEVICE' | xargs /usr/bin/xcrun`,
@@ -127,7 +139,8 @@ PY`,
'xcrun simctl listapps DEVICE',
'xcrun simctl list "$DEVICE"',
'xcrun simctl getenv "$DEVICE" HOME',
- 'xcrun --sdk "$SDK" simctl list devices',
+ 'xcrun --sdk iphonesimulator simctl list devices',
+ 'xcrun swift --version',
'exec xcrun simctl list devices',
'command -p xcrun simctl listapps DEVICE',
"bash -lc 'xcrun simctl list devices'",
diff --git a/apps/desktop/src/main/maker-host/shell-command-policy.ts b/apps/desktop/src/main/maker-host/shell-command-policy.ts
index f6337bb89d..a1d5299a39 100644
--- a/apps/desktop/src/main/maker-host/shell-command-policy.ts
+++ b/apps/desktop/src/main/maker-host/shell-command-policy.ts
@@ -867,23 +867,36 @@ function containsShellConsumedLiteralBypass(command: string): boolean {
return false;
}
+function isLiteralXcrunBoundaryToken(token: string): boolean {
+ return /^[A-Za-z0-9_./:+-]+$/.test(token);
+}
+
function hasUnresolvedXcrunTool(tokens: string[]): boolean {
if (executableName(tokens[0]) !== 'xcrun') return false;
let index = 1;
while (index < tokens.length && tokens[index]!.startsWith('-')) {
const option = tokens[index]!;
- index +=
- option === '--sdk' || option === '-sdk' || option === '--toolchain' || option === '-toolchain'
- ? 2
- : 1;
+ if (/^(?:--sdk|-sdk|--toolchain|-toolchain)=/.test(option)) {
+ const value = option.slice(option.indexOf('=') + 1);
+ if (!isLiteralXcrunBoundaryToken(value)) return true;
+ index += 1;
+ continue;
+ }
+ if (
+ option === '--sdk' ||
+ option === '-sdk' ||
+ option === '--toolchain' ||
+ option === '-toolchain'
+ ) {
+ const value = tokens[index + 1];
+ if (!value || !isLiteralXcrunBoundaryToken(value)) return true;
+ index += 2;
+ continue;
+ }
+ index += 1;
}
const firstToolToken = tokens[index] ?? '';
- if (!/[$`*?\[]/.test(firstToolToken)) return false;
- let end = index + 1;
- if (firstToolToken.includes('$(') && !firstToolToken.includes(')')) {
- while (end < tokens.length && !tokens[end - 1]!.includes(')')) end += 1;
- }
- return containsLiteralSimulatorExecutor(tokens.slice(index, end).join(' '));
+ return firstToolToken !== '' && !isLiteralXcrunBoundaryToken(firstToolToken);
}
/** Function bodies are executable later, so reject unsafe bodies at definition time. */
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
index e3fff26dde..2641887de2 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
@@ -4393,6 +4393,80 @@ describe('iOS Simulator host', () => {
await host.dispose();
});
+ it('cancels active WDA snapshot reads with the owning task', async () => {
+ let snapshotSignal: AbortSignal | undefined;
+ const bootedDevice = READY_REPORT.devices[0]!;
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => bootedDevice),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore(),
+ lifecycle,
+ });
+ const instance = actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'abc',
+ device: bootedDevice,
+ });
+ const driver = {
+ getAccessibilityTree: vi.fn(
+ (_sessionId: string | undefined, signal?: AbortSignal) =>
+ new Promise<never>((_resolve, reject) => {
+ snapshotSignal = signal;
+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });
+ }),
+ ),
+ getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),
+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),
+ };
+ const running = {
+ instanceId: instance.instanceId,
+ simulatorUdid: instance.simulatorUdid,
+ pid: 42,
+ driver,
+ driverSessionId: 'wda-session',
+ } as unknown as WdaRunningInstance;
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ driverManager: {
+ get: vi.fn(() => running),
+ start: vi.fn(),
+ stop: vi.fn(async () => undefined),
+ },
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ });
+ await host.reconcileOwnership();
+ const current = actor.getOwned('session-a', instance.instanceId);
+ const route = {
+ instanceId: current.instanceId,
+ generation: current.generation,
+ leaseId: current.lease.id,
+ };
+
+ const reading = host.callTool('get_screen_map', route, {
+ sessionId: 'session-a',
+ origin: 'user',
+ });
+ await vi.waitFor(() => expect(snapshotSignal).toBeDefined());
+
+ const cancelling = host.cancelSessionOperations('session-a');
+ expect(snapshotSignal?.aborted).toBe(true);
+ await expect(reading).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ await expect(cancelling).resolves.toBeUndefined();
+ expect(driver.getAccessibilityTree).toHaveBeenCalledWith('wda-session', snapshotSignal);
+ await host.dispose();
+ });
+
it('automatically authorizes the same agent session after attach for start', async () => {
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(),
@@ -5713,19 +5787,31 @@ describe('iOS Simulator host', () => {
});
const driver = {
kind: 'wda' as const,
- probe: vi.fn(async () => ({ ready: true, message: null })),
- getAccessibilityTree: vi.fn(async () => ({
- capturedAt: '2026-07-22T12:00:00.000Z',
- tree: {
- type: 'XCUIElementTypeButton',
- label: 'Continue',
- enabled: true,
- visible: true,
- rect: { x: 20, y: 40, width: 100, height: 40 },
- },
- })),
- getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),
- getOrientation: vi.fn(async () => 'PORTRAIT' as const),
+ probe: vi.fn(async (...args: [signal?: AbortSignal]) => {
+ void args;
+ return { ready: true, message: null };
+ }),
+ getAccessibilityTree: vi.fn(async (...args: [sessionId?: string, signal?: AbortSignal]) => {
+ void args;
+ return {
+ capturedAt: '2026-07-22T12:00:00.000Z',
+ tree: {
+ type: 'XCUIElementTypeButton',
+ label: 'Continue',
+ enabled: true,
+ visible: true,
+ rect: { x: 20, y: 40, width: 100, height: 40 },
+ },
+ };
+ }),
+ getWindowSize: vi.fn(async (...args: [sessionId?: string, signal?: AbortSignal]) => {
+ void args;
+ return { width: 393, height: 852 };
+ }),
+ getOrientation: vi.fn(async (...args: [sessionId?: string, signal?: AbortSignal]) => {
+ void args;
+ return 'PORTRAIT' as const;
+ }),
configureStream: vi.fn(
async (
...args: [
@@ -5911,6 +5997,12 @@ describe('iOS Simulator host', () => {
ok: true,
data: { screenMap: { generation: instance.generation, elements: [{ label: 'Continue' }] } },
});
+ expect(driver.getAccessibilityTree).toHaveBeenLastCalledWith(
+ 'wda-session',
+ expect.any(AbortSignal),
+ );
+ expect(driver.getWindowSize).toHaveBeenLastCalledWith('wda-session', expect.any(AbortSignal));
+ expect(driver.getOrientation).toHaveBeenLastCalledWith('wda-session', expect.any(AbortSignal));
const doctor = await host.callTool('doctor', {}, { sessionId: 'session-a', origin: 'agent' });
expect(doctor).toMatchObject({
ok: true,
@@ -5959,6 +6051,12 @@ describe('iOS Simulator host', () => {
},
},
});
+ expect(driver.probe).toHaveBeenLastCalledWith(expect.any(AbortSignal));
+ expect(driver.getOrientation).toHaveBeenLastCalledWith('wda-session', expect.any(AbortSignal));
+ expect(driver.getAccessibilityTree).toHaveBeenLastCalledWith(
+ 'wda-session',
+ expect.any(AbortSignal),
+ );
expect(JSON.stringify(capturedState)).not.toContain('/Users/example');
expect(JSON.stringify(capturedState)).not.toContain('SimulatorKit.framework');
expect(JSON.stringify(capturedState)).not.toContain('private-value');
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 7054fad247..537c6790d5 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -2558,8 +2558,9 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
async function refreshInteractionSnapshot(
instance: IOSSimulatorInstance,
running: WdaRunningInstance,
+ signal?: AbortSignal,
) {
- const snapshot = await running.driver.getAccessibilityTree(running.driverSessionId);
+ const snapshot = await running.driver.getAccessibilityTree(running.driverSessionId, signal);
return screenMaps.capture({
instanceId: instance.instanceId,
generation: instance.generation,
@@ -2787,7 +2788,11 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
baselineFingerprint = screenMapFingerprint(baseline);
}
while (true) {
- const screenMap = await refreshInteractionSnapshot(input.instance, input.running);
+ const screenMap = await refreshInteractionSnapshot(
+ input.instance,
+ input.running,
+ input.signal,
+ );
lastScreenMap = screenMap;
const fingerprint = screenMapFingerprint(screenMap);
const now = Date.now();
@@ -2845,7 +2850,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (mode === 'immediate') {
return {
mode,
- screenMap: await refreshInteractionSnapshot(instance, running),
+ screenMap: await refreshInteractionSnapshot(instance, running, signal),
stable: false,
timedOut: false,
elapsedMs: 0,
@@ -2881,7 +2886,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const nativeInput = running.driverRouter?.continuousInput();
if (nativeInput && durationMs >= 8) {
const viewport =
- driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));
+ driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running, signal));
await nativeInput.touchPath(nativeSwipePath(start, end, durationMs, viewport), signal);
return 'native-hid';
}
@@ -2899,7 +2904,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const nativeInput = running.driverRouter?.continuousInput();
if (nativeInput) {
const viewport =
- driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));
+ driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running, signal));
const normalized = normalizedPointFromViewport(point, viewport);
await nativeInput.touchPath(
[
@@ -3997,7 +4002,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
true,
);
}
- const { viewer, driver } = await currentViewports(running);
+ const { viewer, driver } = await currentViewports(running, signal);
assertCurrentViewer(resolved.sessionId, instance.instanceId, viewerWebContentsId);
const driverPoint = pointFromViewer(
{ xRatio: touch.xRatio, yRatio: touch.yRatio },
@@ -4332,12 +4337,14 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
if (name === 'get_screen_map') {
const route = readMutationRoute(sessionId, args);
- const captured = await runHostMutation(route, context, async (instance) => {
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
const running = requireDriver(instance.instanceId);
const [screenMap, viewport] = await Promise.all([
- refreshInteractionSnapshot(instance, running),
- context?.origin === 'user' ? readViewport(running) : readDriverViewport(running),
+ refreshInteractionSnapshot(instance, running, signal),
+ context?.origin === 'user'
+ ? readViewport(running, signal)
+ : readDriverViewport(running, signal),
]);
return { screenMap, viewport };
});
@@ -4366,14 +4373,14 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const route = readMutationRoute(sessionId, args);
const maxViolations =
args.maxViolations === undefined ? 200 : readPositiveInteger(args, 'maxViolations');
- const captured = await runHostMutation(route, context, async (instance) => {
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
const running = requireDriver(instance.instanceId);
const current = screenMaps.current(instance.instanceId);
const screenMap =
current?.generation === instance.generation
? current
- : await refreshInteractionSnapshot(instance, running);
+ : await refreshInteractionSnapshot(instance, running, signal);
return {
audit: auditIOSSimulatorScreenMap(screenMap, maxViolations),
};
@@ -4391,10 +4398,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
const maxChanges =
args.maxChanges === undefined ? 200 : readPositiveInteger(args, 'maxChanges');
- const captured = await runHostMutation(route, context, async (instance) => {
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
const running = requireDriver(instance.instanceId);
- const current = await refreshInteractionSnapshot(instance, running);
+ const current = await refreshInteractionSnapshot(instance, running, signal);
return {
diff: diffIOSSimulatorScreenMaps(baseline, current, maxChanges),
};
@@ -4411,11 +4418,11 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (elementId) {
const screenMap =
context?.origin === 'user'
- ? await refreshInteractionSnapshot(instance, running)
+ ? await refreshInteractionSnapshot(instance, running, signal)
: requireAgentInteractionSnapshot(instance, args);
point = elementPoint(screenMap, elementId);
} else if (context?.origin === 'user') {
- const { viewer, driver } = await currentViewports(running);
+ const { viewer, driver } = await currentViewports(running, signal);
point = pointFromViewer(args, viewer, driver, 'xRatio', 'yRatio');
} else {
requireAgentInteractionSnapshot(instance, args);
@@ -4427,7 +4434,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const nativeInput = running.driverRouter?.continuousInput();
if (nativeInput) {
const nativeViewport =
- driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));
+ driverViewports.get(instance.instanceId) ??
+ (await readDriverViewport(running, signal));
const normalized = normalizedPointFromViewport(point, nativeViewport);
await nativeInput.touchPath(
[
@@ -4459,7 +4467,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const captured = await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
const running = requireDriver(instance.instanceId);
- const viewport = context?.origin === 'user' ? await currentViewports(running) : null;
+ const viewport =
+ context?.origin === 'user' ? await currentViewports(running, signal) : null;
if (!viewport) {
requireAgentInteractionSnapshot(instance, args);
}
@@ -4505,7 +4514,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const running = requireDriver(instance.instanceId);
const screenMap =
context?.origin === 'user'
- ? await refreshInteractionSnapshot(instance, running)
+ ? await refreshInteractionSnapshot(instance, running, signal)
: requireAgentInteractionSnapshot(instance, args);
const start = elementPoint(screenMap, readString(args, 'fromElementId'));
const end = elementPoint(screenMap, readString(args, 'toElementId'));
@@ -4539,7 +4548,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const running = requireDriver(instance.instanceId);
const screenMap =
context?.origin === 'user'
- ? await refreshInteractionSnapshot(instance, running)
+ ? await refreshInteractionSnapshot(instance, running, signal)
: requireAgentInteractionSnapshot(instance, args);
const point = elementPoint(screenMap, readString(args, 'elementId'));
const backend = await performLongPress(
@@ -4600,7 +4609,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const running = requireDriver(instance.instanceId);
let screenMap =
context?.origin === 'user'
- ? await refreshInteractionSnapshot(instance, running)
+ ? await refreshInteractionSnapshot(instance, running, signal)
: requireAgentInteractionSnapshot(instance, args);
const completed: Array<{ index: number; type: string; backend: string }> = [];
for (const [index, rawAction] of actions.entries()) {
@@ -4612,7 +4621,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const nativeInput = running.driverRouter?.continuousInput();
if (nativeInput) {
const viewport =
- driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));
+ driverViewports.get(instance.instanceId) ??
+ (await readDriverViewport(running, signal));
const normalized = normalizedPointFromViewport(point, viewport);
await nativeInput.touchPath(
[
@@ -4672,7 +4682,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
);
}
screenMaps.invalidate(instance.instanceId);
- screenMap = await refreshInteractionSnapshot(instance, running);
+ screenMap = await refreshInteractionSnapshot(instance, running, signal);
completed.push({ index, type, backend });
}
const observation = await observeAfterInteraction(instance, running, args, signal);
@@ -4704,7 +4714,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
);
}
const viewport =
- driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));
+ driverViewports.get(instance.instanceId) ??
+ (await readDriverViewport(running, signal));
await nativeInput.touchPath(
readTouchPath(args, 'points', viewport, readTouchEdge(args.edge)),
signal,
@@ -4741,7 +4752,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
);
}
const viewport =
- driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));
+ driverViewports.get(instance.instanceId) ??
+ (await readDriverViewport(running, signal));
await nativeInput.touch2Path(
readTouchPath(args, 'first', viewport),
readTouchPath(args, 'second', viewport),
@@ -5591,13 +5603,13 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
if (name === 'capture_state') {
const route = readMutationRoute(sessionId, args);
- const captured = await runHostMutation(route, context, async (instance) => {
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
const running = requireDriver(instance.instanceId);
const [health, orientation, accessibility] = await Promise.all([
- running.driver.probe(),
- running.driver.getOrientation(running.driverSessionId),
- running.driver.getAccessibilityTree(running.driverSessionId),
+ running.driver.probe(signal),
+ running.driver.getOrientation(running.driverSessionId, signal),
+ running.driver.getAccessibilityTree(running.driverSessionId, signal),
]);
const screenMap = screenMaps.capture({
instanceId: instance.instanceId,