Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): degrade unavailable x64 iOS simulator helper

JiangJiahaof5ebe5c35353
diff --git a/apps/desktop/forge-ios-simulator-helper.ts b/apps/desktop/forge-ios-simulator-helper.ts
new file mode 100644
index 0000000000..4709b618d9
--- /dev/null
+++ b/apps/desktop/forge-ios-simulator-helper.ts
@@ -0,0 +1,190 @@
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+const IOS_SIMULATOR_HELPER_BUNDLE = 'Cindy iOS Simulator Helper.app';
+const IOS_SIMULATOR_HELPER_EXECUTABLE = 'ios-simulator-sidecar';
+const IOS_SIMULATOR_HELPER_BUILD_RESULT = 'build-result.json';
+const IOS_SIMULATOR_PACKAGED_BUILD_RESULT = 'native-helper-build-result.json';
+const IOS_SIMULATOR_HELPER_UNSUPPORTED_REASON = 'simulator-kit-architecture-unavailable';
+
+type IOSSimulatorHelperBuildResult =
+ | {
+ schemaVersion: 1;
+ status: 'built';
+ targetArchitecture: 'arm64' | 'x86_64' | 'universal';
+ simulatorKitArchitectures: string[];
+ }
+ | {
+ schemaVersion: 1;
+ status: 'unsupported';
+ targetArchitecture: 'x86_64';
+ reason: typeof IOS_SIMULATOR_HELPER_UNSUPPORTED_REASON;
+ simulatorKitArchitectures: string[];
+ };
+
+function expectedHelperArchitecture(arch: string): 'arm64' | 'x86_64' | 'universal' {
+ switch (arch) {
+ case 'arm64':
+ return 'arm64';
+ case 'x64':
+ return 'x86_64';
+ case 'universal':
+ return 'universal';
+ default:
+ throw new Error(`[forge:postPackage] unsupported iOS Simulator helper arch: ${arch}`);
+ }
+}
+
+function simulatorKitSupportsArchitecture(architectures: string[], target: string): boolean {
+ if (target === 'arm64') {
+ return architectures.includes('arm64') || architectures.includes('arm64e');
+ }
+ return architectures.includes(target);
+}
+
+function readBuildResult(resultPath: string): IOSSimulatorHelperBuildResult {
+ let value: unknown;
+ try {
+ value = JSON.parse(fs.readFileSync(resultPath, 'utf8'));
+ } catch (error) {
+ throw new Error(
+ `[forge:postPackage] invalid iOS Simulator helper build result at ${resultPath}: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
+ if (!value || typeof value !== 'object') {
+ throw new Error(
+ `[forge:postPackage] invalid iOS Simulator helper build result at ${resultPath}`,
+ );
+ }
+ const result = value as Record<string, unknown>;
+ const simulatorKitArchitectures = Array.isArray(result.simulatorKitArchitectures)
+ ? result.simulatorKitArchitectures
+ : null;
+ const commonValid =
+ result.schemaVersion === 1 &&
+ simulatorKitArchitectures !== null &&
+ simulatorKitArchitectures.every((item) => typeof item === 'string');
+ const builtValid =
+ result.status === 'built' &&
+ (result.targetArchitecture === 'arm64' ||
+ result.targetArchitecture === 'x86_64' ||
+ result.targetArchitecture === 'universal');
+ const unsupportedValid =
+ result.status === 'unsupported' &&
+ result.targetArchitecture === 'x86_64' &&
+ result.reason === IOS_SIMULATOR_HELPER_UNSUPPORTED_REASON &&
+ simulatorKitArchitectures !== null &&
+ simulatorKitArchitectures.length > 0 &&
+ !simulatorKitArchitectures.includes('x86_64');
+ if (!commonValid || (!builtValid && !unsupportedValid)) {
+ throw new Error(
+ `[forge:postPackage] invalid iOS Simulator helper build result at ${resultPath}`,
+ );
+ }
+ const typedResult = result as IOSSimulatorHelperBuildResult;
+ if (typedResult.status === 'built') {
+ const requiredArchitectures =
+ typedResult.targetArchitecture === 'universal'
+ ? ['x86_64', 'arm64']
+ : [typedResult.targetArchitecture];
+ if (
+ requiredArchitectures.some(
+ (target) =>
+ !simulatorKitSupportsArchitecture(typedResult.simulatorKitArchitectures, target),
+ )
+ ) {
+ throw new Error(`[forge:postPackage] invalid iOS Simulator helper build result at ${resultPath}`);
+ }
+ }
+ return typedResult;
+}
+
+/**
+ * Moves a successfully built Helper into the nested-code location. A missing
+ * Helper is accepted only when the build script emitted the exact x86_64
+ * unsupported result; all other missing or malformed artifacts fail closed.
+ */
+export function stageMacIOSSimulatorHelper(
+ buildPath: string,
+ platform: string,
+ arch: string,
+): void {
+ if (platform !== 'darwin' && platform !== 'mas') return;
+ const expectedArchitecture = expectedHelperArchitecture(arch);
+ const apps = fs.readdirSync(buildPath).filter((name) => name.endsWith('.app'));
+ if (apps.length !== 1) {
+ throw new Error(
+ `[forge:postPackage] expected one macOS app while staging iOS Simulator helper, found ${apps.length}`,
+ );
+ }
+
+ const appContents = path.join(buildPath, apps[0], 'Contents');
+ const resourceRoot = path.join(appContents, 'Resources', 'ios-simulator');
+ const sourceRoot = path.join(resourceRoot, 'helper');
+ const sourceBundle = path.join(sourceRoot, IOS_SIMULATOR_HELPER_BUNDLE);
+ const destinationBundle = path.join(appContents, 'Helpers', IOS_SIMULATOR_HELPER_BUNDLE);
+ const sourceExecutable = path.join(
+ sourceBundle,
+ 'Contents',
+ 'MacOS',
+ IOS_SIMULATOR_HELPER_EXECUTABLE,
+ );
+ const sourceBuildResultPath = path.join(sourceRoot, IOS_SIMULATOR_HELPER_BUILD_RESULT);
+ const packagedBuildResultPath = path.join(resourceRoot, IOS_SIMULATOR_PACKAGED_BUILD_RESULT);
+ if (!fs.existsSync(sourceBuildResultPath)) {
+ throw new Error(
+ `[forge:postPackage] iOS Simulator helper build result missing at ${sourceBuildResultPath}`,
+ );
+ }
+ const buildResult = readBuildResult(sourceBuildResultPath);
+ if (buildResult.targetArchitecture !== expectedArchitecture) {
+ throw new Error(
+ `[forge:postPackage] iOS Simulator helper build result targets ${buildResult.targetArchitecture}, expected ${expectedArchitecture}`,
+ );
+ }
+
+ fs.rmSync(packagedBuildResultPath, { force: true });
+ if (buildResult.status === 'unsupported') {
+ if (arch !== 'x64') {
+ throw new Error(
+ `[forge:postPackage] iOS Simulator helper fallback is allowed only for x64 packages, received ${arch}`,
+ );
+ }
+ if (fs.existsSync(sourceExecutable)) {
+ throw new Error(
+ '[forge:postPackage] unsupported iOS Simulator helper result unexpectedly contains an executable',
+ );
+ }
+ fs.mkdirSync(resourceRoot, { recursive: true });
+ fs.writeFileSync(packagedBuildResultPath, `${JSON.stringify(buildResult, null, 2)}\n`, {
+ mode: 0o644,
+ });
+ fs.rmSync(destinationBundle, { recursive: true, force: true });
+ fs.rmSync(sourceRoot, { recursive: true, force: true });
+ fs.rmSync(path.join(resourceRoot, 'native'), { recursive: true, force: true });
+ console.warn(
+ `[forge:postPackage] skipped ${IOS_SIMULATOR_HELPER_BUNDLE}: x86_64 SimulatorKit slice unavailable; WDA/MJPEG remains packaged`,
+ );
+ return;
+ }
+
+ if (!fs.existsSync(sourceExecutable)) {
+ throw new Error(
+ `[forge:postPackage] staged iOS Simulator helper executable missing at ${sourceExecutable}`,
+ );
+ }
+ fs.mkdirSync(path.dirname(destinationBundle), { recursive: true });
+ fs.rmSync(destinationBundle, { recursive: true, force: true });
+ fs.renameSync(sourceBundle, destinationBundle);
+ fs.rmSync(sourceRoot, { recursive: true, force: true });
+ fs.rmSync(path.join(resourceRoot, 'native'), { recursive: true, force: true });
+ fs.chmodSync(
+ path.join(destinationBundle, 'Contents', 'MacOS', IOS_SIMULATOR_HELPER_EXECUTABLE),
+ 0o755,
+ );
+ console.log(
+ `[forge:postPackage] staged ${IOS_SIMULATOR_HELPER_BUNDLE} in ${apps[0]}/Contents/Helpers`,
+ );
+}
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index 7fba5a055e..c2453890c1 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -19,6 +19,7 @@ import {
brandExecutableName,
resolveCindyRegion,
} from '@cindy/maker-shared/brand-identity';
+import { stageMacIOSSimulatorHelper } from './forge-ios-simulator-helper';
import { stagePackagedThirdPartyNotices } from './forge-third-party-notices';
const _require = createRequire(__filename);
@@ -681,54 +682,6 @@ function applyMacPackagedDisplayName(buildPath: string, platform: string): void
}
}
-const IOS_SIMULATOR_HELPER_BUNDLE = 'Cindy iOS Simulator Helper.app';
-const IOS_SIMULATOR_HELPER_EXECUTABLE = 'ios-simulator-sidecar';
-
-/**
- * Forge first copies the Host-owned helper through extraResource, then this
- * postPackage step moves it into the canonical nested-code location. Raw dev
- * binaries and the temporary helper staging directory must not remain in the
- * final application bundle.
- */
-function stageMacIOSSimulatorHelper(buildPath: string, platform: string): void {
- if (platform !== 'darwin' && platform !== 'mas') return;
- const apps = fs.readdirSync(buildPath).filter((name) => name.endsWith('.app'));
- if (apps.length !== 1) {
- throw new Error(
- `[forge:postPackage] expected one macOS app while staging iOS Simulator helper, found ${apps.length}`,
- );
- }
-
- const appContents = path.join(buildPath, apps[0], 'Contents');
- const resourceRoot = path.join(appContents, 'Resources', 'ios-simulator');
- const sourceBundle = path.join(resourceRoot, 'helper', IOS_SIMULATOR_HELPER_BUNDLE);
- const destinationBundle = path.join(appContents, 'Helpers', IOS_SIMULATOR_HELPER_BUNDLE);
- const sourceExecutable = path.join(
- sourceBundle,
- 'Contents',
- 'MacOS',
- IOS_SIMULATOR_HELPER_EXECUTABLE,
- );
- if (!fs.existsSync(sourceExecutable)) {
- throw new Error(
- `[forge:postPackage] staged iOS Simulator helper executable missing at ${sourceExecutable}`,
- );
- }
-
- fs.mkdirSync(path.dirname(destinationBundle), { recursive: true });
- fs.rmSync(destinationBundle, { recursive: true, force: true });
- fs.renameSync(sourceBundle, destinationBundle);
- fs.rmSync(path.join(resourceRoot, 'helper'), { recursive: true, force: true });
- fs.rmSync(path.join(resourceRoot, 'native'), { recursive: true, force: true });
- fs.chmodSync(
- path.join(destinationBundle, 'Contents', 'MacOS', IOS_SIMULATOR_HELPER_EXECUTABLE),
- 0o755,
- );
- console.log(
- `[forge:postPackage] staged ${IOS_SIMULATOR_HELPER_BUNDLE} in ${apps[0]}/Contents/Helpers`,
- );
-}
-
function targetPlatformKey(targetPlatform: string, targetArch: string): string {
return `${targetPlatform}-${targetArch}`;
}
@@ -1442,7 +1395,7 @@ const config: ForgeConfig = {
const noticeName = stagePackagedThirdPartyNotices(buildPath, opts.platform);
console.log(`[forge:postPackage] staged ${noticeName} + restricted component disclosure`);
signPackagedExes(buildPath);
- stageMacIOSSimulatorHelper(buildPath, opts.platform);
+ stageMacIOSSimulatorHelper(buildPath, opts.platform, opts.arch);
applyMacPackagedDisplayName(buildPath, opts.platform);
}
},
diff --git a/apps/desktop/scripts/ci/ios-simulator-helper-packaging.test.mjs b/apps/desktop/scripts/ci/ios-simulator-helper-packaging.test.mjs
new file mode 100644
index 0000000000..c099a49962
--- /dev/null
+++ b/apps/desktop/scripts/ci/ios-simulator-helper-packaging.test.mjs
@@ -0,0 +1,159 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ inspectPackagedIOSSimulatorHelper,
+ signIOSSimulatorHelper,
+} from './lib.mjs';
+
+const roots = [];
+
+function createApp() {
+ const appPath = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-signed-ios-helper-'));
+ roots.push(appPath);
+ return appPath;
+}
+
+function helperExecutable(appPath) {
+ return path.join(
+ appPath,
+ 'Contents',
+ 'Helpers',
+ 'Cindy iOS Simulator Helper.app',
+ 'Contents',
+ 'MacOS',
+ 'ios-simulator-sidecar',
+ );
+}
+
+function unsupportedBuildResult(appPath, patch = {}) {
+ const resultPath = path.join(
+ appPath,
+ 'Contents',
+ 'Resources',
+ 'ios-simulator',
+ 'native-helper-build-result.json',
+ );
+ fs.mkdirSync(path.dirname(resultPath), { recursive: true });
+ fs.writeFileSync(
+ resultPath,
+ `${JSON.stringify({
+ schemaVersion: 1,
+ status: 'unsupported',
+ targetArchitecture: 'x86_64',
+ reason: 'simulator-kit-architecture-unavailable',
+ simulatorKitArchitectures: ['arm64e'],
+ ...patch,
+ })}\n`,
+ );
+ return resultPath;
+}
+
+afterEach(() => {
+ for (const root of roots.splice(0)) {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+describe('packaged iOS Simulator Helper inspection', () => {
+ it('reports a packaged Helper when the executable is present', () => {
+ const appPath = createApp();
+ const executablePath = helperExecutable(appPath);
+ fs.mkdirSync(path.dirname(executablePath), { recursive: true });
+ fs.writeFileSync(executablePath, 'sidecar');
+
+ expect(inspectPackagedIOSSimulatorHelper(appPath, 'x64')).toMatchObject({
+ status: 'present',
+ executablePath,
+ });
+ });
+
+ it('accepts only the explicit x86_64 unsupported build result', () => {
+ const appPath = createApp();
+ const buildResultPath = unsupportedBuildResult(appPath);
+
+ expect(inspectPackagedIOSSimulatorHelper(appPath, 'x64')).toMatchObject({
+ status: 'unsupported',
+ buildResultPath,
+ result: {
+ targetArchitecture: 'x86_64',
+ reason: 'simulator-kit-architecture-unavailable',
+ },
+ });
+ });
+
+ it('skips signing only for the explicit unsupported result and removes a stale manifest', () => {
+ const appPath = createApp();
+ unsupportedBuildResult(appPath);
+ const manifestPath = path.join(
+ appPath,
+ 'Contents',
+ 'Resources',
+ 'ios-simulator',
+ 'native-sidecar-manifest.json',
+ );
+ fs.writeFileSync(manifestPath, '{}');
+
+ expect(
+ signIOSSimulatorHelper(
+ appPath,
+ ['--sign', '-'],
+ { mode: 'adhoc', teamIdentifier: null },
+ 'x64',
+ ),
+ ).toBe(false);
+ expect(fs.existsSync(manifestPath)).toBe(false);
+ });
+
+ it('fails when a missing Helper has no explicit unsupported result', () => {
+ const appPath = createApp();
+ expect(() => inspectPackagedIOSSimulatorHelper(appPath, 'x64')).toThrow(
+ 'packaged iOS Simulator helper is missing',
+ );
+ });
+
+ it('fails for malformed, arm64, or conflicting unsupported results', () => {
+ const malformedApp = createApp();
+ unsupportedBuildResult(malformedApp, { targetArchitecture: 'arm64' });
+ expect(() => inspectPackagedIOSSimulatorHelper(malformedApp, 'x64')).toThrow(
+ 'build result is invalid',
+ );
+
+ const conflictingApp = createApp();
+ unsupportedBuildResult(conflictingApp);
+ const executablePath = helperExecutable(conflictingApp);
+ fs.mkdirSync(path.dirname(executablePath), { recursive: true });
+ fs.writeFileSync(executablePath, 'sidecar');
+ expect(() => inspectPackagedIOSSimulatorHelper(conflictingApp, 'x64')).toThrow(
+ 'conflicts with unsupported build result',
+ );
+ });
+
+ it('rejects x86_64 fallback markers for arm64 and universal packages', () => {
+ const arm64App = createApp();
+ const universalApp = createApp();
+ unsupportedBuildResult(arm64App);
+ unsupportedBuildResult(universalApp);
+
+ expect(() => inspectPackagedIOSSimulatorHelper(arm64App, 'arm64')).toThrow(
+ 'fallback is allowed only for x64 packages',
+ );
+ expect(() => inspectPackagedIOSSimulatorHelper(universalApp, 'universal')).toThrow(
+ 'fallback is allowed only for x64 packages',
+ );
+ });
+
+ it('rejects a missing-slice marker that still lists x86_64', () => {
+ const appPath = createApp();
+ unsupportedBuildResult(appPath, {
+ simulatorKitArchitectures: ['x86_64', 'arm64e'],
+ });
+
+ expect(() => inspectPackagedIOSSimulatorHelper(appPath, 'x64')).toThrow(
+ 'build result is invalid',
+ );
+ });
+});
diff --git a/apps/desktop/scripts/ci/lib.mjs b/apps/desktop/scripts/ci/lib.mjs
index 6ea593bdef..2c64f95de0 100644
--- a/apps/desktop/scripts/ci/lib.mjs
+++ b/apps/desktop/scripts/ci/lib.mjs
@@ -764,6 +764,82 @@ const IOS_SIMULATOR_SIDECAR_MANIFEST_RELATIVE_PATH = path.join(
'ios-simulator',
'native-sidecar-manifest.json',
);
+const IOS_SIMULATOR_HELPER_BUILD_RESULT_RELATIVE_PATH = path.join(
+ 'Contents',
+ 'Resources',
+ 'ios-simulator',
+ 'native-helper-build-result.json',
+);
+const IOS_SIMULATOR_HELPER_UNSUPPORTED_REASON =
+ 'simulator-kit-architecture-unavailable';
+
+function expectedIOSSimulatorHelperArchitecture(packageArch) {
+ switch (packageArch) {
+ case 'arm64':
+ return 'arm64';
+ case 'x64':
+ return 'x86_64';
+ case 'universal':
+ return 'universal';
+ default:
+ throw new Error(`unsupported packaged iOS Simulator helper architecture: ${packageArch}`);
+ }
+}
+
+export function inspectPackagedIOSSimulatorHelper(appPath, packageArch) {
+ const expectedArchitecture = expectedIOSSimulatorHelperArchitecture(packageArch);
+ const helperPath = path.join(appPath, IOS_SIMULATOR_HELPER_RELATIVE_PATH);
+ const executablePath = path.join(
+ helperPath,
+ 'Contents',
+ 'MacOS',
+ IOS_SIMULATOR_HELPER_EXECUTABLE,
+ );
+ const buildResultPath = path.join(
+ appPath,
+ IOS_SIMULATOR_HELPER_BUILD_RESULT_RELATIVE_PATH,
+ );
+ const hasExecutable = fs.existsSync(executablePath);
+ const hasBuildResult = fs.existsSync(buildResultPath);
+ if (hasExecutable) {
+ if (hasBuildResult) {
+ throw new Error('packaged iOS Simulator helper conflicts with unsupported build result');
+ }
+ return { status: 'present', helperPath, executablePath };
+ }
+ if (!hasBuildResult) {
+ throw new Error(`packaged iOS Simulator helper is missing: ${executablePath}`);
+ }
+
+ let result;
+ try {
+ result = JSON.parse(fs.readFileSync(buildResultPath, 'utf8'));
+ } catch (error) {
+ throw new Error(
+ `packaged iOS Simulator helper build result is invalid: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
+ if (
+ result?.schemaVersion !== 1 ||
+ result?.status !== 'unsupported' ||
+ result?.targetArchitecture !== 'x86_64' ||
+ result?.reason !== IOS_SIMULATOR_HELPER_UNSUPPORTED_REASON ||
+ !Array.isArray(result?.simulatorKitArchitectures) ||
+ result.simulatorKitArchitectures.length === 0 ||
+ result.simulatorKitArchitectures.includes('x86_64') ||
+ !result.simulatorKitArchitectures.every((architecture) => typeof architecture === 'string')
+ ) {
+ throw new Error('packaged iOS Simulator helper build result is invalid');
+ }
+ if (expectedArchitecture !== 'x86_64') {
+ throw new Error(
+ `packaged iOS Simulator helper fallback is allowed only for x64 packages, received ${packageArch}`,
+ );
+ }
+ return { status: 'unsupported', buildResultPath, result };
+}
function runSigningCommand(command, args, label) {
const result = spawnSync(command, args, { encoding: 'utf8' });
@@ -848,33 +924,34 @@ export function writeIOSSimulatorSidecarManifest(appPath, signing) {
return manifestPath;
}
-function signIOSSimulatorHelper(appPath, signArgs, signing) {
- const helperPath = path.join(appPath, IOS_SIMULATOR_HELPER_RELATIVE_PATH);
- const executablePath = path.join(
- helperPath,
- 'Contents',
- 'MacOS',
- IOS_SIMULATOR_HELPER_EXECUTABLE,
- );
- if (!fs.existsSync(executablePath)) {
- throw new Error(`packaged iOS Simulator helper is missing: ${executablePath}`);
+export function signIOSSimulatorHelper(appPath, signArgs, signing, packageArch) {
+ const helper = inspectPackagedIOSSimulatorHelper(appPath, packageArch);
+ if (helper.status === 'unsupported') {
+ fs.rmSync(path.join(appPath, IOS_SIMULATOR_SIDECAR_MANIFEST_RELATIVE_PATH), {
+ force: true,
+ });
+ console.warn(
+ ' Skipping iOS Simulator helper signing: x86_64 SimulatorKit slice unavailable; package will use WDA/MJPEG',
+ );
+ return false;
}
console.log(' Signing iOS Simulator helper executable...');
runSigningCommand(
'/usr/bin/codesign',
- [...signArgs, executablePath],
+ [...signArgs, helper.executablePath],
'iOS Simulator helper signing',
);
console.log(' Signing iOS Simulator helper bundle...');
runSigningCommand(
'/usr/bin/codesign',
- [...signArgs, helperPath],
+ [...signArgs, helper.helperPath],
'iOS Simulator helper bundle signing',
);
writeIOSSimulatorSidecarManifest(appPath, signing);
+ return true;
}
-export function adhocSignMacApp(appPath, helperEntitlementsPath, mainEntitlementsPath) {
+export function adhocSignMacApp(appPath, helperEntitlementsPath, mainEntitlementsPath, arch) {
console.log('==> Ad-hoc signing macOS app for local packaged testing...');
const signBase = '/usr/bin/codesign --force --options runtime --sign -';
const frameworksDir = path.join(appPath, 'Contents', 'Frameworks');
@@ -893,13 +970,16 @@ export function adhocSignMacApp(appPath, helperEntitlementsPath, mainEntitlement
exec(`find "${frameworksDir}" -type f | while IFS= read -r f; do if file "$f" | grep -qE "Mach-O"; then ${signBase} "$f"; fi; done`);
exec(`find "${frameworksDir}" -name "*.app" -exec ${signBase} --entitlements "${helperEntitlementsPath}" "{}" \\;`);
exec(`find "${frameworksDir}" -maxdepth 1 -name "*.framework" -exec ${signBase} "{}" \\;`);
- signIOSSimulatorHelper(appPath, ['--force', '--options', 'runtime', '--sign', '-'], {
- mode: 'adhoc',
- teamIdentifier: null,
- });
+ const iosSimulatorHelperSigned = signIOSSimulatorHelper(
+ appPath,
+ ['--force', '--options', 'runtime', '--sign', '-'],
+ { mode: 'adhoc', teamIdentifier: null },
+ arch,
+ );
exec(`${signBase} --entitlements "${mainEntitlementsPath}" "${appPath}"`);
exec(`/usr/bin/codesign --verify --deep --strict "${appPath}"`);
verifyMacContactsPermissions(appPath);
+ return iosSimulatorHelperSigned;
}
// ── macOS 正式签名 / 公证 / DMG(单点实现;publish-macos 与 package-desktop 共用)──
@@ -915,7 +995,7 @@ export function signMacAppWithIdentity(
helperEntitlementsPath,
mainEntitlementsPath,
identity,
- { keychainAccessGroup } = {},
+ { keychainAccessGroup, arch } = {},
) {
console.log(' Removing provenance attributes...');
exec(`/usr/bin/xattr -dr com.apple.provenance "${appPath}" 2>/dev/null || true`);
@@ -955,10 +1035,11 @@ export function signMacAppWithIdentity(
// 4. Host-owned iOS Simulator Helper uses Hardened Runtime but receives no
// Electron/V8 or main-app entitlements. Its manifest is written only after
// the final nested signature, then sealed by the outer app signature.
- signIOSSimulatorHelper(
+ const iosSimulatorHelperSigned = signIOSSimulatorHelper(
appPath,
['--force', '--timestamp', '--options', 'runtime', '--sign', identity.signIdentity],
{ mode: 'developer-id', teamIdentifier: identity.teamId },
+ arch,
);
// 5. 主 app bundle
@@ -971,6 +1052,7 @@ export function signMacAppWithIdentity(
keychainAccessGroup,
signingTeamId: identity.teamId,
});
+ return iosSimulatorHelperSigned;
}
const NOTARYTOOL_TIMEOUT_MS = 1800000;
diff --git a/apps/desktop/scripts/package-desktop.mjs b/apps/desktop/scripts/package-desktop.mjs
index ccab88131f..ee1a35e8b9 100644
--- a/apps/desktop/scripts/package-desktop.mjs
+++ b/apps/desktop/scripts/package-desktop.mjs
@@ -395,13 +395,27 @@ async function finishDarwin({
});
}
console.log('==> Signing (Developer ID)...');
- signMacAppWithIdentity(appPath, helperEntitlementsPath, mainEntitlementsPath, identity, {
- keychainAccessGroup,
- });
+ const iosSimulatorHelperSigned = signMacAppWithIdentity(
+ appPath,
+ helperEntitlementsPath,
+ mainEntitlementsPath,
+ identity,
+ { keychainAccessGroup, arch },
+ );
+ if (requireNativeReleaseGate && !iosSimulatorHelperSigned) {
+ throw new Error(
+ 'CINDY_IOS_SIMULATOR_RELEASE_NATIVE_SMOKE=1 requires a packaged Native Helper',
+ );
+ }
console.log('==> Notarizing...');
notarizeMacApp(appPath, identity);
signingMode = 'developer-id+notarized';
- runIOSSimulatorReleaseGate(appPath, arch, 'verified', requireNativeReleaseGate);
+ runIOSSimulatorReleaseGate(
+ appPath,
+ arch,
+ iosSimulatorHelperSigned ? 'verified' : 'untrusted',
+ requireNativeReleaseGate,
+ );
const dmgPath = path.join(artifactDir, `${baseName}-${arch}.dmg`);
console.log('==> Creating DMG...');
@@ -420,7 +434,7 @@ async function finishDarwin({
// 版本无关(或显式放行)→ ad-hoc 签名,产出 .app 的 zip 供本机/内部试用。
writeMacEntitlements(helperEntitlementsPath);
writeMacEntitlements(mainEntitlementsPath, { appleEvents: true });
- adhocSignMacApp(appPath, helperEntitlementsPath, mainEntitlementsPath);
+ adhocSignMacApp(appPath, helperEntitlementsPath, mainEntitlementsPath, arch);
if (requireNativeReleaseGate) {
throw new Error(
'CINDY_IOS_SIMULATOR_RELEASE_NATIVE_SMOKE=1 requires a Developer ID signed and notarized package',
diff --git a/apps/desktop/src/main/__tests__/forgeIOSSimulatorHelper.test.ts b/apps/desktop/src/main/__tests__/forgeIOSSimulatorHelper.test.ts
new file mode 100644
index 0000000000..57e1407711
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/forgeIOSSimulatorHelper.test.ts
@@ -0,0 +1,183 @@
+import { mkdtemp, mkdir, readFile, stat, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { stageMacIOSSimulatorHelper } from '../../../forge-ios-simulator-helper';
+
+const roots: string[] = [];
+
+async function createFixture(result: Record<string, unknown>, includeExecutable: boolean) {
+ const buildPath = await mkdtemp(path.join(os.tmpdir(), 'cindy-forge-ios-helper-'));
+ roots.push(buildPath);
+ const appContents = path.join(buildPath, 'Cindy.app', 'Contents');
+ const resourceRoot = path.join(appContents, 'Resources', 'ios-simulator');
+ const helperRoot = path.join(resourceRoot, 'helper');
+ const executablePath = path.join(
+ helperRoot,
+ 'Cindy iOS Simulator Helper.app',
+ 'Contents',
+ 'MacOS',
+ 'ios-simulator-sidecar',
+ );
+ await mkdir(helperRoot, { recursive: true });
+ await writeFile(path.join(helperRoot, 'build-result.json'), `${JSON.stringify(result)}\n`);
+ await writeFile(path.join(resourceRoot, 'wda-source.tar.gz'), 'wda');
+ await mkdir(path.join(resourceRoot, 'native'), { recursive: true });
+ await writeFile(path.join(resourceRoot, 'native', 'stale'), 'stale');
+ if (includeExecutable) {
+ await mkdir(path.dirname(executablePath), { recursive: true });
+ await writeFile(executablePath, 'sidecar', { mode: 0o644 });
+ }
+ return { buildPath, appContents, resourceRoot };
+}
+
+afterEach(async () => {
+ const { rm } = await import('node:fs/promises');
+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
+});
+
+describe('stageMacIOSSimulatorHelper', () => {
+ it('stages a built Helper and removes temporary native resources', async () => {
+ const fixture = await createFixture(
+ {
+ schemaVersion: 1,
+ status: 'built',
+ targetArchitecture: 'x86_64',
+ simulatorKitArchitectures: ['x86_64', 'arm64e'],
+ },
+ true,
+ );
+
+ stageMacIOSSimulatorHelper(fixture.buildPath, 'darwin', 'x64');
+
+ const executable = path.join(
+ fixture.appContents,
+ 'Helpers',
+ 'Cindy iOS Simulator Helper.app',
+ 'Contents',
+ 'MacOS',
+ 'ios-simulator-sidecar',
+ );
+ await expect(stat(executable)).resolves.toMatchObject({ mode: expect.any(Number) });
+ expect((await stat(executable)).mode & 0o777).toBe(0o755);
+ await expect(stat(path.join(fixture.resourceRoot, 'helper'))).rejects.toThrow();
+ await expect(stat(path.join(fixture.resourceRoot, 'native'))).rejects.toThrow();
+ await expect(
+ stat(path.join(fixture.resourceRoot, 'native-helper-build-result.json')),
+ ).rejects.toThrow();
+ });
+
+ it('preserves an explicit x86_64 unsupported result and removes stale Helper content', async () => {
+ const result = {
+ schemaVersion: 1,
+ status: 'unsupported',
+ targetArchitecture: 'x86_64',
+ reason: 'simulator-kit-architecture-unavailable',
+ simulatorKitArchitectures: ['arm64e'],
+ };
+ const fixture = await createFixture(result, false);
+ const staleDestination = path.join(
+ fixture.appContents,
+ 'Helpers',
+ 'Cindy iOS Simulator Helper.app',
+ );
+ await mkdir(staleDestination, { recursive: true });
+
+ stageMacIOSSimulatorHelper(fixture.buildPath, 'darwin', 'x64');
+
+ await expect(stat(staleDestination)).rejects.toThrow();
+ await expect(stat(path.join(fixture.resourceRoot, 'helper'))).rejects.toThrow();
+ await expect(stat(path.join(fixture.resourceRoot, 'native'))).rejects.toThrow();
+ await expect(
+ readFile(path.join(fixture.resourceRoot, 'native-helper-build-result.json'), 'utf8'),
+ ).resolves.toContain('simulator-kit-architecture-unavailable');
+ await expect(readFile(path.join(fixture.resourceRoot, 'wda-source.tar.gz'), 'utf8')).resolves.toBe(
+ 'wda',
+ );
+ });
+
+ it('rejects a missing executable without the exact unsupported result', async () => {
+ const fixture = await createFixture(
+ {
+ schemaVersion: 1,
+ status: 'built',
+ targetArchitecture: 'x86_64',
+ simulatorKitArchitectures: ['x86_64'],
+ },
+ false,
+ );
+ expect(() => stageMacIOSSimulatorHelper(fixture.buildPath, 'darwin', 'x64')).toThrow(
+ 'helper executable missing',
+ );
+ });
+
+ it('rejects unsupported markers for arm64 or unknown reasons', async () => {
+ const fixture = await createFixture(
+ {
+ schemaVersion: 1,
+ status: 'unsupported',
+ targetArchitecture: 'arm64',
+ reason: 'simulator-kit-architecture-unavailable',
+ simulatorKitArchitectures: ['x86_64'],
+ },
+ false,
+ );
+ expect(() => stageMacIOSSimulatorHelper(fixture.buildPath, 'darwin', 'x64')).toThrow(
+ 'invalid iOS Simulator helper build result',
+ );
+ });
+
+ it('rejects an x86_64 fallback marker for arm64 and universal packages', async () => {
+ const result = {
+ schemaVersion: 1,
+ status: 'unsupported',
+ targetArchitecture: 'x86_64',
+ reason: 'simulator-kit-architecture-unavailable',
+ simulatorKitArchitectures: ['arm64e'],
+ };
+ const arm64Fixture = await createFixture(result, false);
+ const universalFixture = await createFixture(result, false);
+
+ expect(() =>
+ stageMacIOSSimulatorHelper(arm64Fixture.buildPath, 'darwin', 'arm64'),
+ ).toThrow('targets x86_64, expected arm64');
+ expect(() =>
+ stageMacIOSSimulatorHelper(universalFixture.buildPath, 'darwin', 'universal'),
+ ).toThrow('targets x86_64, expected universal');
+ });
+
+ it('rejects a built result from a different package architecture', async () => {
+ const fixture = await createFixture(
+ {
+ schemaVersion: 1,
+ status: 'built',
+ targetArchitecture: 'x86_64',
+ simulatorKitArchitectures: ['x86_64', 'arm64e'],
+ },
+ true,
+ );
+
+ expect(() => stageMacIOSSimulatorHelper(fixture.buildPath, 'darwin', 'arm64')).toThrow(
+ 'targets x86_64, expected arm64',
+ );
+ });
+
+ it('rejects a missing-slice marker that still lists x86_64', async () => {
+ const fixture = await createFixture(
+ {
+ schemaVersion: 1,
+ status: 'unsupported',
+ targetArchitecture: 'x86_64',
+ reason: 'simulator-kit-architecture-unavailable',
+ simulatorKitArchitectures: ['x86_64', 'arm64e'],
+ },
+ false,
+ );
+
+ expect(() => stageMacIOSSimulatorHelper(fixture.buildPath, 'darwin', 'x64')).toThrow(
+ 'invalid iOS Simulator helper build result',
+ );
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-artifact.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-artifact.test.ts
index 05fa2db0d6..732aaa5c75 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-artifact.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-artifact.test.ts
@@ -158,14 +158,18 @@ describe('packaged iOS Simulator sidecar artifact verification', () => {
const testDirectory = path.dirname(fileURLToPath(import.meta.url));
const sourcePath = path.resolve(testDirectory, '../../../../forge.config.ts');
const source = await readFile(sourcePath, 'utf8');
+ const helperSourcePath = path.resolve(
+ testDirectory,
+ '../../../../forge-ios-simulator-helper.ts',
+ );
+ const helperSource = await readFile(helperSourcePath, 'utf8');
const resourcesStart = source.indexOf('function extraResourcesForTarget');
const resourcesEnd = source.indexOf('function assertRealAndroidPlatformTool');
const ensureWdaStart = source.indexOf('function ensureMacIOSSimulatorWdaArchive');
const ensureWdaEnd = source.indexOf('const MACOS_VOICE_HELPER_DEPLOYMENT_TARGET');
const buildStart = source.indexOf('function buildMacIOSSimulatorHelper');
const buildEnd = source.indexOf('function runSwiftcForTarget');
- const stageStart = source.indexOf('function stageMacIOSSimulatorHelper');
- const stageEnd = source.indexOf('function targetPlatformKey');
+ const stageStart = helperSource.indexOf('export function stageMacIOSSimulatorHelper');
const prePackageStart = source.indexOf('prePackage: async');
const postPackageStart = source.indexOf('postPackage: async');
const postPackageEnd = source.indexOf(' makers,', postPackageStart);
@@ -178,7 +182,6 @@ describe('packaged iOS Simulator sidecar artifact verification', () => {
buildStart,
buildEnd,
stageStart,
- stageEnd,
prePackageStart,
postPackageStart,
postPackageEnd,
@@ -189,7 +192,7 @@ describe('packaged iOS Simulator sidecar artifact verification', () => {
const resourcesBody = source.slice(resourcesStart, resourcesEnd);
const ensureWdaBody = source.slice(ensureWdaStart, ensureWdaEnd);
const buildBody = source.slice(buildStart, buildEnd);
- const stageBody = source.slice(stageStart, stageEnd);
+ const stageBody = helperSource.slice(stageStart);
const prePackageBody = source.slice(prePackageStart, postPackageStart);
const postPackageBody = source.slice(postPackageStart, postPackageEnd);
@@ -206,14 +209,20 @@ describe('packaged iOS Simulator sidecar artifact verification', () => {
expect(buildBody).toContain('CINDY_IOS_SIDECAR_ARCH: helperArch');
expect(buildBody).toContain('`${CINDY_APP_ID}.ios-simulator-helper`');
expect(buildBody).toContain('process.env.APP_VERSION ?? DESKTOP_PACKAGE_VERSION');
+ expect(helperSource).toContain(
+ "const IOS_SIMULATOR_PACKAGED_BUILD_RESULT = 'native-helper-build-result.json'",
+ );
expect(stageBody).toContain("path.join(appContents, 'Helpers', IOS_SIMULATOR_HELPER_BUNDLE)");
- expect(stageBody).toContain("fs.rmSync(path.join(resourceRoot, 'helper')");
+ expect(stageBody).toContain("buildResult.status === 'unsupported'");
+ expect(stageBody).toContain('fs.rmSync(sourceRoot');
expect(stageBody).toContain("fs.rmSync(path.join(resourceRoot, 'native')");
const ensureWdaIndex = prePackageBody.indexOf('ensureMacIOSSimulatorWdaArchive(platform);');
const buildHelperIndex = prePackageBody.indexOf('buildMacIOSSimulatorHelper(platform, arch);');
expect(ensureWdaIndex).toBeGreaterThan(-1);
expect(buildHelperIndex).toBeGreaterThan(ensureWdaIndex);
- expect(postPackageBody).toContain('stageMacIOSSimulatorHelper(buildPath, opts.platform);');
+ expect(postPackageBody).toContain(
+ 'stageMacIOSSimulatorHelper(buildPath, opts.platform, opts.arch);',
+ );
});
it('promotes only the fixed signed Helper layout to a verified descriptor', async () => {
@@ -341,9 +350,7 @@ describe('packaged iOS Simulator sidecar artifact verification', () => {
source.indexOf('async function finishLinux'),
);
const notarizeIndex = finishDarwinBody.indexOf('notarizeMacApp(appPath, identity)');
- const verifiedGateIndex = finishDarwinBody.indexOf(
- "runIOSSimulatorReleaseGate(appPath, arch, 'verified'",
- );
+ const releaseGateIndex = finishDarwinBody.indexOf('runIOSSimulatorReleaseGate(', notarizeIndex);
const dmgIndex = finishDarwinBody.indexOf('createMacDMG(');
const adhocIndex = finishDarwinBody.indexOf('adhocSignMacApp(');
const untrustedGateIndex = finishDarwinBody.indexOf(
@@ -352,8 +359,12 @@ describe('packaged iOS Simulator sidecar artifact verification', () => {
const appZipIndex = finishDarwinBody.indexOf('Creating app ZIP (ad-hoc signed)');
expect(notarizeIndex).toBeGreaterThan(-1);
- expect(verifiedGateIndex).toBeGreaterThan(notarizeIndex);
- expect(dmgIndex).toBeGreaterThan(verifiedGateIndex);
+ expect(releaseGateIndex).toBeGreaterThan(notarizeIndex);
+ expect(finishDarwinBody).toContain("iosSimulatorHelperSigned ? 'verified' : 'untrusted'");
+ expect(finishDarwinBody).toContain(
+ 'CINDY_IOS_SIMULATOR_RELEASE_NATIVE_SMOKE=1 requires a packaged Native Helper',
+ );
+ expect(dmgIndex).toBeGreaterThan(releaseGateIndex);
expect(adhocIndex).toBeGreaterThan(-1);
expect(untrustedGateIndex).toBeGreaterThan(adhocIndex);
expect(appZipIndex).toBeGreaterThan(untrustedGateIndex);
diff --git a/packages/ios-simulator-runtime/scripts/build-native-sidecar.mjs b/packages/ios-simulator-runtime/scripts/build-native-sidecar.mjs
index 3caeff058c..4550fb30df 100644
--- a/packages/ios-simulator-runtime/scripts/build-native-sidecar.mjs
+++ b/packages/ios-simulator-runtime/scripts/build-native-sidecar.mjs
@@ -12,6 +12,12 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
+import {
+ IOS_SIMULATOR_HELPER_BUILD_RESULT_FILENAME,
+ decideNativeSidecarBuild,
+ parseMachOArchitectures,
+} from "./native-sidecar-build-policy.mjs";
+
const execFileAsync = promisify(execFile);
const packageRoot = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
@@ -42,6 +48,10 @@ const helperStagingRoot = path.join(
);
const helperBundleName = "Cindy iOS Simulator Helper.app";
const executableName = "ios-simulator-sidecar";
+const helperBuildResult = path.join(
+ helperStagingRoot,
+ IOS_SIMULATOR_HELPER_BUILD_RESULT_FILENAME,
+);
if (process.platform !== "darwin") {
console.log("[ios-simulator-sidecar] skipped: macOS-only native helper");
@@ -78,6 +88,33 @@ const simulatorKitFrameworks = path.join(
"Library",
"PrivateFrameworks",
);
+const simulatorKitBinary = path.join(
+ simulatorKitFrameworks,
+ "SimulatorKit.framework",
+ "SimulatorKit",
+);
+
+async function inspectSimulatorKitArchitectures() {
+ const { stdout } = await execFileAsync(
+ "xcrun",
+ ["lipo", "-archs", simulatorKitBinary],
+ { maxBuffer: 1024 * 1024 },
+ );
+ const architectures = parseMachOArchitectures(stdout);
+ if (architectures.length === 0) {
+ throw new Error("SimulatorKit architecture inspection returned no slices");
+ }
+ return architectures;
+}
+
+async function writeHelperBuildResult(result) {
+ await mkdir(helperStagingRoot, { recursive: true });
+ await writeFile(
+ helperBuildResult,
+ `${JSON.stringify(result, null, 2)}\n`,
+ "utf8",
+ );
+}
async function compileArchitecture(targetArchitecture, output) {
const outputDir = path.dirname(output);
@@ -210,20 +247,46 @@ async function buildRawBinary() {
"[ios-simulator-sidecar] build failed: raw output requires one architecture",
);
}
+ const simulatorKitArchitectures = await inspectSimulatorKitArchitectures();
+ decideNativeSidecarBuild({
+ outputMode,
+ targetArchitecture: architecture,
+ simulatorKitArchitectures,
+ });
const output = path.join(nativeOutputRoot, architecture, executableName);
await compileArchitecture(architecture, output);
console.log(`[ios-simulator-sidecar] built ${output}`);
}
async function buildHelperBundle() {
- const tempRoot = await mkdtemp(
- path.join(os.tmpdir(), "cindy-ios-simulator-helper-"),
- );
const helperBundle = path.join(helperStagingRoot, helperBundleName);
const contents = path.join(helperBundle, "Contents");
const executable = path.join(contents, "MacOS", executableName);
await rm(helperStagingRoot, { recursive: true, force: true });
+ const simulatorKitArchitectures = await inspectSimulatorKitArchitectures();
+ const decision = decideNativeSidecarBuild({
+ outputMode,
+ targetArchitecture: architecture,
+ simulatorKitArchitectures,
+ });
+ if (decision.action === "unsupported") {
+ await writeHelperBuildResult({
+ schemaVersion: 1,
+ status: "unsupported",
+ targetArchitecture: architecture,
+ reason: decision.reason,
+ simulatorKitArchitectures,
+ });
+ console.warn(
+ `[ios-simulator-sidecar] skipped helper ${architecture}: SimulatorKit provides ${simulatorKitArchitectures.join("+") || "no compatible slices"}; packaged app will use WDA/MJPEG`,
+ );
+ return;
+ }
+
+ const tempRoot = await mkdtemp(
+ path.join(os.tmpdir(), "cindy-ios-simulator-helper-"),
+ );
await mkdir(path.dirname(executable), { recursive: true });
try {
const thinOutputs = [];
@@ -250,6 +313,12 @@ async function buildHelperBundle() {
helperInfoPlist(),
"utf8",
);
+ await writeHelperBuildResult({
+ schemaVersion: 1,
+ status: "built",
+ targetArchitecture: architecture,
+ simulatorKitArchitectures,
+ });
console.log(
`[ios-simulator-sidecar] built helper ${helperBundle} (${targetArchitectures.join("+")})`,
);
diff --git a/packages/ios-simulator-runtime/scripts/native-sidecar-build-policy.mjs b/packages/ios-simulator-runtime/scripts/native-sidecar-build-policy.mjs
new file mode 100644
index 0000000000..f1d69a13e4
--- /dev/null
+++ b/packages/ios-simulator-runtime/scripts/native-sidecar-build-policy.mjs
@@ -0,0 +1,57 @@
+export const IOS_SIMULATOR_HELPER_BUILD_RESULT_FILENAME = "build-result.json";
+export const IOS_SIMULATOR_HELPER_UNSUPPORTED_REASON =
+ "simulator-kit-architecture-unavailable";
+
+export function parseMachOArchitectures(value) {
+ return [
+ ...new Set(
+ String(value ?? "")
+ .trim()
+ .split(/\s+/)
+ .filter(Boolean),
+ ),
+ ];
+}
+
+function simulatorKitSupportsArchitecture(architectures, targetArchitecture) {
+ if (targetArchitecture === "arm64") {
+ return architectures.includes("arm64") || architectures.includes("arm64e");
+ }
+ return architectures.includes(targetArchitecture);
+}
+
+export function decideNativeSidecarBuild({
+ outputMode,
+ targetArchitecture,
+ simulatorKitArchitectures,
+}) {
+ const targetArchitectures =
+ targetArchitecture === "universal"
+ ? ["x86_64", "arm64"]
+ : [targetArchitecture];
+ const missingArchitectures = targetArchitectures.filter(
+ (candidate) =>
+ !simulatorKitSupportsArchitecture(simulatorKitArchitectures, candidate),
+ );
+
+ if (missingArchitectures.length === 0) {
+ return { action: "build", targetArchitectures };
+ }
+
+ if (
+ outputMode === "helper" &&
+ targetArchitecture === "x86_64" &&
+ missingArchitectures.length === 1 &&
+ missingArchitectures[0] === "x86_64"
+ ) {
+ return {
+ action: "unsupported",
+ targetArchitectures,
+ reason: IOS_SIMULATOR_HELPER_UNSUPPORTED_REASON,
+ };
+ }
+
+ throw new Error(
+ `SimulatorKit is missing required architecture(s): ${missingArchitectures.join(", ")}`,
+ );
+}
diff --git a/packages/ios-simulator-runtime/scripts/native-sidecar-build-policy.test.mjs b/packages/ios-simulator-runtime/scripts/native-sidecar-build-policy.test.mjs
new file mode 100644
index 0000000000..585fe61583
--- /dev/null
+++ b/packages/ios-simulator-runtime/scripts/native-sidecar-build-policy.test.mjs
@@ -0,0 +1,74 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ IOS_SIMULATOR_HELPER_UNSUPPORTED_REASON,
+ decideNativeSidecarBuild,
+ parseMachOArchitectures,
+} from "./native-sidecar-build-policy.mjs";
+
+describe("native sidecar build policy", () => {
+ it("parses unique architectures from lipo output", () => {
+ expect(parseMachOArchitectures("x86_64 arm64e x86_64\n")).toEqual([
+ "x86_64",
+ "arm64e",
+ ]);
+ });
+
+ it("builds x86_64 when SimulatorKit provides the slice", () => {
+ expect(
+ decideNativeSidecarBuild({
+ outputMode: "helper",
+ targetArchitecture: "x86_64",
+ simulatorKitArchitectures: ["x86_64", "arm64e"],
+ }),
+ ).toEqual({ action: "build", targetArchitectures: ["x86_64"] });
+ });
+
+ it("treats arm64e SimulatorKit as link-compatible with an arm64 helper", () => {
+ expect(
+ decideNativeSidecarBuild({
+ outputMode: "helper",
+ targetArchitecture: "arm64",
+ simulatorKitArchitectures: ["arm64e"],
+ }),
+ ).toEqual({ action: "build", targetArchitectures: ["arm64"] });
+ });
+
+ it("allows only a thin x86_64 helper to fall back when the slice is unavailable", () => {
+ expect(
+ decideNativeSidecarBuild({
+ outputMode: "helper",
+ targetArchitecture: "x86_64",
+ simulatorKitArchitectures: ["arm64e"],
+ }),
+ ).toEqual({
+ action: "unsupported",
+ targetArchitectures: ["x86_64"],
+ reason: IOS_SIMULATOR_HELPER_UNSUPPORTED_REASON,
+ });
+ });
+
+ it("keeps raw, arm64, and universal builds fail-closed when a slice is missing", () => {
+ expect(() =>
+ decideNativeSidecarBuild({
+ outputMode: "raw",
+ targetArchitecture: "x86_64",
+ simulatorKitArchitectures: ["arm64e"],
+ }),
+ ).toThrow("missing required architecture(s): x86_64");
+ expect(() =>
+ decideNativeSidecarBuild({
+ outputMode: "helper",
+ targetArchitecture: "arm64",
+ simulatorKitArchitectures: ["x86_64"],
+ }),
+ ).toThrow("missing required architecture(s): arm64");
+ expect(() =>
+ decideNativeSidecarBuild({
+ outputMode: "helper",
+ targetArchitecture: "universal",
+ simulatorKitArchitectures: ["arm64e"],
+ }),
+ ).toThrow("missing required architecture(s): x86_64");
+ });
+});