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。

feat(ios-simulator): add stable agent interaction tools

JiangJiahao0ac7d8aa25d5
diff --git a/apps/desktop/src/main/maker-host/ios-simulator-codex-dynamic-tools.ts b/apps/desktop/src/main/maker-host/ios-simulator-codex-dynamic-tools.ts
index 04cadea439..932fae61d6 100644
--- a/apps/desktop/src/main/maker-host/ios-simulator-codex-dynamic-tools.ts
+++ b/apps/desktop/src/main/maker-host/ios-simulator-codex-dynamic-tools.ts
@@ -141,10 +141,15 @@ export function createIOSSimulatorCodexDynamicToolProvider(options: {
false,
);
}
+ const availability = await options.deps.describeTools?.({
+ sessionId: context.sessionId,
+ origin: 'agent',
+ });
return textResponse({
ok: true,
category: 'ios_simulator',
- tools: registry.list(),
+ tools: registry.list(availability?.tools),
+ ...(availability ? { availability } : {}),
workflow:
'Use this embedded viewer workflow: check_environment, then list_devices and either create_instance or attach_device, then start_instance. Build, install, and launch the app through this gateway. Route mutations with instanceId, generation, and leaseId.',
});
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 4af42e7148..33dbef540d 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
@@ -1290,10 +1290,14 @@ describe('iOS Simulator host', () => {
{ sessionId: 'session-a', origin: 'user' },
),
).resolves.toMatchObject({ ok: true });
- expect(wdaDriver.tap).toHaveBeenCalledWith('wda-session', {
- x: 196.5,
- y: 639,
- });
+ expect(wdaDriver.tap).toHaveBeenCalledWith(
+ 'wda-session',
+ {
+ x: 196.5,
+ y: 639,
+ },
+ expect.any(AbortSignal),
+ );
await expect(
host.callTool(
'swipe',
@@ -1909,6 +1913,28 @@ describe('iOS Simulator host', () => {
ok: true,
data: { screenMap: { generation: instance.generation, elements: [{ label: 'Continue' }] } },
});
+ const doctor = await host.callTool(
+ 'doctor',
+ {},
+ { sessionId: 'session-a', origin: 'agent' },
+ );
+ expect(doctor).toMatchObject({
+ ok: true,
+ data: {
+ availability: {
+ ready: true,
+ instanceCount: 1,
+ runningInstanceCount: 1,
+ tools: {
+ drag: { state: 'available', backend: 'wda' },
+ touch_path: { state: 'unavailable', reasonCode: 'NATIVE_HID_NOT_ADMITTED' },
+ },
+ },
+ resource: { runningCount: 1 },
+ },
+ });
+ expect(JSON.stringify(doctor)).not.toContain('/Users/example');
+ expect(JSON.stringify(doctor)).not.toContain('SimulatorKit.framework');
const capturedState = await host.callTool('capture_state', route, {
sessionId: 'session-a',
origin: 'agent',
@@ -2090,11 +2116,111 @@ describe('iOS Simulator host', () => {
origin: 'agent',
});
if (!refreshedScreenResult.ok) throw new Error('expected a refreshed screen map');
- const screenMap = (
+ let screenMap = (
refreshedScreenResult.data as {
screenMap: { snapshotId: string; elements: Array<{ elementId: string }> };
}
).screenMap;
+ driver.getAccessibilityTree.mockResolvedValueOnce({
+ capturedAt: '2026-07-22T12:00:01.000Z',
+ tree: {
+ type: 'XCUIElementTypeButton',
+ label: 'Done',
+ enabled: true,
+ visible: true,
+ rect: { x: 20, y: 40, width: 100, height: 40 },
+ },
+ });
+ await expect(
+ host.callTool(
+ 'tap',
+ {
+ ...route,
+ snapshotId: screenMap.snapshotId,
+ elementId: screenMap.elements[0]!.elementId,
+ observeAfter: 'immediate',
+ },
+ { sessionId: 'session-a', origin: 'agent' },
+ ),
+ ).resolves.toMatchObject({
+ ok: true,
+ data: {
+ interaction: 'tap',
+ screenMapInvalidated: false,
+ observation: {
+ mode: 'immediate',
+ screenMap: { elements: [{ label: 'Done' }] },
+ },
+ },
+ });
+
+ driver.getAccessibilityTree.mockResolvedValueOnce({
+ capturedAt: '2026-07-22T12:00:02.000Z',
+ tree: {
+ type: 'XCUIElementTypeStaticText',
+ label: 'Loading',
+ enabled: true,
+ visible: true,
+ rect: { x: 20, y: 40, width: 100, height: 40 },
+ },
+ });
+ driver.getAccessibilityTree.mockResolvedValueOnce({
+ capturedAt: '2026-07-22T12:00:03.000Z',
+ tree: {
+ type: 'XCUIElementTypeButton',
+ label: 'Done',
+ enabled: true,
+ visible: true,
+ rect: { x: 20, y: 40, width: 100, height: 40 },
+ },
+ });
+ await expect(
+ host.callTool(
+ 'wait_for_ui',
+ {
+ ...route,
+ condition: { kind: 'element_exists', selector: { labelContains: 'Done' } },
+ timeoutMs: 1_000,
+ pollIntervalMs: 100,
+ stableForMs: 100,
+ },
+ { sessionId: 'session-a', origin: 'agent' },
+ ),
+ ).resolves.toMatchObject({
+ ok: true,
+ data: {
+ timedOut: false,
+ screenMap: { elements: [{ label: 'Done' }] },
+ },
+ });
+ await expect(
+ host.callTool(
+ 'wait_for_ui',
+ {
+ ...route,
+ condition: { kind: 'element_exists', selector: { labelContains: 'Never appears' } },
+ timeoutMs: 100,
+ pollIntervalMs: 100,
+ stableForMs: 100,
+ },
+ { sessionId: 'session-a', origin: 'agent' },
+ ),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'UI_WAIT_TIMEOUT' });
+ expect(actor.mutationState(instance.instanceId)).toMatchObject({
+ activeSource: null,
+ takeoverPending: false,
+ });
+
+ const postObservationScreen = await host.callTool('get_screen_map', route, {
+ sessionId: 'session-a',
+ origin: 'agent',
+ });
+ if (!postObservationScreen.ok) throw new Error('expected post-observation screen map');
+ screenMap = (
+ postObservationScreen.data as {
+ screenMap: { snapshotId: string; elements: Array<{ elementId: string }> };
+ }
+ ).screenMap;
const tapArgs = {
...route,
snapshotId: screenMap.snapshotId,
@@ -2103,7 +2229,11 @@ describe('iOS Simulator host', () => {
await expect(
host.callTool('tap', tapArgs, { sessionId: 'session-a', origin: 'agent' }),
).resolves.toMatchObject({ ok: true });
- expect(driver.tap).toHaveBeenCalledWith('wda-session', { x: 70, y: 60 });
+ expect(driver.tap).toHaveBeenCalledWith(
+ 'wda-session',
+ { x: 70, y: 60 },
+ expect.any(AbortSignal),
+ );
await expect(
host.callTool('tap', tapArgs, { sessionId: 'session-a', origin: 'agent' }),
).resolves.toMatchObject({ ok: false, errorCode: 'STALE_UI_SNAPSHOT' });
@@ -2115,7 +2245,11 @@ describe('iOS Simulator host', () => {
{ sessionId: 'session-a', origin: 'user' },
),
).resolves.toMatchObject({ ok: true });
- expect(driver.tap).toHaveBeenLastCalledWith('wda-session', { x: 196.5, y: 213 });
+ expect(driver.tap).toHaveBeenLastCalledWith(
+ 'wda-session',
+ { x: 196.5, y: 213 },
+ expect.any(AbortSignal),
+ );
await expect(
host.callTool(
'swipe',
@@ -2320,7 +2454,11 @@ describe('iOS Simulator host', () => {
{ sessionId: 'session-a', origin: 'user' },
),
).resolves.toMatchObject({ ok: true });
- expect(driver.typeText).toHaveBeenLastCalledWith('wda-session', 'Hello');
+ expect(driver.typeText).toHaveBeenLastCalledWith(
+ 'wda-session',
+ 'Hello',
+ expect.any(AbortSignal),
+ );
await expect(
host.callTool('press_home', route, { sessionId: 'session-a', origin: 'user' }),
).resolves.toMatchObject({ ok: true });
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 36d17178fd..bac28b8f84 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -60,6 +60,8 @@ import type {
IOSSimulatorMcpDeps,
IOSSimulatorMcpErrorCode,
IOSSimulatorMcpToolName,
+ IOSSimulatorToolAvailability,
+ IOSSimulatorToolAvailabilityReport,
} from '@cindy/mcps';
import type {
@@ -154,6 +156,7 @@ export interface IOSSimulatorHost {
/** Stop host-owned WDA/recording resources without changing simulator ownership. */
dispose(): Promise<void>;
reconcileOwnership(): Promise<void>;
+ describeTools(sessionId: string): Promise<IOSSimulatorToolAvailabilityReport>;
getStatus(sessionId: string): Promise<IOSSimulatorSessionStatus>;
callTool(
name: IOSSimulatorMcpToolName,
@@ -1059,6 +1062,351 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
});
}
+ async function describeToolsForSession(
+ sessionId: string,
+ environment?: IOSSimulatorEnvironmentReport,
+ ): Promise<IOSSimulatorToolAvailabilityReport> {
+ const inspected = environment ?? (await runtime.inspect());
+ const instances = actor.list(sessionId);
+ const running = instances
+ .map((instance) => ({ instance, driver: getDriverManager().get(instance.instanceId) }))
+ .filter((entry) => entry.driver !== null);
+ const capabilityReports = running
+ .map((entry) => entry.driver?.driverRouter?.capabilityReport?.())
+ .filter((report): report is NonNullable<typeof report> => Boolean(report));
+ const hasNativeInput = capabilityReports.some(
+ (report) => report.routes.continuousInput.selected === 'native-sidecar' && !report.routes.continuousInput.fallback,
+ );
+ const hasMultiTouch = capabilityReports.some(
+ (report) => report.nativeSidecar.capabilities?.multiTouch === true && report.nativeSidecar.available,
+ );
+ const hasInstance = instances.length > 0;
+ const hasRunning = running.length > 0;
+ const requiresInstance: IOSSimulatorToolAvailability = {
+ state: hasInstance ? (hasRunning ? 'available' : 'instance-dependent') : 'requires-instance',
+ ...(hasInstance ? {} : { reasonCode: 'INSTANCE_REQUIRED' }),
+ };
+ const tools: Record<string, IOSSimulatorToolAvailability> = {
+ check_environment: { state: 'available', backend: 'host' },
+ doctor: { state: 'available', backend: 'host' },
+ list_devices: inspected.ready
+ ? { state: 'available', backend: 'simctl' }
+ : { state: 'unavailable', reasonCode: inspected.issue ?? 'ENVIRONMENT_NOT_READY' },
+ list_instances: { state: 'available', backend: 'host' },
+ create_instance: inspected.ready
+ ? { state: 'available', backend: 'simctl' }
+ : { state: 'unavailable', reasonCode: inspected.issue ?? 'ENVIRONMENT_NOT_READY' },
+ attach_device: inspected.ready
+ ? { state: 'available', backend: 'host' }
+ : { state: 'unavailable', reasonCode: inspected.issue ?? 'ENVIRONMENT_NOT_READY' },
+ start_instance: { ...requiresInstance, backend: 'simctl' },
+ stop_instance: { ...requiresInstance, backend: 'simctl' },
+ detach_device: { ...requiresInstance, backend: 'host' },
+ get_screen_map: { ...requiresInstance, backend: 'wda' },
+ audit_accessibility: { ...requiresInstance, backend: 'wda' },
+ compare_screen_maps: { ...requiresInstance, backend: 'wda' },
+ wait_for_ui: { ...requiresInstance, backend: 'wda' },
+ tap: { ...requiresInstance, backend: hasNativeInput ? 'native-hid' : 'wda' },
+ swipe: { ...requiresInstance, backend: hasNativeInput ? 'native-hid' : 'wda' },
+ drag: { ...requiresInstance, backend: hasNativeInput ? 'native-hid' : 'wda' },
+ long_press: { ...requiresInstance, backend: hasNativeInput ? 'native-hid' : 'wda' },
+ key_press: { ...requiresInstance, backend: 'wda' },
+ batch: { ...requiresInstance, backend: hasNativeInput ? 'native-hid' : 'wda' },
+ touch_path: hasNativeInput
+ ? { state: 'available', backend: 'native-hid' }
+ : {
+ state: hasInstance ? 'unavailable' : 'requires-instance',
+ reasonCode: hasInstance ? 'NATIVE_HID_NOT_ADMITTED' : 'INSTANCE_REQUIRED',
+ },
+ touch2_path: hasMultiTouch
+ ? { state: 'available', backend: 'native-hid' }
+ : {
+ state: hasInstance ? 'unavailable' : 'requires-instance',
+ reasonCode: hasInstance ? 'MULTI_TOUCH_NOT_ADMITTED' : 'INSTANCE_REQUIRED',
+ },
+ };
+ for (const name of [
+ 'type_text',
+ 'press_home',
+ 'set_orientation',
+ 'set_appearance',
+ 'set_increase_contrast',
+ 'set_content_size',
+ 'set_location',
+ 'start_location_route',
+ 'clear_location',
+ 'set_privacy',
+ 'push_notification',
+ 'set_status_bar',
+ 'clear_status_bar',
+ 'lock_screen',
+ 'unlock_screen',
+ 'build_app',
+ 'read_build_diagnostics',
+ 'install_app',
+ 'launch_app',
+ 'terminate_app',
+ 'open_url',
+ 'take_screenshot',
+ 'capture_visual_baseline',
+ 'visual_diff',
+ 'capture_state',
+ 'get_diagnostics',
+ 'start_recording',
+ 'stop_recording',
+ ]) {
+ tools[name] = { ...requiresInstance, backend: name === 'build_app' ? 'host' : 'wda' };
+ }
+ return {
+ ready: inspected.ready,
+ instanceCount: instances.length,
+ runningInstanceCount: running.length,
+ tools,
+ };
+ }
+
+ function screenMapFingerprint(screenMap: IOSSimulatorScreenMap): string {
+ return createHash('sha256').update(JSON.stringify(screenMap.elements)).digest('hex');
+ }
+
+ function sleepWithAbort(delayMs: number, signal: AbortSignal): Promise<void> {
+ if (signal.aborted) {
+ return Promise.reject(
+ new IOSSimulatorInstanceError('MUTATION_CANCELLED', 'The UI operation was cancelled.', true),
+ );
+ }
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ signal.removeEventListener('abort', onAbort);
+ resolve();
+ }, delayMs);
+ const onAbort = () => {
+ clearTimeout(timer);
+ signal.removeEventListener('abort', onAbort);
+ reject(
+ new IOSSimulatorInstanceError('MUTATION_CANCELLED', 'The UI operation was cancelled.', true),
+ );
+ };
+ signal.addEventListener('abort', onAbort, { once: true });
+ });
+ }
+
+ function elementMatches(
+ element: IOSSimulatorScreenMap['elements'][number],
+ selector: Record<string, unknown>,
+ ): boolean {
+ if (typeof selector.elementId === 'string' && element.elementId !== selector.elementId) {
+ return false;
+ }
+ if (typeof selector.role === 'string' && element.role !== selector.role) return false;
+ if (
+ typeof selector.labelContains === 'string' &&
+ !element.label?.toLocaleLowerCase().includes(selector.labelContains.toLocaleLowerCase())
+ ) {
+ return false;
+ }
+ if (
+ typeof selector.valueContains === 'string' &&
+ !element.value?.toLocaleLowerCase().includes(selector.valueContains.toLocaleLowerCase())
+ ) {
+ return false;
+ }
+ return true;
+ }
+
+ function elementPoint(screenMap: IOSSimulatorScreenMap, elementId: string) {
+ const element = screenMap.elements.find((candidate) => candidate.elementId === elementId);
+ if (!element?.frame || element.enabled === false || element.visible === false) {
+ throw new IOSSimulatorInstanceError(
+ 'STALE_UI_SNAPSHOT',
+ 'The target is no longer interactable. Read a new screen map.',
+ true,
+ );
+ }
+ return {
+ x: element.frame.x + element.frame.width / 2,
+ y: element.frame.y + element.frame.height / 2,
+ };
+ }
+
+ async function waitForUiCondition(input: {
+ instance: IOSSimulatorInstance;
+ running: WdaRunningInstance;
+ condition: Record<string, unknown>;
+ timeoutMs: number;
+ pollIntervalMs: number;
+ stableForMs: number;
+ signal: AbortSignal;
+ throwOnTimeout: boolean;
+ }): Promise<{
+ screenMap: IOSSimulatorScreenMap;
+ elapsedMs: number;
+ stable: boolean;
+ timedOut: boolean;
+ }> {
+ const startedAt = Date.now();
+ let previousFingerprint: string | null = null;
+ let stableSince = startedAt;
+ let lastScreenMap: IOSSimulatorScreenMap | null = null;
+ let baselineFingerprint: string | null = null;
+ const kind = readString(input.condition, 'kind');
+ if (kind === 'screen_changed') {
+ const baseline = screenMaps.requireCurrent({
+ instanceId: input.instance.instanceId,
+ generation: input.instance.generation,
+ snapshotId: readString(input.condition, 'snapshotId'),
+ });
+ baselineFingerprint = screenMapFingerprint(baseline);
+ }
+ while (true) {
+ const screenMap = await refreshInteractionSnapshot(input.instance, input.running);
+ lastScreenMap = screenMap;
+ const fingerprint = screenMapFingerprint(screenMap);
+ const now = Date.now();
+ if (fingerprint !== previousFingerprint) {
+ previousFingerprint = fingerprint;
+ stableSince = now;
+ }
+ let matched = false;
+ if (kind === 'element_exists' || kind === 'element_missing') {
+ const selector = readObject(input.condition, 'selector');
+ const exists = screenMap.elements.some((element) => elementMatches(element, selector));
+ matched = kind === 'element_exists' ? exists : !exists;
+ } else if (kind === 'screen_changed') {
+ matched = fingerprint !== baselineFingerprint;
+ } else if (kind === 'screen_stable') {
+ matched = now - stableSince >= input.stableForMs;
+ } else {
+ throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'Unsupported UI wait condition.');
+ }
+ if (matched) {
+ return {
+ screenMap,
+ elapsedMs: now - startedAt,
+ stable: kind === 'screen_stable',
+ timedOut: false,
+ };
+ }
+ if (now - startedAt >= input.timeoutMs) {
+ if (input.throwOnTimeout) {
+ throw new IOSSimulatorInstanceError(
+ 'UI_WAIT_TIMEOUT',
+ 'The requested UI condition did not become true before the timeout.',
+ true,
+ );
+ }
+ return {
+ screenMap: lastScreenMap,
+ elapsedMs: now - startedAt,
+ stable: false,
+ timedOut: true,
+ };
+ }
+ await sleepWithAbort(input.pollIntervalMs, input.signal);
+ }
+ }
+
+ async function observeAfterInteraction(
+ instance: IOSSimulatorInstance,
+ running: WdaRunningInstance,
+ args: Record<string, unknown>,
+ signal: AbortSignal,
+ ) {
+ const mode = args.observeAfter === undefined ? 'none' : readString(args, 'observeAfter');
+ if (mode === 'none') return null;
+ if (mode === 'immediate') {
+ return {
+ mode,
+ screenMap: await refreshInteractionSnapshot(instance, running),
+ stable: false,
+ timedOut: false,
+ elapsedMs: 0,
+ };
+ }
+ if (mode !== 'stable') {
+ throw new IOSSimulatorInstanceError(
+ 'INVALID_ARGUMENT',
+ 'observeAfter must be none, immediate, or stable',
+ );
+ }
+ const observed = await waitForUiCondition({
+ instance,
+ running,
+ condition: { kind: 'screen_stable' },
+ timeoutMs: readPositiveInteger(args, 'observeTimeoutMs'),
+ pollIntervalMs: 100,
+ stableForMs: readPositiveInteger(args, 'stableForMs'),
+ signal,
+ throwOnTimeout: false,
+ });
+ return { mode, ...observed };
+ }
+
+ async function performSwipe(
+ instance: IOSSimulatorInstance,
+ running: WdaRunningInstance,
+ start: { x: number; y: number },
+ end: { x: number; y: number },
+ durationMs: number,
+ signal: AbortSignal,
+ ): Promise<'native-hid' | 'wda'> {
+ const nativeInput = running.driverRouter?.continuousInput();
+ if (nativeInput && durationMs >= 8) {
+ const viewport =
+ driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));
+ await nativeInput.touchPath(nativeSwipePath(start, end, durationMs, viewport), signal);
+ return 'native-hid';
+ }
+ await running.driver.swipe(running.driverSessionId, start, end, durationMs, signal);
+ return 'wda';
+ }
+
+ async function performLongPress(
+ instance: IOSSimulatorInstance,
+ running: WdaRunningInstance,
+ point: { x: number; y: number },
+ durationMs: number,
+ signal: AbortSignal,
+ ): Promise<'native-hid' | 'wda'> {
+ const nativeInput = running.driverRouter?.continuousInput();
+ if (nativeInput) {
+ const viewport =
+ driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));
+ const normalized = normalizedPointFromViewport(point, viewport);
+ await nativeInput.touchPath(
+ [
+ { ...normalized, phase: 'down', dtMs: 0, edge: 'none' },
+ { ...normalized, phase: 'up', dtMs: durationMs, edge: 'none' },
+ ],
+ signal,
+ );
+ return 'native-hid';
+ }
+ await running.driver.swipe(running.driverSessionId, point, point, durationMs, signal);
+ return 'wda';
+ }
+
+ const webDriverKeys: Record<string, string> = {
+ return: '\uE007',
+ tab: '\uE004',
+ escape: '\uE00C',
+ delete: '\uE017',
+ arrow_up: '\uE013',
+ arrow_down: '\uE015',
+ arrow_left: '\uE012',
+ arrow_right: '\uE014',
+ };
+
+ async function performKeyPress(
+ running: WdaRunningInstance,
+ key: string,
+ signal?: AbortSignal,
+ ): Promise<void> {
+ const value = webDriverKeys[key];
+ if (!value) throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'Unsupported key.');
+ await running.driver.typeText(running.driverSessionId, value, signal);
+ }
+
function pointFromViewer(
args: Record<string, unknown>,
viewerViewport: IOSSimulatorPublicViewport,
@@ -1338,6 +1686,22 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return {
reconcileOwnership: reconcilePersistedOwnership,
+ async describeTools(sessionId) {
+ const resolved = await resolveSession(sessionId);
+ if (!resolved.ok) {
+ return {
+ ready: false,
+ instanceCount: 0,
+ runningInstanceCount: 0,
+ tools: {
+ doctor: { state: 'available', backend: 'host' },
+ check_environment: { state: 'available', backend: 'host' },
+ list_devices: { state: 'unavailable', reasonCode: resolved.errorCode },
+ },
+ };
+ }
+ return describeToolsForSession(resolved.sessionId);
+ },
getStatus: inspectForSession,
async setViewerVisibility(sessionId, route, visible, preferredEncoding = 'jpeg') {
try {
@@ -1745,6 +2109,25 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
});
return { ok: true, data: captured };
}
+ if (name === 'wait_for_ui') {
+ const route = readMutationRoute(sessionId, args);
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
+ requireControlGrant(instance, context);
+ const running = requireDriver(instance.instanceId);
+ const condition = readObject(args, 'condition');
+ return waitForUiCondition({
+ instance,
+ running,
+ condition,
+ timeoutMs: readPositiveInteger(args, 'timeoutMs'),
+ pollIntervalMs: readPositiveInteger(args, 'pollIntervalMs'),
+ stableForMs: readPositiveInteger(args, 'stableForMs'),
+ signal,
+ throwOnTimeout: true,
+ });
+ });
+ return { ok: true, data: captured };
+ }
if (name === 'audit_accessibility') {
const route = readMutationRoute(sessionId, args);
const maxViolations =
@@ -1786,7 +2169,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
if (name === 'tap') {
const route = readMutationRoute(sessionId, args);
- await runHostMutation(route, context, async (instance, signal) => {
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
const running = requireDriver(instance.instanceId);
const elementId = typeof args.elementId === 'string' ? args.elementId.trim() : '';
@@ -1796,20 +2179,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
context?.origin === 'user'
? await refreshInteractionSnapshot(instance, running)
: requireAgentInteractionSnapshot(instance, args);
- const element = screenMap.elements.find(
- (candidate) => candidate.elementId === elementId,
- );
- if (!element?.frame || element.enabled === false || element.visible === false) {
- throw new IOSSimulatorInstanceError(
- 'STALE_UI_SNAPSHOT',
- 'The target is no longer interactable. Read a new screen map.',
- true,
- );
- }
- point = {
- x: element.frame.x + element.frame.width / 2,
- y: element.frame.y + element.frame.height / 2,
- };
+ point = elementPoint(screenMap, elementId);
} else if (context?.origin === 'user') {
const { viewer, driver } = await currentViewports(running);
point = pointFromViewer(args, viewer, driver, 'xRatio', 'yRatio');
@@ -1833,15 +2203,26 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
signal,
);
} else {
- await running.driver.tap(running.driverSessionId, point);
+ await running.driver.tap(running.driverSessionId, point, signal);
}
screenMaps.invalidate(instance.instanceId);
+ return {
+ backend: nativeInput ? 'native-hid' : 'wda',
+ observation: await observeAfterInteraction(instance, running, args, signal),
+ };
});
- return { ok: true, data: { interaction: 'tap', screenMapInvalidated: true } };
+ return {
+ ok: true,
+ data: {
+ interaction: 'tap',
+ screenMapInvalidated: !Boolean(captured.observation),
+ ...captured,
+ },
+ };
}
if (name === 'swipe') {
const route = readMutationRoute(sessionId, args);
- await runHostMutation(route, context, async (instance, signal) => {
+ 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;
@@ -1867,26 +2248,214 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
y: readFiniteCoordinate(args, 'endY'),
};
const durationMs = readPositiveInteger(args, 'durationMs');
- const nativeInput = running.driverRouter?.continuousInput();
- if (nativeInput && durationMs >= 8) {
- const nativeViewport =
- viewport?.driver ??
- driverViewports.get(instance.instanceId) ??
- (await readDriverViewport(running));
- await nativeInput.touchPath(
- nativeSwipePath(start, end, durationMs, nativeViewport),
- signal,
- );
- } else {
- await running.driver.swipe(running.driverSessionId, start, end, durationMs, signal);
- }
+ const backend = await performSwipe(instance, running, start, end, durationMs, signal);
screenMaps.invalidate(instance.instanceId);
+ return {
+ backend,
+ observation: await observeAfterInteraction(instance, running, args, signal),
+ };
});
- return { ok: true, data: { interaction: 'swipe', screenMapInvalidated: true } };
+ return {
+ ok: true,
+ data: {
+ interaction: 'swipe',
+ screenMapInvalidated: !Boolean(captured.observation),
+ ...captured,
+ },
+ };
+ }
+ if (name === 'drag') {
+ const route = readMutationRoute(sessionId, args);
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
+ requireControlGrant(instance, context);
+ const running = requireDriver(instance.instanceId);
+ const screenMap =
+ context?.origin === 'user'
+ ? await refreshInteractionSnapshot(instance, running)
+ : requireAgentInteractionSnapshot(instance, args);
+ const start = elementPoint(screenMap, readString(args, 'fromElementId'));
+ const end = elementPoint(screenMap, readString(args, 'toElementId'));
+ const backend = await performSwipe(
+ instance,
+ running,
+ start,
+ end,
+ readPositiveInteger(args, 'durationMs'),
+ signal,
+ );
+ screenMaps.invalidate(instance.instanceId);
+ return {
+ backend,
+ observation: await observeAfterInteraction(instance, running, args, signal),
+ };
+ });
+ return {
+ ok: true,
+ data: {
+ interaction: 'drag',
+ screenMapInvalidated: !Boolean(captured.observation),
+ ...captured,
+ },
+ };
+ }
+ if (name === 'long_press') {
+ const route = readMutationRoute(sessionId, args);
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
+ requireControlGrant(instance, context);
+ const running = requireDriver(instance.instanceId);
+ const screenMap =
+ context?.origin === 'user'
+ ? await refreshInteractionSnapshot(instance, running)
+ : requireAgentInteractionSnapshot(instance, args);
+ const point = elementPoint(screenMap, readString(args, 'elementId'));
+ const backend = await performLongPress(
+ instance,
+ running,
+ point,
+ readPositiveInteger(args, 'durationMs'),
+ signal,
+ );
+ screenMaps.invalidate(instance.instanceId);
+ return {
+ backend,
+ observation: await observeAfterInteraction(instance, running, args, signal),
+ };
+ });
+ return {
+ ok: true,
+ data: {
+ interaction: 'long_press',
+ screenMapInvalidated: !Boolean(captured.observation),
+ ...captured,
+ },
+ };
+ }
+ if (name === 'key_press') {
+ const route = readMutationRoute(sessionId, args);
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
+ requireControlGrant(instance, context);
+ const running = requireDriver(instance.instanceId);
+ if (context?.origin !== 'user') requireAgentInteractionSnapshot(instance, args);
+ await performKeyPress(running, readString(args, 'key'), signal);
+ screenMaps.invalidate(instance.instanceId);
+ return {
+ backend: 'wda' as const,
+ observation: await observeAfterInteraction(instance, running, args, signal),
+ };
+ });
+ return {
+ ok: true,
+ data: {
+ interaction: 'key_press',
+ screenMapInvalidated: !Boolean(captured.observation),
+ ...captured,
+ },
+ };
+ }
+ if (name === 'batch') {
+ const route = readMutationRoute(sessionId, args);
+ const actions = args.actions;
+ if (!Array.isArray(actions) || actions.length === 0 || actions.length > 16) {
+ throw new IOSSimulatorInstanceError(
+ 'INVALID_ARGUMENT',
+ 'actions must contain between 1 and 16 UI actions',
+ );
+ }
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
+ requireControlGrant(instance, context);
+ const running = requireDriver(instance.instanceId);
+ let screenMap =
+ context?.origin === 'user'
+ ? await refreshInteractionSnapshot(instance, running)
+ : requireAgentInteractionSnapshot(instance, args);
+ const completed: Array<{ index: number; type: string; backend: string }> = [];
+ for (const [index, rawAction] of actions.entries()) {
+ const action = rawAction as Record<string, unknown>;
+ const type = readString(action, 'type');
+ let backend = 'wda';
+ if (type === 'tap') {
+ const point = elementPoint(screenMap, readString(action, 'elementId'));
+ const nativeInput = running.driverRouter?.continuousInput();
+ if (nativeInput) {
+ const viewport =
+ driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));
+ const normalized = normalizedPointFromViewport(point, viewport);
+ await nativeInput.touchPath(
+ [
+ { ...normalized, phase: 'down', dtMs: 0, edge: 'none' },
+ { ...normalized, phase: 'up', dtMs: 8, edge: 'none' },
+ ],
+ signal,
+ );
+ backend = 'native-hid';
+ } else {
+ await running.driver.tap(running.driverSessionId, point, signal);
+ }
+ } else if (type === 'swipe') {
+ backend = await performSwipe(
+ instance,
+ running,
+ {
+ x: readFiniteCoordinate(action, 'startX'),
+ y: readFiniteCoordinate(action, 'startY'),
+ },
+ {
+ x: readFiniteCoordinate(action, 'endX'),
+ y: readFiniteCoordinate(action, 'endY'),
+ },
+ readPositiveInteger(action, 'durationMs'),
+ signal,
+ );
+ } else if (type === 'drag') {
+ backend = await performSwipe(
+ instance,
+ running,
+ elementPoint(screenMap, readString(action, 'fromElementId')),
+ elementPoint(screenMap, readString(action, 'toElementId')),
+ readPositiveInteger(action, 'durationMs'),
+ signal,
+ );
+ } else if (type === 'long_press') {
+ backend = await performLongPress(
+ instance,
+ running,
+ elementPoint(screenMap, readString(action, 'elementId')),
+ readPositiveInteger(action, 'durationMs'),
+ signal,
+ );
+ } else if (type === 'type_text') {
+ const text = action.text;
+ if (typeof text !== 'string' || text.length > 10_000) {
+ throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'Invalid batch text.');
+ }
+ await running.driver.typeText(running.driverSessionId, text, signal);
+ } else if (type === 'key_press') {
+ await performKeyPress(running, readString(action, 'key'), signal);
+ } else {
+ throw new IOSSimulatorInstanceError(
+ 'INVALID_ARGUMENT',
+ `Unsupported batch action: ${type}`,
+ );
+ }
+ screenMaps.invalidate(instance.instanceId);
+ screenMap = await refreshInteractionSnapshot(instance, running);
+ completed.push({ index, type, backend });
+ }
+ const observation = await observeAfterInteraction(instance, running, args, signal);
+ return { completed, observation: observation ?? { mode: 'immediate', screenMap } };
+ });
+ return {
+ ok: true,
+ data: {
+ interaction: 'batch',
+ screenMapInvalidated: false,
+ ...captured,
+ },
+ };
}
if (name === 'touch_path') {
const route = readMutationRoute(sessionId, args);
- await runHostMutation(route, context, async (instance, signal) => {
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
const running = requireDriver(instance.instanceId);
if (context?.origin !== 'user') {
@@ -1907,12 +2476,23 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
signal,
);
screenMaps.invalidate(instance.instanceId);
+ return {
+ backend: 'native-hid' as const,
+ observation: await observeAfterInteraction(instance, running, args, signal),
+ };
});
- return { ok: true, data: { interaction: 'touch_path', screenMapInvalidated: true } };
+ return {
+ ok: true,
+ data: {
+ interaction: 'touch_path',
+ screenMapInvalidated: !Boolean(captured.observation),
+ ...captured,
+ },
+ };
}
if (name === 'touch2_path') {
const route = readMutationRoute(sessionId, args);
- await runHostMutation(route, context, async (instance, signal) => {
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
const running = requireDriver(instance.instanceId);
if (context?.origin !== 'user') {
@@ -1934,12 +2514,23 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
signal,
);
screenMaps.invalidate(instance.instanceId);
+ return {
+ backend: 'native-hid' as const,
+ observation: await observeAfterInteraction(instance, running, args, signal),
+ };
});
- return { ok: true, data: { interaction: 'touch2_path', screenMapInvalidated: true } };
+ return {
+ ok: true,
+ data: {
+ interaction: 'touch2_path',
+ screenMapInvalidated: !Boolean(captured.observation),
+ ...captured,
+ },
+ };
}
if (name === 'type_text') {
const route = readMutationRoute(sessionId, args);
- await runHostMutation(route, context, async (instance) => {
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
const running = requireDriver(instance.instanceId);
if (context?.origin !== 'user') {
@@ -1952,23 +2543,45 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'text must be a string of at most 10000 characters',
);
}
- await running.driver.typeText(running.driverSessionId, text);
+ await running.driver.typeText(running.driverSessionId, text, signal);
screenMaps.invalidate(instance.instanceId);
+ return {
+ backend: 'wda' as const,
+ observation: await observeAfterInteraction(instance, running, args, signal),
+ };
});
- return { ok: true, data: { interaction: 'type_text', screenMapInvalidated: true } };
+ return {
+ ok: true,
+ data: {
+ interaction: 'type_text',
+ screenMapInvalidated: !Boolean(captured.observation),
+ ...captured,
+ },
+ };
}
if (name === 'press_home') {
const route = readMutationRoute(sessionId, args);
- await runHostMutation(route, context, async (instance) => {
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
const running = requireDriver(instance.instanceId);
if (context?.origin !== 'user') {
requireAgentInteractionSnapshot(instance, args);
}
- await running.driver.home();
+ await running.driver.home(signal);
screenMaps.invalidate(instance.instanceId);
+ return {
+ backend: 'wda' as const,
+ observation: await observeAfterInteraction(instance, running, args, signal),
+ };
});
- return { ok: true, data: { interaction: 'press_home', screenMapInvalidated: true } };
+ return {
+ ok: true,
+ data: {
+ interaction: 'press_home',
+ screenMapInvalidated: !Boolean(captured.observation),
+ ...captured,
+ },
+ };
}
if (name === 'set_orientation') {
const route = readMutationRoute(sessionId, args);
@@ -2736,6 +3349,46 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (name === 'check_environment') {
return { ok: true, data: publicEnvironment(environment) };
}
+ if (name === 'doctor') {
+ const availability = await describeToolsForSession(sessionId, environment);
+ const instances = actor.list(sessionId).map((instance) => {
+ const driver = getDriverManager().get(instance.instanceId);
+ const diagnostics = getDriverManager().diagnostics?.(instance.instanceId);
+ return {
+ instance: publicInstance(instance),
+ running: Boolean(driver),
+ mutation: actor.mutationState(instance.instanceId),
+ capabilityReport: diagnostics?.capabilityReport ?? null,
+ nativeSidecar: publicNativeSidecarDiagnostics(diagnostics?.nativeSidecar),
+ logTail: publicDriverLogTail(diagnostics?.logTail ?? ''),
+ };
+ });
+ const recommendedActions: string[] = [];
+ if (!environment.ready) recommendedActions.push('check_environment');
+ if (environment.ready && instances.length === 0) {
+ recommendedActions.push('list_devices', 'create_instance_or_attach_device');
+ }
+ if (instances.some((entry) => !entry.running)) recommendedActions.push('start_instance');
+ if (
+ instances.some(
+ (entry) =>
+ entry.running &&
+ entry.capabilityReport?.routes.continuousInput.fallback === true,
+ )
+ ) {
+ recommendedActions.push('continue_with_wda_mjpeg_fallback');
+ }
+ return {
+ ok: true,
+ data: {
+ environment: publicEnvironment(environment),
+ availability,
+ resource: { runningCount: resourceScheduler.runningCount(), hardLimit: 4 },
+ instances,
+ recommendedActions,
+ },
+ };
+ }
if (!environment.ready) {
const safeEnvironment = publicEnvironment(environment);
return {
@@ -2954,6 +3607,32 @@ export function getIOSSimulatorMcpDeps(
): IOSSimulatorMcpDeps {
const host = options.host ?? defaultIOSSimulatorHost;
return {
+ describeTools: async (context) => {
+ const sessionId = context?.sessionId?.trim();
+ if (!sessionId) {
+ return {
+ ready: false,
+ instanceCount: 0,
+ runningInstanceCount: 0,
+ tools: {
+ doctor: { state: 'unavailable', reasonCode: 'SESSION_CONTEXT_REQUIRED' },
+ check_environment: { state: 'unavailable', reasonCode: 'SESSION_CONTEXT_REQUIRED' },
+ },
+ };
+ }
+ if (options.isIOSSimulatorEnabled && !options.isIOSSimulatorEnabled()) {
+ return {
+ ready: false,
+ instanceCount: 0,
+ runningInstanceCount: 0,
+ tools: {
+ doctor: { state: 'unavailable', reasonCode: 'IOS_SIMULATOR_DISABLED' },
+ check_environment: { state: 'unavailable', reasonCode: 'IOS_SIMULATOR_DISABLED' },
+ },
+ };
+ }
+ return host.describeTools(sessionId);
+ },
callTool: async (name, args, context) => {
if (options.isIOSSimulatorEnabled && !options.isIOSSimulatorEnabled()) {
return {
diff --git a/docs/ios-simulator-integration-plan.md b/docs/ios-simulator-integration-plan.md
index faec5f5017..797a8e20aa 100644
--- a/docs/ios-simulator-integration-plan.md
+++ b/docs/ios-simulator-integration-plan.md
@@ -8,7 +8,7 @@
>
> 适用平台:macOS
>
-> 更新时间:2026-07-25
+> 更新时间:2026-08-04
## 0. 当前实施状态
@@ -263,33 +263,92 @@ MiniSim 是 Swift/AppKit 菜单栏应用。它通过 `xcrun simctl list ... -j`
| 最多 4 个 pane | Phase 3 才有多实例 | 保持 Phase 3 实施,但从 Phase 1 起数据模型和 UI registry 不假设 singleton device |
| 截图/录屏到 Desktop | `cindy-media` | 保持 Cindy 专属差异,所有持久媒体进总仓 |
-## 6. 已验证技术边界
+### 5.6 插件化、MCP 与 Host Capability 的边界
-### 6.1 Apple 官方工具能做什么
+Cindy 的 MCP 是 Agent 调用宿主能力的结构化入口,但它不是模拟器画面传输层,也不是
+Sidecar 的生命周期 owner。插件化设计应把工作流和垂直交互与宿主级原生能力分开。
-`simctl` 适合:
+#### 5.6.1 Cindy 当前 MCP 的调用链
-- list/create/clone/boot/bootstatus/shutdown/delete/erase。
-- install/uninstall/launch/terminate/openurl。
-- privacy、push、location、status bar、appearance 等设备状态操作。
-- screenshot 和 video record。
+当前 iOS Simulator 能力由 Cindy Host 注册并注入 Agent-facing MCP provider:
-`xcodebuild` 适合:
+~~~text
+Agent
+ ↓ cindy_ios_simulator MCP
+Lizi MCP server / tool registry
+ ↓ 带 sessionId 的结构化请求
+Cindy Desktop main host
+ ↓ ownership / lease / device grant / generation / admission
+WDA 或 Native Sidecar
+ ↓
+CoreSimulator device
+~~~
-- project/workspace/scheme/configuration/destination 构建。
-- test 和 `.xcresult` 产出。
-- 构建日志与错误定位。
+cindy_ios_simulator 由 Host 创建并绑定当前 Session。它通过 list_tools 暴露稳定的
+设备工作流,再通过 call_tool 调用经过 registry 校验的具体工具。请求包含当前 Session
+上下文;设备 mutation 还必须携带 instance、generation 和 lease,不能由模型自行指定一个
+任意设备或绕过 Host policy。
-它们不直接提供:
+因此,Agent 可以通过这个 MCP 请求:
-- 通用的 tap、swipe、输入文本、Home 等交互 API。
-- 可嵌入 Electron 的实时 Simulator surface。
-- Session 归属和多实例仲裁。
+- 检查环境、列出设备、创建或 attach instance;
+- 启动、停止、解绑和恢复 Simulator instance;
+- build、install、launch、terminate、open URL;
+- 获取 screen map、截图和诊断;
+- 执行 tap、swipe、文本输入、Home、连续单指和双指 HID。
-### 6.2 截图轮询不能当实时流
+这些动作最终都进入 Desktop main 的同一个 Host 状态机;右侧栏 UI 不会另起一套生命周期。
-本机 Xcode 26.4、1206×2622 PNG 的 `simctl io screenshot` 实测约 7.3 FPS。该数字只说明可以用于低频快照或极低资源预览,不能满足流畅的人机协同:
+#### 5.6.2 MCP、Host IPC 与 Native Sidecar 的分工
+三条链路职责不同:
+
+| 层 | 负责什么 | 不负责什么 |
+| --- | --- | --- |
+| Agent-facing MCP | 工具发现、参数校验、结构化调用和业务错误 | 不直接读 IOSurface、不拥有设备、不执行 Sidecar |
+| Host service / typed IPC | Session ownership、grant、admission、生命周期、恢复、WDA/Sidecar 选择;向 Renderer 推送状态和媒体帧 | 不把原始宿主路径、token 或 Sidecar 句柄暴露给插件/Agent |
+| Native Sidecar protocol | Host 与 Swift helper 的 stdio framed transport;IOSurface capture、VideoToolbox H.264、native HID | 不决定是否可信、不决定是否准入、不直接服务模型 |
+
+H.264 和 JPEG 不通过 MCP 传输。MCP 返回操作结果或短诊断;持续媒体由 Main 的 frame pump
+经 typed IPC 送到 Renderer,再由 Renderer 解码/显示。点击和滑动也不是 MCP 自己模拟
+出来的:Agent 通过 MCP 发出结构化 mutation,Host 根据 capability route 选择 WDA 语义
+操作或 Native HID。
+
+#### 5.6.3 与插件的边界
+
+推荐的混合形态是:
+
+~~~text
+Cindy Host
+├── IOSSimulatorCapabilitySlot
+├── ownership / lease / grant / lifecycle / recovery
+├── WDA + MJPEG fallback
+├── Native Sidecar + IOSurface / H.264 / HID
+├── artifact trust / sandbox / admission
+└── 内嵌右侧 Simulator panel
+
+可选 iOS 工作流插件
+├── build/debug/performance Skills
+├── Xcode/构建/测试工具的 MCP 配置
+├── workflow prompts、诊断模板和项目约定
+├── 可选浏览器 preview adapter
+└── 可选 Sidecar artifact candidate(只能交给 Host 验证)
+~~~
+
+插件负责工作流、工具声明、结构化 UI 和项目适配;Host 负责通用且必须受控的原生能力。
+插件可以携带外部工具文件或 Sidecar candidate,但不能自行执行它们,也不能把
+source: plugin 当成可信证明。Host 必须在启动前重新验证签名、摘要、架构以及 Xcode/iOS
+runtime 的精确兼容矩阵,再决定是否授予 H.264、连续 HID 或其它 capability。
+
+插件禁用、升级、卸载和崩溃只调用 Host 的 provider/supervisor 生命周期入口。Sidecar
+artifact 的最终执行权、设备 ownership、媒体传输、权限和恢复都不下放给插件沙箱。
+
+结论:不要把完整 iOS Simulator runtime 塞进 .cindy 插件。将来可以把 iOS 开发工作流
+做成官方插件,但 Cindy 的内嵌画面、低延迟点击/拖动和原生生命周期必须继续由 Host-owned
+capability slot 提供。
+
+本节是 Phase 4E 的产品边界补充:Phase 4E 抽象的是 Host capability provider、artifact
+resolver、admission policy 与 supervisor,不意味着把完整 native runtime 移入插件沙箱。
- PNG 编码、文件 IO 和 Electron 解码成本过高。
- 输入后的视觉反馈延迟明显。
- 多实例时资源消耗线性放大。
@@ -957,6 +1016,18 @@ MVP 规则:
| `start_recording` | 开始显式录屏 |
| `stop_recording` | 停止并摄入 `cindy-media` |
+### 13.1.1 稳定性扩展工具与动作契约
+
+在 MVP 工具之上,Host 已提供一组面向 Agent 的确定性稳定性能力:
+
+- `doctor`:一次有界诊断,汇总环境、实例归属、driver/capability、资源状态、脱敏日志尾部和下一步建议;不返回端口、绝对路径、token 或 private framework 细节。
+- `wait_for_ui`:按 `element_exists`、`element_missing`、`screen_changed` 或 `screen_stable` 轮询无障碍 screen map;有超时和 takeover AbortSignal,超时返回稳定的 `UI_WAIT_TIMEOUT`。
+- `observeAfter`:`tap`、`swipe`、`touch_path`、`touch2_path`、`type_text`、`press_home`、`drag`、`long_press` 和 `key_press` 可选择 `none`、`immediate` 或有界 `stable` 观察,并在成功时返回新的 screen map。
+- 语义动作:`drag` 与 `long_press` 使用 screen map 元素中心点,优先 Native HID、否则 WDA;`key_press` 只接受受限 WebDriver key 集合。
+- `batch`:最多 16 步、只允许 tap/swipe/drag/long_press/type_text/key_press;固定同一 instance/generation/lease,每步刷新 screen map,首个失败立即停止,不包含生命周期、构建、权限或文件操作。
+
+`list_tools` 在 MCP 和 Codex dynamic gateway 两条入口都带 Host 计算出的 capability availability(`available`、`requires-instance`、`instance-dependent`、`unavailable` 以及 backend/reasonCode)。availability 只用于发现和解释,最终执行仍由 Host 的 ownership、lease、generation 和 admission policy 再次校验。
+
Agent 对设备的控制、install/launch、tap/type 和模型截图在首次使用设备时必须先经过 UI 的 per-device consent;授权操作本身不暴露给 Agent 工具。用户拒绝后,pane 的查看和手动输入仍可用,Agent mutation 返回 `DEVICE_CONTROL_NOT_GRANTED`。`build_app` 与 `open_url` 还要分别经过现有 Session permission mode,设备授权不能替代它们。
### 13.2 后续工具
diff --git a/packages/ios-simulator-runtime/src/instance-errors.ts b/packages/ios-simulator-runtime/src/instance-errors.ts
index 02cedbe7ae..490f989630 100644
--- a/packages/ios-simulator-runtime/src/instance-errors.ts
+++ b/packages/ios-simulator-runtime/src/instance-errors.ts
@@ -12,6 +12,7 @@ export const IOS_SIMULATOR_INSTANCE_ERROR_CODES = [
"LEASE_EXPIRED",
"STALE_GENERATION",
"STALE_UI_SNAPSHOT",
+ "UI_WAIT_TIMEOUT",
"NATIVE_INPUT_UNAVAILABLE",
"INVALID_INSTANCE_STATE",
"SIMULATOR_NOT_FOUND",
diff --git a/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.ts b/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.ts
index 62104b12fe..ea9739733f 100644
--- a/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.ts
+++ b/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.ts
@@ -55,6 +55,7 @@ describe("createIOSSimulatorMcpServer", () => {
const payload = JSON.parse(readResultText(result));
expect(payload.tools.map((tool: { name: string }) => tool.name)).toEqual([
"check_environment",
+ "doctor",
"list_devices",
"list_instances",
"create_instance",
@@ -65,8 +66,13 @@ describe("createIOSSimulatorMcpServer", () => {
"get_screen_map",
"audit_accessibility",
"compare_screen_maps",
+ "wait_for_ui",
"tap",
"swipe",
+ "drag",
+ "long_press",
+ "key_press",
+ "batch",
"touch_path",
"touch2_path",
"type_text",
@@ -109,6 +115,88 @@ describe("createIOSSimulatorMcpServer", () => {
await Promise.all([client.close(), server.close()]);
});
+ it("includes Host capability availability in progressive discovery", async () => {
+ const describeTools = vi.fn(async () => ({
+ ready: true,
+ instanceCount: 1,
+ runningInstanceCount: 1,
+ tools: {
+ doctor: { state: "available" as const, backend: "host" as const },
+ wait_for_ui: { state: "available" as const, backend: "wda" as const },
+ drag: { state: "available" as const, backend: "native-hid" as const },
+ },
+ }));
+ const { client, server } = await connect(
+ { callTool: vi.fn(), describeTools },
+ "session-a",
+ );
+
+ const result = await client.callTool({ name: "list_tools", arguments: {} });
+ const payload = JSON.parse(readResultText(result));
+
+ expect(describeTools).toHaveBeenCalledWith({
+ sessionId: "session-a",
+ origin: "agent",
+ });
+ expect(payload.availability).toMatchObject({
+ ready: true,
+ instanceCount: 1,
+ runningInstanceCount: 1,
+ });
+ expect(
+ payload.tools.find((tool: { name: string }) => tool.name === "drag"),
+ ).toMatchObject({
+ availability: { state: "available", backend: "native-hid" },
+ });
+ await Promise.all([client.close(), server.close()]);
+ });
+
+ it("rejects invalid high-level UI arguments before calling the Host", async () => {
+ const callTool = vi.fn();
+ const { client, server } = await connect({ callTool }, "session-a");
+ const route = {
+ instanceId: "instance-a",
+ generation: 1,
+ leaseId: "lease-a",
+ snapshotId: "dbe4ecda-0e96-43d7-8419-d73dc62b5d03",
+ };
+ const invalidCalls = [
+ {
+ name: "wait_for_ui",
+ args: {
+ ...route,
+ condition: { kind: "element_exists", selector: {} },
+ },
+ },
+ { name: "tap", args: { ...route, elementId: "element-a", observeAfter: "later" } },
+ {
+ name: "long_press",
+ args: { ...route, elementId: "element-a", durationMs: 299 },
+ },
+ { name: "key_press", args: { ...route, key: "space" } },
+ {
+ name: "batch",
+ args: {
+ ...route,
+ actions: Array.from({ length: 17 }, () => ({ type: "key_press", key: "return" })),
+ },
+ },
+ ];
+
+ for (const invocation of invalidCalls) {
+ const result = await client.callTool({
+ name: "call_tool",
+ arguments: invocation,
+ });
+ expect(result.isError).toBe(true);
+ expect(JSON.parse(readResultText(result))).toMatchObject({
+ errorCode: "INVALID_ARGS",
+ });
+ }
+ expect(callTool).not.toHaveBeenCalled();
+ await Promise.all([client.close(), server.close()]);
+ });
+
it("validates mutation routes before calling the host", async () => {
const callTool = vi.fn();
const { client, server } = await connect({ callTool }, "session-a");
diff --git a/packages/lizi-mcps/src/ios-simulator/server.ts b/packages/lizi-mcps/src/ios-simulator/server.ts
index ec08b9d2cd..da7c7444e3 100644
--- a/packages/lizi-mcps/src/ios-simulator/server.ts
+++ b/packages/lizi-mcps/src/ios-simulator/server.ts
@@ -50,20 +50,29 @@ export function createIOSSimulatorMcpServer(
"list_tools",
"Discover Cindy's embedded iOS Simulator tools. This is the preferred entry point for opening, running, testing, or debugging an iOS app in Cindy. Do not use cindy_computer to launch macOS Simulator.app unless the user explicitly requests an external system window. Start with check_environment before selecting a device.",
{ category: z.enum(["ios_simulator"]).optional() },
- async () => ({
- content: [
- {
- type: "text" as const,
- text: JSON.stringify({
- ok: true,
- category: "ios_simulator",
- tools: registry.list(),
- workflow:
- "Use this embedded viewer workflow: check_environment, then list_devices and either create_instance or attach_device, then start_instance. Build, install, and launch the app through this server. Route mutations with instanceId, generation, and leaseId.",
- }),
- },
- ],
- }),
+ async () => {
+ const availability = options.getSessionContext
+ ? await deps.describeTools?.({
+ sessionId: options.getSessionContext().sessionId,
+ origin: "agent",
+ })
+ : await deps.describeTools?.({ sessionId: options.sessionId, origin: "agent" });
+ return {
+ content: [
+ {
+ type: "text" as const,
+ text: JSON.stringify({
+ ok: true,
+ category: "ios_simulator",
+ tools: registry.list(availability?.tools),
+ ...(availability ? { availability } : {}),
+ workflow:
+ "Use this embedded viewer workflow: check_environment, then list_devices and either create_instance or attach_device, then start_instance. Build, install, and launch the app through this server. Route mutations with instanceId, generation, and leaseId.",
+ }),
+ },
+ ],
+ };
+ },
);
server.tool(
"call_tool",
diff --git a/packages/lizi-mcps/src/ios-simulator/tool-registry.ts b/packages/lizi-mcps/src/ios-simulator/tool-registry.ts
index 582cd2a6a1..d7517eb149 100644
--- a/packages/lizi-mcps/src/ios-simulator/tool-registry.ts
+++ b/packages/lizi-mcps/src/ios-simulator/tool-registry.ts
@@ -1,6 +1,9 @@
import { z } from "zod";
-import type { IOSSimulatorMcpErrorCode } from "../types.js";
+import type {
+ IOSSimulatorMcpErrorCode,
+ IOSSimulatorToolAvailability,
+} from "../types.js";
export type IOSSimulatorToolContentBlock = { type: "text"; text: string };
@@ -69,12 +72,30 @@ export class IOSSimulatorToolRegistry {
} as unknown as IOSSimulatorToolDefinition);
}
- list(): Array<{ name: string; description: string; readOnly: boolean }> {
+ list(
+ availability: Record<string, IOSSimulatorToolAvailability> = {},
+ ): Array<{
+ name: string;
+ description: string;
+ readOnly: boolean;
+ availability?: IOSSimulatorToolAvailability;
+ }> {
+ const hasAvailability = Object.keys(availability).length > 0;
return Array.from(this.tools.values()).map(
({ name, description, readOnly }) => ({
name,
description,
readOnly,
+ ...(hasAvailability
+ ? {
+ availability:
+ availability[name] ??
+ ({
+ state: "unavailable",
+ reasonCode: "TOOL_NOT_REPORTED",
+ } satisfies IOSSimulatorToolAvailability),
+ }
+ : {}),
}),
);
}
diff --git a/packages/lizi-mcps/src/ios-simulator/tools.ts b/packages/lizi-mcps/src/ios-simulator/tools.ts
index 0a6f48bea2..1247653402 100644
--- a/packages/lizi-mcps/src/ios-simulator/tools.ts
+++ b/packages/lizi-mcps/src/ios-simulator/tools.ts
@@ -59,6 +59,75 @@ async function callHost(
}
}
+const observeAfterShape = {
+ observeAfter: z.enum(["none", "immediate", "stable"]).default("none"),
+ observeTimeoutMs: z.number().int().min(100).max(15_000).default(3_000),
+ stableForMs: z.number().int().min(100).max(2_000).default(300),
+};
+
+const uiElementConditionShape = {
+ elementId: z.string().min(1).max(128).optional(),
+ role: z.string().min(1).max(128).optional(),
+ labelContains: z.string().min(1).max(500).optional(),
+ valueContains: z.string().min(1).max(500).optional(),
+};
+
+const uiElementCondition = z
+ .object(uiElementConditionShape)
+ .strict()
+ .refine((value) => Object.values(value).some((entry) => entry !== undefined), {
+ message: "At least one element selector is required.",
+ });
+
+const waitCondition = z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("element_exists"), selector: uiElementCondition }).strict(),
+ z.object({ kind: z.literal("element_missing"), selector: uiElementCondition }).strict(),
+ z.object({ kind: z.literal("screen_changed"), snapshotId: z.string().uuid() }).strict(),
+ z.object({ kind: z.literal("screen_stable") }).strict(),
+]);
+
+const keyName = z.enum([
+ "return",
+ "tab",
+ "escape",
+ "delete",
+ "arrow_up",
+ "arrow_down",
+ "arrow_left",
+ "arrow_right",
+]);
+
+const batchAction = z.discriminatedUnion("type", [
+ z.object({ type: z.literal("tap"), elementId: z.string().min(1).max(128) }).strict(),
+ z
+ .object({
+ type: z.literal("swipe"),
+ startX: z.number().finite().nonnegative().max(1_000_000),
+ startY: z.number().finite().nonnegative().max(1_000_000),
+ endX: z.number().finite().nonnegative().max(1_000_000),
+ endY: z.number().finite().nonnegative().max(1_000_000),
+ durationMs: z.number().int().min(50).max(10_000).default(300),
+ })
+ .strict(),
+ z
+ .object({
+ type: z.literal("drag"),
+ fromElementId: z.string().min(1).max(128),
+ toElementId: z.string().min(1).max(128),
+ durationMs: z.number().int().min(100).max(10_000).default(500),
+ })
+ .strict(),
+ z
+ .object({
+ type: z.literal("long_press"),
+ elementId: z.string().min(1).max(128),
+ durationMs: z.number().int().min(300).max(10_000).default(750),
+ })
+ .strict(),
+ z.object({ type: z.literal("type_text"), text: z.string().max(10_000) }).strict(),
+ z.object({ type: z.literal("key_press"), key: keyName }).strict(),
+]);
+
export function registerIOSSimulatorTools(
registry: IOSSimulatorToolRegistry,
deps: IOSSimulatorMcpDeps,
@@ -73,6 +142,14 @@ export function registerIOSSimulatorTools(
handler: async () =>
callHost(deps, "check_environment", {}, getContext?.()),
});
+ registry.register({
+ name: "doctor",
+ description:
+ "Run one bounded Host diagnosis for the current Cindy session, including environment, ownership, drivers, admitted capabilities, tool availability, and recommended next actions.",
+ readOnly: true,
+ inputShape: {},
+ handler: async () => callHost(deps, "doctor", {}, getContext?.()),
+ });
registry.register({
name: "list_devices",
description:
@@ -225,6 +302,20 @@ export function registerIOSSimulatorTools(
handler: async (args) =>
callHost(deps, "compare_screen_maps", args, getContext?.()),
});
+ registry.register({
+ name: "wait_for_ui",
+ description:
+ "Wait for one bounded accessibility condition without fixed sleeps, then return a fresh screen map.",
+ readOnly: true,
+ inputShape: {
+ ...routeShape,
+ condition: waitCondition,
+ timeoutMs: z.number().int().min(100).max(30_000).default(10_000),
+ pollIntervalMs: z.number().int().min(100).max(2_000).default(250),
+ stableForMs: z.number().int().min(100).max(2_000).default(300),
+ },
+ handler: async (args) => callHost(deps, "wait_for_ui", args, getContext?.()),
+ });
registry.register({
name: "tap",
description:
@@ -234,6 +325,7 @@ export function registerIOSSimulatorTools(
elementId: z.string().min(1).max(128).optional(),
x: z.number().finite().nonnegative().max(1_000_000).optional(),
y: z.number().finite().nonnegative().max(1_000_000).optional(),
+ ...observeAfterShape,
},
handler: async (args) => callHost(deps, "tap", args, getContext?.()),
});
@@ -248,9 +340,59 @@ export function registerIOSSimulatorTools(
endX: z.number().finite().nonnegative().max(1_000_000),
endY: z.number().finite().nonnegative().max(1_000_000),
durationMs: z.number().int().min(50).max(60_000).default(300),
+ ...observeAfterShape,
},
handler: async (args) => callHost(deps, "swipe", args, getContext?.()),
});
+ registry.register({
+ name: "drag",
+ description:
+ "Drag from one element in the current screen map to another using native HID when admitted and WDA otherwise.",
+ inputShape: {
+ ...snapshotRouteShape,
+ fromElementId: z.string().min(1).max(128),
+ toElementId: z.string().min(1).max(128),
+ durationMs: z.number().int().min(100).max(10_000).default(500),
+ ...observeAfterShape,
+ },
+ handler: async (args) => callHost(deps, "drag", args, getContext?.()),
+ });
+ registry.register({
+ name: "long_press",
+ description:
+ "Long-press an element from the current screen map for a bounded duration.",
+ inputShape: {
+ ...snapshotRouteShape,
+ elementId: z.string().min(1).max(128),
+ durationMs: z.number().int().min(300).max(10_000).default(750),
+ ...observeAfterShape,
+ },
+ handler: async (args) => callHost(deps, "long_press", args, getContext?.()),
+ });
+ registry.register({
+ name: "key_press",
+ description:
+ "Send one bounded WebDriver keyboard key to the currently focused control.",
+ inputShape: {
+ ...snapshotRouteShape,
+ key: keyName,
+ ...observeAfterShape,
+ },
+ handler: async (args) => callHost(deps, "key_press", args, getContext?.()),
+ });
+ registry.register({
+ name: "batch",
+ description:
+ "Run up to 16 low-risk UI actions against one instance route, stopping on the first failure and returning a final observation.",
+ inputShape: {
+ ...snapshotRouteShape,
+ actions: z.array(batchAction).min(1).max(16),
+ observeAfter: z.enum(["immediate", "stable"]).default("stable"),
+ observeTimeoutMs: z.number().int().min(100).max(15_000).default(3_000),
+ stableForMs: z.number().int().min(100).max(2_000).default(300),
+ },
+ handler: async (args) => callHost(deps, "batch", args, getContext?.()),
+ });
const touchSampleShape = z.object({
phase: z.enum(["down", "move", "up", "cancel"]),
x: z.number().finite().nonnegative().max(1_000_000),
@@ -265,6 +407,7 @@ export function registerIOSSimulatorTools(
...snapshotRouteShape,
points: z.array(touchSampleShape).min(2).max(4_096),
edge: z.enum(["none", "left", "top", "bottom", "right"]).default("none"),
+ ...observeAfterShape,
},
handler: async (args) => callHost(deps, "touch_path", args, getContext?.()),
});
@@ -276,6 +419,7 @@ export function registerIOSSimulatorTools(
...snapshotRouteShape,
first: z.array(touchSampleShape).min(2).max(4_096),
second: z.array(touchSampleShape).min(2).max(4_096),
+ ...observeAfterShape,
},
handler: async (args) =>
callHost(deps, "touch2_path", args, getContext?.()),
@@ -286,6 +430,7 @@ export function registerIOSSimulatorTools(
inputShape: {
...snapshotRouteShape,
text: z.string().max(10_000),
+ ...observeAfterShape,
},
handler: async (args) => callHost(deps, "type_text", args, getContext?.()),
});
@@ -293,7 +438,7 @@ export function registerIOSSimulatorTools(
name: "press_home",
description:
"Press the simulated Home button after observing the current screen map.",
- inputShape: snapshotRouteShape,
+ inputShape: { ...snapshotRouteShape, ...observeAfterShape },
handler: async (args) => callHost(deps, "press_home", args, getContext?.()),
});
registry.register({
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index 94b7ba1360..c679703b16 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -725,8 +725,28 @@ export type IOSSimulatorMcpErrorCode =
| "ORIENTATION_UNSUPPORTED"
| "IOS_SIMULATOR_HOST_ERROR";
+export type IOSSimulatorToolAvailabilityState =
+ | "available"
+ | "requires-instance"
+ | "instance-dependent"
+ | "unavailable";
+
+export interface IOSSimulatorToolAvailability {
+ state: IOSSimulatorToolAvailabilityState;
+ reasonCode?: string;
+ backend?: "wda" | "native-hid" | "simctl" | "host";
+}
+
+export interface IOSSimulatorToolAvailabilityReport {
+ ready: boolean;
+ instanceCount: number;
+ runningInstanceCount: number;
+ tools: Record<string, IOSSimulatorToolAvailability>;
+}
+
export type IOSSimulatorMcpToolName =
| "check_environment"
+ | "doctor"
| "list_devices"
| "list_instances"
| "create_instance"
@@ -737,8 +757,13 @@ export type IOSSimulatorMcpToolName =
| "get_screen_map"
| "audit_accessibility"
| "compare_screen_maps"
+ | "wait_for_ui"
| "tap"
| "swipe"
+ | "drag"
+ | "long_press"
+ | "key_press"
+ | "batch"
| "touch_path"
| "touch2_path"
| "type_text"
@@ -783,6 +808,9 @@ export interface IOSSimulatorMcpDeps {
args: Record<string, unknown>,
context?: IOSSimulatorMcpCallContext,
): Promise<unknown>;
+ describeTools?(
+ context?: IOSSimulatorMcpCallContext,
+ ): Promise<IOSSimulatorToolAvailabilityReport>;
logger?: LiziMcpLogger;
}