import { execFileSync } from 'node:child_process'; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { Readable } from 'node:stream'; import { afterEach, beforeEach, expect, test, vi } from 'vitest'; import type { BuildStartParams } from '@stim-cli/core/protocol'; import { processContext } from '../cli-operation.ts'; import { createOwnedIosSim, ownedSimName } from '../devices/ios.ts'; import { teardownOwnedIosSim } from '../devices/teardown.ts'; import type { DoctorContext } from '../diagnostics/doctor.ts'; import { withIosOperationScope } from '../integrations/ios-operation-scope.ts'; import type { IosArtifactContext } from '../integrations/ios-project.ts'; import { runPluginIosBuild } from '../integrations/plugin-ios.ts'; import { projectRegistry } from '../integrations/projects.ts'; import { BuildHost } from '../job/offload/host.ts'; import { runOffloadWorker } from '../job/offload/worker.ts'; import { manifestDigest } from '../offload/manifest.ts'; import { resolveOptimizations } from '../optimizations.ts'; import { sourceManifest } from '../offload/native-source.ts'; const fixture = vi.hoisted(() => ({ dir: '' })); vi.mock('../shipped-plugins.ts', () => ({ shippedPluginDir: (name: string) => (name === 'fixture' ? fixture.dir : null), shippedPluginNames: () => ['fixture'], })); vi.mock('../devices/ios.ts', async (actual) => ({ ...(await actual()), createOwnedIosSim: vi.fn(async (label) => ({ udid: 'PROBE-SIM', name: `stim-${label}`, deviceType: null, runtime: null, })), bootIosSim: vi.fn(async () => {}), listAllIosSimsAsync: vi.fn(async () => []), })); vi.mock('../integrations/plugin-ios.ts', async (actual) => { const module = await actual(); return { ...module, runPluginIosBuild: vi.fn(module.runPluginIosBuild) }; }); vi.mock('../engine/device-capacity.ts', async (actual) => ({ ...(await actual()), withDeviceBootAdmission: vi.fn<(device: unknown, boot: () => Promise) => Promise>( async (_device, boot) => boot(), ), })); vi.mock('../devices/teardown.ts', async (actual) => ({ ...(await actual()), teardownOwnedIosSim: vi.fn(async () => ({ status: 'torn-down', })), })); const MARKER = 'fixture.project'; const PINS = { tool: '1.0' }; const BUILD = '#!/bin/sh\nenv > env-seen.txt\necho "error: fixture failed"\nexit 3\n'; let root: string; let loads: string; let execEnv: string; let tools: string; let commit: string; const saved = { ...process.env }; const stdin = Object.getOwnPropertyDescriptor(process, 'stdin'); function git(dir: string, ...args: string[]): string { return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', env: { ...process.env, GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@t', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@t', }, }).trim(); } function write(path: string, text: string, mode = 0o644): void { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); chmodSync(path, mode); } const MODULE = `import { appendFileSync, existsSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; appendFileSync(LOADS, 'loaded\\n'); export function createProjectPlugin(host) { return { ios: { simulator: (root) => existsSync(join(root, 'modules.json')) ? { reason: 'it reads its modules on a simulator', buildOnly: { message: 'needs a simulator', remedy: 'Run stim ios.' } } : null, build: ({ root, scheme, configuration, simulator, arch, env }) => ({ argv: [join(root, 'build.sh')], env: { ...env, FIXTURE_SIM: simulator ?? 'none', FIXTURE_SCHEME: scheme ?? 'none', FIXTURE_CONFIGURATION: configuration ?? 'none', FIXTURE_ARCH: arch }, }), result: ({ lines }) => ({ app: null, diagnostics: lines.filter((line) => line.startsWith('error: ')) }), doctor: () => [{ code: 'fixture-tools', level: 'cost', title: 'No fixture tool', detail: 'missing', fix: null }], offload: { plan: (root, env) => ({ pins: { tool: '1.0' }, payload: { greeting: env.FIXTURE_GREETING ?? 'unset' }, checkout: { name: 'shop-app', sibling: null }, }), check: (pins, payload) => pins.tool !== '1.0' ? 'The fixture needs tool 1.0.' : payload && typeof payload.greeting !== 'string' ? 'The fixture needs a greeting.' : null, tools: async (pins, env) => { const { stdout } = await host.exec('/usr/bin/env', [], { timeoutMs: 10000 }); writeFileSync(EXEC_ENV, stdout + 'MODULE_TICKET=' + (process.env.STIM_ACCESS_TICKET ?? '') + '\\n'); return env.FIXTURE_TOOL_MISSING ? [{ reason: 'no fixture tool ' + pins.tool, commands: ['install-fixture-tool ' + pins.tool] }] : []; }, source: () => ({ dir: TOOLS, commit: TOOLS_COMMIT }), env: ({ env, payload, source, sibling }) => ({ ...env, FIXTURE_GREETING: payload.greeting, FIXTURE_SOURCE: source ?? 'none', FIXTURE_SIBLING: sibling ?? 'none', }), }, }, }; } `; beforeEach(() => { root = realpathSync(mkdtempSync(join(tmpdir(), 'stim-plugin-offload-'))); loads = join(root, 'loads.txt'); execEnv = join(root, 'exec-env.txt'); tools = join(root, 'machine', 'tools'); write(join(tools, 'bin', 'tool'), ''); git(tools, 'init', '-q'); git(tools, 'add', '.'); git(tools, 'commit', '-q', '-m', 'tools'); commit = git(tools, 'rev-parse', 'HEAD'); fixture.dir = join(root, 'plugin'); write( join(fixture.dir, 'package.json'), JSON.stringify({ name: '@stim-cli/plugin-fixture', version: '1.2.3', stimPlugin: { kinds: { project: 2 }, project: { id: 'fixture', name: 'Fixture', markers: [MARKER], module: 'plugin.mjs', targets: { ios: {} } }, }, }), ); write( join(fixture.dir, 'plugin.mjs'), MODULE.replace('LOADS', JSON.stringify(loads)) .replace('EXEC_ENV', JSON.stringify(execEnv)) .replace('TOOLS_COMMIT', JSON.stringify(commit)) .replace('TOOLS', JSON.stringify(tools)), ); Object.assign(process.env, { STIM_HOME: join(root, 'stim-home'), STIM_ACCESS_TICKET: 'secret-ticket' }); }); afterEach(() => { for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key]; Object.assign(process.env, saved); if (stdin) Object.defineProperty(process, 'stdin', stdin); vi.restoreAllMocks(); rmSync(root, { recursive: true, force: true }); }); const PLUGIN: NonNullable = { id: 'fixture', version: '1.2.3', pins: PINS, payload: { greeting: 'client-value' }, checkout: { name: 'shop-app', sibling: null }, }; /** Runs the worker's build mode on `files`, as stim-server hands it a synced manifest. */ async function build( files: Record, plugin: object = PLUGIN, { configuration = null, scheme = null }: { configuration?: string | null; scheme?: string | null } = {}, ): Promise<{ result: Record; area: string }> { const client = join(root, 'client'); const blobs = join(root, 'blobs'); rmSync(client, { recursive: true, force: true }); for (const [path, text] of Object.entries(files)) write(join(client, path), text, path.endsWith('.sh') ? 0o755 : 0o644); git(client, 'init', '-q'); git(client, 'add', '.'); const manifest = await sourceManifest(client); for (const { path, sha256 } of manifest) write(join(blobs, sha256.slice(0, 2), sha256), readFileSync(join(client, path), 'utf8')); const area = join(root, 'area'); mkdirSync(area, { recursive: true }); const job = { job: '0badc0de-job', area, blobs, manifest, platform: 'ios', macos: null, swiftpmCache: join(root, 'swiftpm'), project: '', isExpo: false, configuration, scheme, runtime: null, android: null, expectedFingerprint: manifestDigest(manifest), plugin, optimizations: null, compat: 6, }; Object.defineProperty(process, 'stdin', { value: Readable.from([Buffer.from(JSON.stringify(job))]), configurable: true, }); const lines: string[] = []; vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => { lines.push(String(chunk)); return true; }); await runOffloadWorker('build'); return { result: lines.map((line) => JSON.parse(line)).find((each) => each.type === 'result'), area }; } const seen = (path: string) => Object.fromEntries( readFileSync(path, 'utf8') .split('\n') .filter((line) => line.includes('=')) .map((line) => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)]), ); test('a build machine with no plugins setting builds a shipped plugin from its own Stim build, with the selected build, the payload, its second checkout and no access ticket', async () => { const { result, area } = await build( { [MARKER]: '', 'build.sh': BUILD }, { ...PLUGIN, checkout: { name: 'shop-app', sibling: '../tools' }, arch: 'arm64' }, { configuration: 'Staging', scheme: 'Staging' }, ); expect(existsSync(join(root, 'stim-home', 'config.json'))).toBe(false); expect(result).toMatchObject({ ok: false, code: 'fixture-build-failed', message: 'error: fixture failed' }); const placed = join(realpathSync(area), 'checkout', 'tools'); expect(git(placed, 'rev-parse', 'HEAD')).toBe(commit); const env = seen(join(area, 'checkout', 'shop-app', 'env-seen.txt')); expect(env).toMatchObject({ FIXTURE_GREETING: 'client-value', FIXTURE_SOURCE: tools, FIXTURE_SIBLING: placed, FIXTURE_SIM: 'none', FIXTURE_SCHEME: 'Staging', FIXTURE_CONFIGURATION: 'Staging', FIXTURE_ARCH: 'arm64', }); expect(env).not.toHaveProperty('STIM_ACCESS_TICKET'); expect(seen(execEnv)).not.toHaveProperty('STIM_ACCESS_TICKET'); expect(seen(execEnv)).toMatchObject({ MODULE_TICKET: '' }); }); test.each(['fixture', 'f'.repeat(40)])( 'a shipped plugin app that needs a simulator builds next to a probe under the stim-build- prefix, deleted after: %s', async (id) => { const manifest = JSON.parse(readFileSync(join(fixture.dir, 'package.json'), 'utf8')); manifest.stimPlugin.project.id = id; write(join(fixture.dir, 'package.json'), JSON.stringify(manifest)); vi.mocked(teardownOwnedIosSim).mockClear(); const { result, area } = await build({ [MARKER]: '', 'build.sh': BUILD, 'modules.json': '[]' }, { ...PLUGIN, id }); expect(result).toMatchObject({ ok: false, code: `${id}-build-failed` }); const label = vi.mocked(createOwnedIosSim).mock.calls.at(-1)?.[0] ?? ''; expect(label).toBe(`build-${id}-0badc0de`); expect(ownedSimName(label, { model: 'iPhone 17 Pro', runtime: '26.0' })).toMatch(/^stim-(?:build|exact)-/); expect(seen(join(area, 'checkout', 'shop-app', 'env-seen.txt'))).toMatchObject({ FIXTURE_SIM: 'PROBE-SIM' }); expect(vi.mocked(teardownOwnedIosSim).mock.calls).toEqual([['PROBE-SIM', { del: true }]]); }, ); test("a shipped plugin's build program runs in the worker's own process group, which the host's cleanup covers", async () => { const { result, area } = await build({ [MARKER]: '', 'build.sh': "#!/bin/sh\nps -o pgid= -p $$ | tr -d ' ' > pgid.txt\nexit 3\n", }); expect(result).toMatchObject({ ok: false, code: 'fixture-build-failed' }); const own = execFileSync('ps', ['-o', 'pgid=', '-p', String(process.pid)], { encoding: 'utf8' }).trim(); expect(readFileSync(join(area, 'checkout', 'shop-app', 'pgid.txt'), 'utf8').trim()).toBe(own); }); test('a shipped plugin build whose compiler cleanup is unverified does not report a settled failure', async () => { vi.mocked(runPluginIosBuild).mockRejectedValueOnce( Object.assign(new Error('compiler cleanup unverified'), { reportCleanup: true }), ); const { result } = await build({ [MARKER]: '', 'build.sh': BUILD }); expect(result).toMatchObject({ ok: false, fingerprintSettled: false }); expect(result).not.toMatchObject({ code: 'fixture-build-failed' }); }); test('a shipped plugin whose offload declares only plan and check builds with the defaults of the other members', async () => { write( join(fixture.dir, 'plugin.mjs'), `import { join } from 'node:path'; export const createProjectPlugin = () => ({ ios: { build: ({ root, env }) => ({ argv: [join(root, 'build.sh')], env }), result: ({ lines }) => ({ app: null, diagnostics: lines.filter((line) => line.startsWith('error: ')) }), offload: { plan: () => ({ unsupported: 'unused on the machine' }), check: () => null }, }, }); `, ); process.env.MACHINE_VALUE = 'from-the-machine'; const { result, area } = await build({ [MARKER]: '', 'build.sh': BUILD }); expect(result).toMatchObject({ ok: false, code: 'fixture-build-failed', message: 'error: fixture failed' }); expect(seen(join(area, 'checkout', 'shop-app', 'env-seen.txt'))).toMatchObject({ MACHINE_VALUE: 'from-the-machine' }); expect( ( await build( { [MARKER]: '', 'build.sh': BUILD }, { ...PLUGIN, checkout: { name: 'shop-app', sibling: '../tools' } }, ) ).result, ).toMatchObject({ ok: false, code: 'fixture-tools', message: expect.stringContaining('gives none of this machine') }); }); test.each([ ['a plugin this Stim build does not ship', { [MARKER]: '' }, { ...PLUGIN, id: 'other' }, 'unsupported-provider'], ['another version of the shipped plugin', { [MARKER]: '' }, { ...PLUGIN, version: '9.9.9' }, 'unsupported-provider'], ['a project without the plugin markers', { 'build.sh': BUILD }, PLUGIN, 'provider-mismatch'], [ 'a React Native project folder', { [MARKER]: '', 'package.json': JSON.stringify({ dependencies: { 'react-native': '0.80.0' } }) }, PLUGIN, 'provider-mismatch', ], ])('a build machine refuses %s without loading any plugin code', async (_, files, plugin, code) => { const { result } = await build(files, plugin); expect(result).toMatchObject({ ok: false, code }); expect(existsSync(loads)).toBe(false); }); const WORKER = `if (process.argv[2] !== 'build') console.log(JSON.stringify({ stimBuild: 'b1', arch: 'arm64', xcode: 'Xcode 27', simulatorSdk: '27', runtimes: ['iOS-27-0'] })); `; test("a build machine's offer reports what it lacks of a shipped plugin's toolchain, and its start refuses what the plugin refuses", async () => { const worker = join(root, 'worker.mjs'); writeFileSync(worker, WORKER); const host = new BuildHost({ worker, env: { ...process.env, FIXTURE_TOOL_MISSING: '1' }, limits: { minFreeBytes: 0 }, }); const offer = (plugin: object) => host.offer('client', { repo: 'repo', plugin }); const session = host.session('client', { OPEN: 1, readyState: 1, bufferedAmount: 0, send: () => {} }, () => {}); const launch = vi.spyOn(host, 'launch').mockResolvedValue({ error: { code: 'build-refused', message: 'launched' } }); try { const { payload: _payload, checkout: _checkout, ...pins } = PLUGIN; expect(await offer(pins)).toMatchObject({ result: { plugin: { missing: [{ reason: 'no fixture tool 1.0', commands: ['install-fixture-tool 1.0'] }] } }, }); expect(seen(execEnv)).not.toHaveProperty('STIM_ACCESS_TICKET'); expect(seen(execEnv)).toMatchObject({ MODULE_TICKET: '' }); expect(await offer({ ...pins, pins: { tool: '2.0' } })).toEqual({ error: { code: 'bad-request', message: 'The fixture needs tool 1.0.' }, }); expect(await offer({ ...pins, version: '9.9.9' })).toMatchObject({ error: { code: 'bad-request' } }); session.sync({ repo: 'repo', files: [], done: true }); const start = (plugin: object) => session.start({ repo: 'repo', project: '', platform: 'ios', runtime: 'iOS-27-0', stimBuild: 'b1', compat: 6, fingerprint: 'a'.repeat(64), plugin, }); expect(await start({ ...PLUGIN, payload: { greeting: 1 } })).toEqual({ error: { code: 'bad-request', message: 'The fixture needs a greeting.' }, }); expect(await start({ ...PLUGIN, arch: 'armv7' })).toMatchObject({ error: { code: 'bad-request' } }); expect(launch).not.toHaveBeenCalled(); expect(await start({ ...PLUGIN, arch: 'x86_64' })).toMatchObject({ error: { message: 'launched' } }); expect(launch.mock.calls[0]?.[0].job.plugin).toEqual({ ...PLUGIN, arch: 'x86_64' }); } finally { launch.mockRestore(); session.close(); await host.close(); } }); function doctorContext(at: string): DoctorContext { return { root: at, options: { platform: 'ios', remoteEnv: { FIXTURE_GREETING: 'from-doctor' } }, settings: {}, optimizations: null, platforms: ['ios'], repoRoot: null, }; } function artifactContext(at: string): IosArtifactContext { return { root: at, operation: { ...processContext(at), env: { FIXTURE_GREETING: 'from-client' } }, logFile: join(at, 'build.log'), configuration: 'Staging', buildScheme: 'Staging', target: { udid: null, destination: null, sdk: 'iphonesimulator', arch: 'arm64', keyArch: null, offloadRuntime: () => 'iOS-27-0', offloadRefusal: null, }, device: null, optimizations: resolveOptimizations({}, {}).ios, cache: { read: false, write: false, remote: false }, phase: () => {}, note: () => {}, logWriter: () => ({ file: join(at, 'build.ndjson'), write: () => true, close: () => ({ file: join(at, 'build.ndjson'), written: 0, dropped: 0, lastError: null }), written: 0, dropped: 0, lastError: null, }), estimates: () => ({ coldBuildMs: null, podsMs: null }), step: () => {}, setPodsMs: () => {}, }; } /** What a client plans for the fixture app with `entry` in its `plugins` setting: doctor's targets and a run's offload. */ async function clientOffload(entry: string) { write(join(root, 'stim-home', 'config.json'), JSON.stringify({ plugins: [entry] })); const app = join(root, 'app'); write(join(app, MARKER), ''); const [doctor] = await projectRegistry.selectDoctor(app, 'ios').load(); if (!doctor) throw new Error('no doctor for the fixture project'); const context = doctorContext(app); await doctor.inspect(context); const targets = doctor.offloadTargets?.(context, async () => null) ?? null; const selected = projectRegistry.selectIos(app); if (!('load' in selected)) throw new Error(selected.problem.message); return withIosOperationScope(processContext(app), async (scope) => { const offload = (await selected.load({}, scope)).artifact(artifactContext(app)).offload; if (!offload) throw new Error('the plugin recipe has no offload'); const planned = await offload.context(); return { targets: targets && (await targets()).map((target) => target.platform === 'ios' && target.plugin), planned, request: () => offload.request('iOS-27-0'), }; }); } test("a client sends a shipped plugin's build to a build machine with the selected build and the pins, payload and checkout it plans", async () => { const { targets, planned, request } = await clientOffload('fixture'); expect(targets).toEqual([{ id: 'fixture', version: '1.2.3', pins: PINS }]); expect(planned).toEqual({ runtime: 'iOS-27-0', unsupported: null }); expect(request()).toMatchObject({ configuration: 'Staging', scheme: 'Staging', plugin: { id: 'fixture', version: '1.2.3', pins: PINS, payload: { greeting: 'from-client' }, checkout: { name: 'shop-app', sibling: null }, arch: 'arm64', }, }); }); test.each([ ['shipped with Stim keeps its code', () => 'fixture', { code: 'fixture-tools' }], ['loaded from a directory has its code dropped', () => fixture.dir, {}], ])('a doctor finding of the plugin %s', async (_, entry, code) => { write(join(root, 'stim-home', 'config.json'), JSON.stringify({ plugins: [entry()] })); const app = join(root, 'app'); write(join(app, MARKER), ''); const [doctor] = await projectRegistry.selectDoctor(app, 'ios').load(); expect(await doctor?.inspect(doctorContext(app))).toStrictEqual([ { ...code, level: 'cost', title: 'No fixture tool', detail: 'missing', fix: null }, ]); }); test('a client keeps the build of a plugin loaded from a directory on this machine', async () => { const { targets, planned } = await clientOffload(fixture.dir); expect(targets).toBeNull(); expect(planned).toEqual({ runtime: 'iOS-27-0', unsupported: 'a build machine builds only the plugins shipped with Stim', }); });