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): validate mobile launch on exact device

JiangJiahao5bea657debbd
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 ccf8ebe594..bb2a24cf19 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
@@ -5725,6 +5725,8 @@ describe('iOS Simulator host', () => {
expectedSource: 'branch@commit',
currentSourceOnExpectedPort: true,
anyMetro: true,
+ targetSimulatorUdid: READY_REPORT.devices[0]!.udid,
+ targetBooted: true,
}));
const projectBuilder: IOSSimulatorProjectBuilderAdapter = {
build: buildProject,
@@ -5870,7 +5872,10 @@ describe('iOS Simulator host', () => {
{ sessionId: 'session-a', origin: 'user' },
),
).resolves.toMatchObject({ ok: true });
- expect(validateLaunch).toHaveBeenCalledWith('/tmp/session-a');
+ expect(validateLaunch).toHaveBeenCalledWith(
+ '/tmp/session-a',
+ READY_REPORT.devices[0]!.udid,
+ );
await host.callTool(
'terminate_app',
{ ...route, artifactId: artifact.artifactId },
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 69cf92cc27..d849afba73 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -5035,7 +5035,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
requireControlGrant(instance, context);
const stored = appArtifacts.get(artifactId);
if (stored?.projectKind === 'cindy-mobile' && projectBuilder.validateLaunch) {
- await projectBuilder.validateLaunch(stored.artifact.worktreeRoot);
+ await projectBuilder.validateLaunch(
+ stored.artifact.worktreeRoot,
+ instance.simulatorUdid,
+ );
}
await appLifecycle.launchExact(
instance.simulatorUdid,
diff --git a/apps/mobile/scripts/lib/sim-whoami.mjs b/apps/mobile/scripts/lib/sim-whoami.mjs
index a71c13dda2..3891989008 100644
--- a/apps/mobile/scripts/lib/sim-whoami.mjs
+++ b/apps/mobile/scripts/lib/sim-whoami.mjs
@@ -5,6 +5,54 @@ import { mobileClientBundleEnv } from '../../../../scripts/shared/client-endpoin
import { withLocalMobileRegionConfig } from './mobile-dev-region.mjs';
const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
+const SIMULATOR_UDID_PATTERN = /^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/;
+
+/** Parse one optional exact Simulator target without changing sim:start arguments. */
+export function extractSimWhoamiUdidArgs(args) {
+ let simulatorUdid = null;
+ const passthrough = [];
+
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+ let value = null;
+ if (arg === '--udid') {
+ value = args[++index];
+ } else if (arg.startsWith('--udid=')) {
+ value = arg.slice('--udid='.length);
+ } else {
+ passthrough.push(arg);
+ continue;
+ }
+
+ if (simulatorUdid !== null) throw new Error('Simulator UDID 只能传一次');
+ const normalized = String(value ?? '').trim().toUpperCase();
+ if (!SIMULATOR_UDID_PATTERN.test(normalized)) {
+ throw new Error(`Simulator UDID 无效: ${value ?? '(缺失)'}`);
+ }
+ simulatorUdid = normalized;
+ }
+
+ return { simulatorUdid, passthrough };
+}
+
+/** Select only the exact booted device when Host supplies a Simulator target. */
+export function bootedSimulatorLinesForTarget(lines, simulatorUdid) {
+ const booted = lines.filter((line) => /\(Booted\)/.test(line));
+ if (!simulatorUdid) return booted;
+ const exactUdid = simulatorUdid.toUpperCase();
+ return booted.filter((line) => line.toUpperCase().includes(`(${exactUdid})`));
+}
+
+/** Probe app installation on the exact Host-owned Simulator without fallback. */
+export function getSimulatorAppContainer(run, simulatorUdid, bundleId) {
+ return run('xcrun', [
+ 'simctl',
+ 'get_app_container',
+ simulatorUdid ?? 'booted',
+ bundleId,
+ 'app',
+ ]);
+}
/** Parse the optional Metro port shared by sim:start and sim:whoami. */
export function extractSimMetroPortArgs(args, defaultPort = 8081) {
diff --git a/apps/mobile/scripts/sim-whoami.mjs b/apps/mobile/scripts/sim-whoami.mjs
index cd9be24dd5..85f2b123b6 100644
--- a/apps/mobile/scripts/sim-whoami.mjs
+++ b/apps/mobile/scripts/sim-whoami.mjs
@@ -23,7 +23,10 @@ import {
formatMobileLocalConfigStatus,
} from "./lib/mobile-local-config.mjs";
import {
+ bootedSimulatorLinesForTarget,
extractSimMetroPortArgs,
+ extractSimWhoamiUdidArgs,
+ getSimulatorAppContainer,
resolveMobileSimulatorBundleId,
} from "./lib/sim-whoami.mjs";
import {
@@ -44,7 +47,8 @@ function resolveTarget() {
const { region, passthrough } = extractMobileDevRegionArgs(
process.argv.slice(2).filter((arg) => arg !== "--json"),
);
- const portArgs = extractSimMetroPortArgs(passthrough);
+ const udidArgs = extractSimWhoamiUdidArgs(passthrough);
+ const portArgs = extractSimMetroPortArgs(udidArgs.passthrough);
if (portArgs.passthrough.length > 0) {
throw new Error(
`mobile:sim:whoami 不支持参数: ${portArgs.passthrough.join(" ")}`,
@@ -53,6 +57,7 @@ function resolveTarget() {
return {
region,
port: portArgs.port,
+ simulatorUdid: udidArgs.simulatorUdid,
bundleId: resolveMobileSimulatorBundleId(region),
};
}
@@ -70,7 +75,7 @@ try {
console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
-const { region, port: expectedPort, bundleId } = target;
+const { region, port: expectedPort, simulatorUdid, bundleId } = target;
const ports = [...new Set([...PORTS, expectedPort])].sort((a, b) => a - b);
const expectedSource = gitSourceIdentity(worktreeRoot);
let healthy = true;
@@ -99,24 +104,26 @@ function shFile(command, args) {
console.log(`==> Mobile dev region: ${region}`);
console.log("==== booted 模拟器 ====");
-const booted = sh("xcrun simctl list devices booted")
- .split("\n")
- .filter((l) => /\(Booted\)/.test(l));
+const allBooted = sh("xcrun simctl list devices booted").split("\n");
+const booted = bootedSimulatorLinesForTarget(allBooted, null);
+const targetBooted = bootedSimulatorLinesForTarget(allBooted, simulatorUdid);
if (booted.length === 0) {
console.log(" (没有 booted 模拟器)");
healthy = false;
} else booted.forEach((l) => console.log(" " + l.trim()));
+if (simulatorUdid && targetBooted.length === 0) {
+ console.log(` (目标模拟器 ${simulatorUdid} 未启动)`);
+ healthy = false;
+}
console.log(`\n==== 模拟器里装的 ${bundleId}(native 安装包版本)====`);
-const container = shFile("xcrun", [
- "simctl",
- "get_app_container",
- "booted",
- bundleId,
- "app",
-]);
+const container = getSimulatorAppContainer(shFile, simulatorUdid, bundleId);
if (!container) {
- console.log(" (未安装 / 无 booted 设备)");
+ console.log(
+ simulatorUdid
+ ? ` (目标模拟器 ${simulatorUdid} 未安装 / 未启动)`
+ : " (未安装 / 无 booted 设备)",
+ );
healthy = false;
} else {
const plist = `${container}/Info.plist`;
@@ -185,6 +192,8 @@ if (jsonOutput) {
currentSourceOnExpectedPort,
anyMetro,
bootedCount: booted.length,
+ targetSimulatorUdid: simulatorUdid,
+ targetBooted: targetBooted.length === 1,
bundleId,
}),
);
diff --git a/apps/mobile/src/__tests__/mobileSimWhoami.test.ts b/apps/mobile/src/__tests__/mobileSimWhoami.test.ts
index 73bb5d6cc9..c38e06fe13 100644
--- a/apps/mobile/src/__tests__/mobileSimWhoami.test.ts
+++ b/apps/mobile/src/__tests__/mobileSimWhoami.test.ts
@@ -1,10 +1,15 @@
// @ts-nocheck —— 被测对象是 .mjs 开发工具模块,vitest 跑其纯函数。
import { describe, expect, it, vi } from 'vitest';
import {
+ bootedSimulatorLinesForTarget,
extractSimMetroPortArgs,
+ extractSimWhoamiUdidArgs,
+ getSimulatorAppContainer,
resolveMobileSimulatorBundleId,
} from '../../scripts/lib/sim-whoami.mjs';
+const SIMULATOR_UDID = 'A1B2C3D4-E5F6-47A8-9B0C-D1E2F3A4B5C6';
+
describe('mobile:sim:whoami Metro port', () => {
it.each([
[['--port', '8082'], 8082],
@@ -29,6 +34,61 @@ describe('mobile:sim:whoami Metro port', () => {
});
});
+describe('mobile:sim:whoami exact Simulator target', () => {
+ it.each([
+ [['--udid', SIMULATOR_UDID.toLowerCase()]],
+ [[`--udid=${SIMULATOR_UDID}`]],
+ ])('accepts and canonicalizes an exact UDID from %j', (args) => {
+ expect(extractSimWhoamiUdidArgs(args)).toEqual({
+ simulatorUdid: SIMULATOR_UDID,
+ passthrough: [],
+ });
+ });
+
+ it('keeps manual whoami compatible when no target is supplied', () => {
+ expect(extractSimWhoamiUdidArgs(['--port', '8082'])).toEqual({
+ simulatorUdid: null,
+ passthrough: ['--port', '8082'],
+ });
+ });
+
+ it('rejects missing, invalid, or duplicate UDIDs', () => {
+ expect(() => extractSimWhoamiUdidArgs(['--udid'])).toThrow(/UDID 无效/);
+ expect(() => extractSimWhoamiUdidArgs(['--udid', 'booted'])).toThrow(/UDID 无效/);
+ expect(() =>
+ extractSimWhoamiUdidArgs(['--udid', SIMULATOR_UDID, `--udid=${SIMULATOR_UDID}`]),
+ ).toThrow(/只能传一次/);
+ });
+
+ it('does not treat another booted Simulator as the requested target', () => {
+ const otherUdid = '11111111-2222-4333-8444-555555555555';
+ const lines = [
+ `iPhone A (${SIMULATOR_UDID}) (Booted)`,
+ `iPhone B (${otherUdid}) (Booted)`,
+ 'iPhone C (AAAAAAAA-BBBB-4CCC-8DDD-EEEEEEEEEEEE) (Shutdown)',
+ ];
+
+ expect(bootedSimulatorLinesForTarget(lines, otherUdid)).toEqual([lines[1]]);
+ expect(bootedSimulatorLinesForTarget(lines, '99999999-2222-4333-8444-555555555555')).toEqual([]);
+ });
+
+ it('probes app installation on the exact target without a booted fallback', () => {
+ const run = vi.fn((_command, args) =>
+ args[2] === SIMULATOR_UDID ? '' : '/another-simulator/Cindy.app',
+ );
+
+ expect(getSimulatorAppContainer(run, SIMULATOR_UDID, 'com.example.cindy')).toBe('');
+ expect(run).toHaveBeenCalledWith('xcrun', [
+ 'simctl',
+ 'get_app_container',
+ SIMULATOR_UDID,
+ 'com.example.cindy',
+ 'app',
+ ]);
+ expect(run).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('mobile:sim:whoami bundle identity', () => {
it.each([
['cn', 'com.local.cindycn'],
diff --git a/packages/ios-simulator-runtime/src/project-adapter.test.ts b/packages/ios-simulator-runtime/src/project-adapter.test.ts
index 8f20c117b6..732e6a9a8f 100644
--- a/packages/ios-simulator-runtime/src/project-adapter.test.ts
+++ b/packages/ios-simulator-runtime/src/project-adapter.test.ts
@@ -18,6 +18,7 @@ import {
import type { IOSSimulatorCommandRunner } from "./types.js";
const roots: string[] = [];
+const SIMULATOR_UDID = "A1B2C3D4-E5F6-47A8-9B0C-D1E2F3A4B5C6";
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
@@ -62,6 +63,8 @@ describe("IOSSimulatorProjectBuilder", () => {
expectedSource: "branch@commit",
currentSourceOnExpectedPort: true,
anyMetro: true,
+ targetSimulatorUdid: SIMULATOR_UDID,
+ targetBooted: true,
})}\n`,
stderr: "",
exitCode: 0,
@@ -70,17 +73,77 @@ describe("IOSSimulatorProjectBuilder", () => {
return { stdout: "", stderr: "", exitCode: 0 };
});
const builder = new IOSSimulatorProjectBuilder({ commandRunner: { run } });
- await expect(builder.validateLaunch(root)).resolves.toMatchObject({
+ await expect(
+ builder.validateLaunch(root, SIMULATOR_UDID.toLowerCase()),
+ ).resolves.toMatchObject({
healthy: true,
expectedPort: 8081,
});
expect(run).toHaveBeenCalledWith(
"pnpm",
- ["mobile:sim:whoami", "--", "--json"],
+ [
+ "mobile:sim:whoami",
+ "--",
+ "--json",
+ "--udid",
+ SIMULATOR_UDID,
+ ],
expect.objectContaining({ cwd: await realpath(root) }),
);
});
+ it("rejects a non-exact Simulator target before launch validation", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));
+ roots.push(root);
+ const mobile = path.join(root, "apps", "mobile");
+ await mkdir(mobile, { recursive: true });
+ await writeFile(path.join(mobile, "app.config.js"), "export default {};");
+ await writeFile(
+ path.join(mobile, "package.json"),
+ JSON.stringify({ name: "mobile" }),
+ );
+ const run = vi.fn();
+ const builder = new IOSSimulatorProjectBuilder({ commandRunner: { run } });
+
+ await expect(builder.validateLaunch(root, "booted")).rejects.toMatchObject({
+ code: "INVALID_ARGUMENT",
+ });
+ expect(run).not.toHaveBeenCalled();
+ });
+
+ it("fails closed when whoami reports a different booted Simulator", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));
+ roots.push(root);
+ const mobile = path.join(root, "apps", "mobile");
+ await mkdir(mobile, { recursive: true });
+ await writeFile(path.join(mobile, "app.config.js"), "export default {};");
+ await writeFile(
+ path.join(mobile, "package.json"),
+ JSON.stringify({ name: "mobile" }),
+ );
+ const builder = new IOSSimulatorProjectBuilder({
+ commandRunner: {
+ run: vi.fn(async () => ({
+ stdout: JSON.stringify({
+ healthy: true,
+ expectedPort: 8081,
+ expectedSource: "branch@commit",
+ currentSourceOnExpectedPort: true,
+ anyMetro: true,
+ targetSimulatorUdid: "11111111-2222-4333-8444-555555555555",
+ targetBooted: true,
+ }),
+ stderr: "",
+ exitCode: 0,
+ })),
+ },
+ });
+
+ await expect(
+ builder.validateLaunch(root, SIMULATOR_UDID),
+ ).rejects.toMatchObject({ code: "METRO_NOT_READY" });
+ });
+
it("fails closed when Cindy Mobile Metro is missing or stale", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));
roots.push(root);
@@ -100,13 +163,17 @@ describe("IOSSimulatorProjectBuilder", () => {
expectedSource: "branch@commit",
currentSourceOnExpectedPort: false,
anyMetro: false,
+ targetSimulatorUdid: SIMULATOR_UDID,
+ targetBooted: true,
}),
stderr: "",
exitCode: 1,
})),
},
});
- await expect(builder.validateLaunch(root)).rejects.toMatchObject({
+ await expect(
+ builder.validateLaunch(root, SIMULATOR_UDID),
+ ).rejects.toMatchObject({
code: "METRO_NOT_READY",
});
});
diff --git a/packages/ios-simulator-runtime/src/project-adapter.ts b/packages/ios-simulator-runtime/src/project-adapter.ts
index b3c8e7e47d..820896a7d9 100644
--- a/packages/ios-simulator-runtime/src/project-adapter.ts
+++ b/packages/ios-simulator-runtime/src/project-adapter.ts
@@ -53,6 +53,8 @@ export interface IOSSimulatorMobileMetroStatus {
expectedSource: string;
currentSourceOnExpectedPort: boolean;
anyMetro: boolean;
+ targetSimulatorUdid: string;
+ targetBooted: boolean;
}
async function exists(candidate: string): Promise<boolean> {
@@ -491,12 +493,26 @@ export class IOSSimulatorProjectBuilder {
*/
async validateLaunch(
worktreeRoot: string,
+ simulatorUdid: string,
): Promise<IOSSimulatorMobileMetroStatus | null> {
const project = await this.inspect(worktreeRoot);
if (project.kind !== "cindy-mobile") return null;
+ const exactSimulatorUdid = simulatorUdid.trim().toUpperCase();
+ if (!/^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/.test(exactSimulatorUdid)) {
+ throw new IOSSimulatorInstanceError(
+ "INVALID_ARGUMENT",
+ "simulatorUdid must be an exact simulator UUID",
+ );
+ }
const result = await this.#runner.run(
"pnpm",
- ["mobile:sim:whoami", "--", "--json"],
+ [
+ "mobile:sim:whoami",
+ "--",
+ "--json",
+ "--udid",
+ exactSimulatorUdid,
+ ],
{
cwd: project.worktreeRoot,
timeoutMs: 60_000,
@@ -518,7 +534,10 @@ export class IOSSimulatorProjectBuilder {
Number.isSafeInteger(parsed.expectedPort) &&
typeof parsed.expectedSource === "string" &&
typeof parsed.currentSourceOnExpectedPort === "boolean" &&
- typeof parsed.anyMetro === "boolean"
+ typeof parsed.anyMetro === "boolean" &&
+ parsed.targetSimulatorUdid?.trim().toUpperCase() ===
+ exactSimulatorUdid &&
+ parsed.targetBooted === true
) {
status = parsed as IOSSimulatorMobileMetroStatus;
break;
@@ -530,7 +549,7 @@ export class IOSSimulatorProjectBuilder {
if (result.exitCode !== 0 || !status?.healthy) {
throw new IOSSimulatorInstanceError(
"METRO_NOT_READY",
- "Cindy Mobile Metro 8081 is not owned by this worktree or its source fingerprint is stale.",
+ "Cindy Mobile is not installed on the target simulator, or Metro 8081 is not owned by this worktree or its source fingerprint is stale.",
true,
);
}