import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { hostSimulatorArch } from '@stim-cli/core'; import { vi } from 'vitest'; import { createLocalStim } from '../api/client.ts'; import { processContext } from '../cli-operation.ts'; import { buildIosOperation } from '../commands/ios/build.ts'; import { readIosBuildPlan } from '../commands/ios/next-build.ts'; import * as planPlacement from '../device-host/plan-placement.ts'; import * as iosDevices from '../devices/ios.ts'; import * as offloadClient from '../offload/client.ts'; import { DEFAULT_DEPS } from '../commands/ios/dependencies.ts'; import { NATIVE_RUN_LOCK } from '../engine/native-run.ts'; import { workspaceProcessLockPath } from '../engine/workspace-process-lock.ts'; import { projectRegistry } from '../integrations/projects.ts'; import type { ProjectPluginModule } from '../plugin.ts'; import { readClaimSet } from '../ownership-claim.ts'; import { workspaceDir } from '../workspace/paths.ts'; let dir: string; beforeEach(() => { dir = realpathSync(mkdtempSync(join(tmpdir(), 'stim-plugin-ios-'))); process.env.STIM_HOME = join(dir, 'home'); mkdirSync(process.env.STIM_HOME); }); afterEach(() => { rmSync(dir, { recursive: true, force: true }); delete process.env.STIM_HOME; }); function mockDarwinCompilerHost(): void { const host = vi.spyOn(DEFAULT_DEPS, 'hostPlatform').mockReturnValue('darwin'); onTestFinished(() => host.mockRestore()); } function alive(pid: number): boolean { try { process.kill(pid, 0); return true; } catch { return false; } } const kit = vi.hoisted((): { timeoutMs: number | undefined } => ({ timeoutMs: undefined })); vi.mock('../kit-host.ts', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, startKitWorker: (options: Parameters[0]) => actual.startKitWorker({ ...options, timeoutMs: kit.timeoutMs ?? options.timeoutMs, project: options.project && { ...options.project, memberTimeoutMs: kit.timeoutMs ?? options.project.memberTimeoutMs, }, }), }; }); const ios = `{ cacheIneligible: 'fixture', configurationProblem: () => null, bundleId: () => 'dev.stim.fixture', simulator: () => null, incremental: () => undefined, build: () => ({ argv: [process.execPath], env: {} }), result: () => ({ app: null, diagnostics: [] }), doctor: () => [], }`; function fixture(source: string): string { const plugin = join(dir, 'plugin'); mkdirSync(plugin); writeFileSync( join(plugin, 'package.json'), JSON.stringify({ name: 'fixture', stimPlugin: { kinds: { project: 2 }, project: { id: 'fixture', name: 'Fixture', markers: ['fixture.marker'], module: 'plugin.mjs', targets: { ios: {} }, }, }, }), ); writeFileSync(join(plugin, 'plugin.mjs'), source); writeFileSync(join(process.env.STIM_HOME ?? '', 'config.json'), JSON.stringify({ plugins: [plugin] })); const root = join(dir, 'project'); mkdirSync(root); writeFileSync(join(root, 'fixture.marker'), ''); return root; } function plan(root: string, controller = new AbortController(), options: { scheme?: string } = {}) { return readIosBuildPlan( processContext(root, controller.signal), { remoteBuild: 'local', ...options }, { ...DEFAULT_DEPS, hostPlatform: () => 'darwin', }, ); } function hostChild(pidFile: string): string { return ` import { existsSync } from 'node:fs'; async function start(host) { void host.exec('/bin/sh', ['-c', ${JSON.stringify(`echo $$ > "${pidFile}"; exec sleep 300`)}], { timeoutMs: 600000 }).catch(() => {}); while (!existsSync(${JSON.stringify(pidFile)})) await new Promise((resolve) => setTimeout(resolve, 20)); }`; } function childFixture(outcome: 'refused' | 'success' | 'cancelled') { const pidFile = join(dir, 'child.pid'); const root = fixture(`${hostChild(pidFile)} export async function createProjectPlugin(host) { if ('${outcome}' === 'refused') { await start(host); throw new Error('gave up'); } return { ios: { ...${ios}, bundleId: async () => { await start(host); if ('${outcome}' === 'cancelled') await new Promise(() => {}); return 'dev.stim.fixture'; }, } }; } `); return { root, pidFile }; } function expectChildGone(pidFile: string) { const pid = Number(readFileSync(pidFile, 'utf8').trim()); expect(alive(pid)).toBe(false); } test.skipIf(process.platform === 'win32')('the plan drains parent-owned exec on success', async () => { const { root, pidFile } = childFixture('success'); expect(await plan(root)).toMatchObject({ platform: 'ios', bundleId: 'dev.stim.fixture' }); expectChildGone(pidFile); }); test.skipIf(process.platform === 'win32')('the plan drains parent-owned exec on a refused load', async () => { const { root, pidFile } = childFixture('refused'); await expect(plan(root)).rejects.toMatchObject({ code: 'STIM_NO_PROJECT', message: expect.stringContaining('createProjectPlugin() failed: gave up'), }); expectChildGone(pidFile); }); test.skipIf(process.platform === 'win32')('the plan drains parent-owned exec on cancellation', async () => { const { root, pidFile } = childFixture('cancelled'); const controller = new AbortController(); const planning = plan(root, controller); async function cancelAtSpawn() { try { await vi.waitFor(() => expect(existsSync(pidFile)).toBe(true)); } finally { controller.abort(); } } await Promise.all([ expect(planning).rejects.toMatchObject({ code: 'STIM_NO_PROJECT', message: expect.stringContaining('operation was aborted'), }), cancelAtSpawn(), ]); expectChildGone(pidFile); }); const nonHostArch = hostSimulatorArch() === 'arm64' ? 'x86_64' : 'arm64'; const architecturePlugin: ProjectPluginModule['createProjectPlugin'] = (host) => ({ ios: { cacheIneligible: 'fixture', configurationProblem: () => null, bundleId: () => 'dev.stim.fixture', simulator: () => null, incremental: () => undefined, async build({ arch }) { const { code, stdout } = await host.exec(process.execPath, ['-p', 'process.execPath'], { timeoutMs: 5000 }); if (code !== 0) throw new Error('could not resolve the fixture build tool'); return { argv: [stdout.trim(), '-e', "require('node:fs').writeFileSync('Fixture.app/arch', process.argv[1])", arch], env: {}, }; }, result: () => ({ app: host.root + '/Fixture.app', diagnostics: [] }), doctor: () => [], }, }); test.each([ { requested: undefined, reported: hostSimulatorArch(), compiled: hostSimulatorArch() }, { requested: nonHostArch, reported: nonHostArch, compiled: nonHostArch }, { requested: 'all', reported: null, compiled: 'all' }, ] as const)( 'build-only reports $reported and the plugin tool builds $compiled', async ({ requested, reported, compiled }) => { mockDarwinCompilerHost(); const root = fixture(`export const createProjectPlugin = ${architecturePlugin.toString()};`); const app = join(root, 'Fixture.app'); mkdirSync(app); writeFileSync( join(app, 'Info.plist'), 'CFBundleIdentifierdev.stim.fixture', ); const output = vi.fn['output']>(); const context = { ...processContext(root), output }; const built = await buildIosOperation(context, root, { arch: requested, remoteBuild: 'local' }); expect(output).toHaveBeenCalledWith('stderr', expect.stringContaining('compiling Debug with plugin.mjs')); expect(built).toMatchObject({ arch: reported, bundleId: 'dev.stim.fixture' }); expect(readFileSync(join(built.appPath, 'arch'), 'utf8')).toBe(compiled); }, ); test('a module with only build and result plans, builds with the scheme given, and reports no doctor findings', async () => { mockDarwinCompilerHost(); const root = fixture(`export const createProjectPlugin = (host) => ({ ios: { build: ({ scheme }) => ({ argv: [process.execPath, '-e', "require('node:fs').writeFileSync('Fixture.app/scheme', process.argv[1])", String(scheme)], env: {}, }), result: () => ({ app: host.root + '/Fixture.app', diagnostics: [] }), } });`); const app = join(root, 'Fixture.app'); mkdirSync(app); writeFileSync( join(app, 'Info.plist'), 'CFBundleIdentifierdev.stim.fixture', ); const planned = await plan(root); expect(planned).toMatchObject({ platform: 'ios', outcome: expect.anything() }); expect(planned).not.toHaveProperty('bundleId'); const context = { ...processContext(root), output: vi.fn['output']>() }; const built = await buildIosOperation(context, root, { scheme: 'App', remoteBuild: 'local' }); expect(built).toMatchObject({ bundleId: 'dev.stim.fixture' }); expect(readFileSync(join(built.appPath, 'scheme'), 'utf8')).toBe('App'); const [doctor] = await projectRegistry.selectDoctor(root, 'ios').load(); expect( await doctor?.inspect({ root, options: { platform: 'ios', operation: processContext(root) }, settings: {}, optimizations: null, platforms: ['ios'], repoRoot: null, }), ).toEqual([]); }); test('a module that names its build tool: the build progress names that tool, not the module', async () => { mockDarwinCompilerHost(); const root = fixture(`export const createProjectPlugin = (host) => ({ ios: { buildTool: 'fixture-cli', build: () => ({ argv: [process.execPath, '-e', ''], env: {} }), result: () => ({ app: host.root + '/Fixture.app', diagnostics: [] }), } });`); const app = join(root, 'Fixture.app'); mkdirSync(app); writeFileSync( join(app, 'Info.plist'), 'CFBundleIdentifierdev.stim.fixture', ); const output = vi.fn['output']>(); await buildIosOperation({ ...processContext(root), output }, root, { remoteBuild: 'local' }); expect(output).toHaveBeenCalledWith('stderr', expect.stringContaining('compiling Debug with fixture-cli')); expect(output).not.toHaveBeenCalledWith('stderr', expect.stringContaining('plugin.mjs')); }); test('a doctor member past the member limit reports the plugin failed its check, not a refusal', async () => { const root = fixture( `export const createProjectPlugin = () => ({ ios: { ...${ios}, doctor: () => new Promise(() => {}) } });`, ); kit.timeoutMs = 750; try { const [doctor] = await projectRegistry.selectDoctor(root, 'ios').load(); expect( await doctor?.inspect({ root, options: { platform: 'ios', operation: processContext(root) }, settings: {}, optimizations: null, platforms: ['ios'], repoRoot: null, }), ).toEqual([ { level: 'cost', title: 'A project plugin failed its doctor check', detail: expect.stringContaining('doctor() did not finish within 750ms'), fix: null, }, ]); } finally { kit.timeoutMs = undefined; } }); test.each([ { flag: undefined, selected: 'Shared' }, { flag: 'App', selected: 'App' }, ])('with ios.scheme set, the plan checks the selected scheme $selected', async ({ flag, selected }) => { const root = fixture(`export const createProjectPlugin = () => ({ ios: { configurationProblem: (scheme) => scheme === ${JSON.stringify(selected)} ? null : { message: 'checked ' + scheme, remedy: 'Pick a scheme.' }, build: () => ({ argv: [process.execPath], env: {} }), result: () => ({ app: null, diagnostics: [] }), } });`); writeFileSync(join(root, '.stim.json'), JSON.stringify({ ios: { scheme: 'Shared' } })); const planned = await plan(root, undefined, flag === undefined ? {} : { scheme: flag }); expect(planned).toMatchObject({ platform: 'ios' }); expect(planned).not.toHaveProperty('refusal'); }); test.each([ ['nonzero exit', '[process.execPath, "-e", "process.exit(23)"]', 'compiler exit: 23'], ['signal', `[process.execPath, "-e", "process.kill(process.pid, 'SIGINT')"]`, 'compiler exit:'], ['spawn failure', '[root + "/missing-compiler"]', 'compiler did not start'], ])('build-only rejects an existing app after compiler %s and reads diagnostics', async (_case, argv, message) => { mockDarwinCompilerHost(); const root = fixture(`export const createProjectPlugin = () => ({ ios: { ...${ios}, build: ({ root }) => ({ argv: ${argv}, env: process.env }), result: ({ exitCode, error }) => ({ app: 'Fixture.app', diagnostics: [error ? 'compiler did not start' : 'compiler exit: ' + exitCode], }), } });`); const app = join(root, 'Fixture.app'); mkdirSync(app); writeFileSync( join(app, 'Info.plist'), 'CFBundleIdentifierdev.stim.fixture', ); const output = vi.fn['output']>(); const context = { ...processContext(root), output }; await expect(buildIosOperation(context, root, { remoteBuild: 'local' })).rejects.toMatchObject({ code: 'STIM_BUILD_FAILED', }); expect(output).toHaveBeenCalledWith('stderr', expect.stringContaining(message)); }); test('a non-Mac module plan refuses compilation even with a hosted simulator and approved builder', async () => { const root = fixture(`export const createProjectPlugin = () => ({ ios: ${ios} });`); vi.spyOn(planPlacement, 'planHostedDevice').mockResolvedValue({ kind: 'hosted', choice: { runtime: '27.0', deviceType: 'iPhone 17 Pro', deviceTypeId: 'iphone', runtimeId: 'ios27', architecture: 'arm64', }, placement: 'on mini', }); const candidates = vi.spyOn(offloadClient, 'buildPlacementCandidates').mockReturnValue({ machines: [ { machine: 'mini', transport: 'tailscale', address: 'mini.example', state: 'approved', requestedAt: '2026-11-29T00:00:00Z', }, ], localEnabled: true, }); try { const result = await readIosBuildPlan( processContext(root), { remote: 'mini' }, { ...DEFAULT_DEPS, hostPlatform: () => 'linux', }, ); expect(result).toMatchObject({ platform: 'ios', placement: 'on mini', outcome: null, refusal: { code: 'STIM_BUILD_FAILED', message: expect.stringContaining('cannot offload compilation') }, }); } finally { candidates.mockRestore(); vi.mocked(planPlacement.planHostedDevice).mockRestore(); } }); test.each(['local', undefined] as const)( 'client.build on a non-Mac host refuses fresh module compilation before probing Xcode (remoteBuild: %s)', async (remoteBuild) => { const root = fixture(`export const createProjectPlugin = () => ({ ios: { ...${ios}, build: () => { throw new Error('Compiler preparation must not run'); }, } });`); const host = vi.spyOn(DEFAULT_DEPS, 'hostPlatform').mockReturnValue('linux'); const candidates = vi.spyOn(offloadClient, 'buildPlacementCandidates').mockReturnValue({ machines: [ { machine: 'mini', transport: 'tailscale', address: 'mini.example', state: 'approved', requestedAt: '2026-11-29T00:00:00Z', }, ], localEnabled: false, }); const runtimeProbe = vi.spyOn(iosDevices, 'listIosRuntimes').mockImplementation(() => { throw new Error('Unexpected xcrun runtime probe'); }); try { const client = createLocalStim({ projectRoot: root, admission: 'none' }); await expect(client.build({ platform: 'ios', ...(remoteBuild && { remoteBuild }) })).rejects.toMatchObject({ code: 'STIM_BUILD_FAILED', message: expect.stringContaining('cannot offload compilation'), }); expect(runtimeProbe).not.toHaveBeenCalled(); } finally { runtimeProbe.mockRestore(); candidates.mockRestore(); host.mockRestore(); } }, ); test.skipIf(process.platform === 'win32')('build-only drains parent-owned exec on a scheme refusal', async () => { const pidFile = join(dir, 'child.pid'); const root = fixture(`${hostChild(pidFile)} export const createProjectPlugin = (host) => ({ ios: { ...${ios}, configurationProblem: async () => { await start(host); return { message: 'no schemes', remedy: 'Drop --scheme.' }; }, } }); `); await expect( buildIosOperation(processContext(root), root, { scheme: 'App', remoteBuild: 'local' }), ).rejects.toMatchObject({ code: 'STIM_BAD_ARG', message: 'no schemes', }); expectChildGone(pidFile); }); test.skipIf(process.platform === 'win32')( 'parallel host exec keeps the native claim pending and drains before the build starts', async () => { const pidFile = join(dir, 'child.pid'); const ready = join(dir, 'short-child-finished'); const release = join(dir, 'release-build'); const buildStarted = join(dir, 'build-started'); const late = join(dir, 'late-exec'); const buildScript = join(dir, 'build.cjs'); const paths = JSON.stringify({ pidFile, ready, release, buildStarted, late, buildScript }); const root = fixture(`${hostChild(pidFile)} import { writeFileSync } from 'node:fs'; const { ready, release, buildStarted, late, buildScript } = ${paths}; export const createProjectPlugin = (host) => ({ ios: { ...${ios}, build: async () => { await start(host); await host.exec(process.execPath, ['-e', ''], { timeoutMs: 5000 }); writeFileSync(ready, ''); while (!existsSync(release)) await new Promise((resolve) => setTimeout(resolve, 10)); const timer = setInterval(() => { if (!existsSync(buildStarted)) return; clearInterval(timer); void host.exec(process.execPath, ['-e', 'require("node:fs").writeFileSync(process.argv[1], "")', late], { timeoutMs: 5000 }).catch(() => writeFileSync(late, 'refused')); }, 10); return { argv: [process.execPath, buildScript], env: {} }; }, } }); `); writeFileSync( buildScript, `const { existsSync, readFileSync, writeFileSync } = require('node:fs'); const { pidFile, buildStarted, late } = ${paths}; try { process.kill(Number(readFileSync(pidFile)), 0); writeFileSync(buildStarted, 'overlap'); } catch (error) { if (error.code !== 'ESRCH') throw error; writeFileSync(buildStarted, 'drained'); } const timer = setInterval(() => { if (existsSync(late)) clearInterval(timer); }, 10); setTimeout(() => clearInterval(timer), 3000).unref();`, ); mockDarwinCompilerHost(); const build = buildIosOperation(processContext(root), root, { remoteBuild: 'local' }); async function checkClaim() { try { await vi.waitFor(() => expect(existsSync(ready)).toBe(true), { timeout: 5000 }); expect(alive(Number(readFileSync(pidFile, 'utf8')))).toBe(true); const lock = workspaceProcessLockPath(workspaceDir(root), NATIVE_RUN_LOCK, true); expect(readClaimSet(lock).live).toEqual([expect.objectContaining({ childDeclared: true, child: null })]); } finally { writeFileSync(release, ''); } } await Promise.all([expect(build).rejects.toMatchObject({ code: 'STIM_BUILD_FAILED' }), checkClaim()]); expect(readFileSync(buildStarted, 'utf8')).toBe('drained'); expect(readFileSync(late, 'utf8')).toBe('refused'); expectChildGone(pidFile); }, 15_000, ); test.skipIf(process.platform === 'win32')( 'selected iOS doctor drains parent-owned exec before giving findings', async () => { const pidFile = join(dir, 'child.pid'); const root = fixture(`${hostChild(pidFile)} export const createProjectPlugin = (host) => ({ ios: { ...${ios}, doctor: async () => { await start(host); return [{ level: 'note', title: 'Fixture', detail: 'ready', fix: null }]; }, } }); `); const [doctor] = await projectRegistry.selectDoctor(root, 'ios').load(); expect(existsSync(pidFile)).toBe(false); expect( await doctor?.inspect({ root, options: { platform: 'ios', operation: processContext(root) }, settings: {}, optimizations: null, platforms: ['ios'], repoRoot: null, }), ).toEqual([{ level: 'note', title: 'Fixture', detail: 'ready', fix: null }]); expectChildGone(pidFile); }, ); test.each([ [ 'module import', `while (true) {} export const createProjectPlugin = () => ({ ios: ${ios} });`, 'module did not load', ], [ 'member call', `export const createProjectPlugin = () => ({ ios: { ...${ios}, bundleId: () => new Promise(() => {}) } });`, 'bundleId() did not finish', ], ])('a hung %s leaves the parent event loop responsive and refuses the plan', async (_, source, message) => { const root = fixture(source); kit.timeoutMs = 750; try { await expect(plan(root)).rejects.toMatchObject({ code: 'STIM_NO_PROJECT', message: expect.stringContaining(message), }); } finally { kit.timeoutMs = undefined; } }); test('plugin stdout reaches stderr without entering the plan output stream', async () => { const marker = 'stim-adapter-plugin-stdout'; const stdout = vi.spyOn(process.stdout, 'write'); const stderr = vi.spyOn(process.stderr, 'write'); try { const root = fixture(` console.log('${marker}'); setInterval(() => {}, 10_000); export const createProjectPlugin = () => ({ ios: ${ios} }); `); expect(await plan(root)).toMatchObject({ bundleId: 'dev.stim.fixture' }); expect(stderr.mock.calls.some(([chunk]) => String(chunk).includes(marker))).toBe(true); expect(stdout.mock.calls.some(([chunk]) => String(chunk).includes(marker))).toBe(false); } finally { stderr.mockRestore(); stdout.mockRestore(); } }); test('build-only hands the module, its member arguments and its compiler no setup ticket', async () => { mockDarwinCompilerHost(); const files = { module: join(dir, 'module'), incremental: join(dir, 'incremental'), build: join(dir, 'build'), child: join(dir, 'child'), }; const record = "require('node:fs').writeFileSync(process.argv[1], JSON.stringify(process.env.STIM_ACCESS_TICKET ?? null))"; const root = fixture(`import { writeFileSync } from 'node:fs'; const seen = (file, env) => writeFileSync(file, JSON.stringify(env.STIM_ACCESS_TICKET ?? null)); seen(${JSON.stringify(files.module)}, process.env); export const createProjectPlugin = (host) => ({ ios: { ...${ios}, incremental: (_root, _configuration, env) => { seen(${JSON.stringify(files.incremental)}, env); return undefined; }, build: ({ env }) => { seen(${JSON.stringify(files.build)}, env); return { argv: [process.execPath, '-e', ${JSON.stringify(record)}, ${JSON.stringify(files.child)}], env }; }, result: () => ({ app: host.root + '/Fixture.app', diagnostics: [] }), } });`); const app = join(root, 'Fixture.app'); mkdirSync(app); writeFileSync( join(app, 'Info.plist'), 'CFBundleIdentifierdev.stim.fixture', ); const base = processContext(root); const context = { ...base, env: { ...base.env, STIM_ACCESS_TICKET: 't'.repeat(42) + 'A' }, output: vi.fn(), }; await buildIosOperation(context, root, { remoteBuild: 'local' }); for (const file of Object.values(files)) expect([file, JSON.parse(readFileSync(file, 'utf8'))]).toEqual([file, null]); });