From 77316c2e1d5bbac4307082b8ae001f06654b2aab Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 09:49:04 +0200 Subject: [PATCH 01/14] test: operator-set iOS signing keys reach the phone daemon's spawn environment (#873) --- src/daemon/main.test.ts | 61 ++++++++++++++++++++++++++++++++++------- 1 file changed, 51 insertions(+), 10 deletions(-) diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 7cc17db9a..f57ed54a4 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -2906,16 +2906,22 @@ describe("startDaemon with the agent-device edge", () => { return { directory, filesystem }; } - function versionAndDaemon(directory: string): ScriptedProcessRunner { + function versionAndDaemon(directory: string, role?: "phones"): ScriptedProcessRunner { + const version = { + match: { args: [realCli, "--version"], command: process.execPath }, + result: { code: 0, stderr: "", stdout: "0.21.28\n" }, + }; + const daemon = (marker: readonly string[]) => ({ + hangs: true, + match: { args: [entry, ...marker], command: process.execPath }, + }); + const simulators = daemon([`--simlock-home=${directory}`]); + if (role === undefined) return new ScriptedProcessRunner([version, simulators]); return new ScriptedProcessRunner([ - { - match: { args: [realCli, "--version"], command: process.execPath }, - result: { code: 0, stderr: "", stdout: "0.21.28\n" }, - }, - { - hangs: true, - match: { args: [entry, `--simlock-home=${directory}`], command: process.execPath }, - }, + version, + simulators, + version, + daemon([`--simlock-home=${directory}`, "--simlock-role=phones"]), ]); } @@ -2923,6 +2929,7 @@ describe("startDaemon with the agent-device edge", () => { setup: Awaited>, ports: { readonly agentDevice?: OptionalModuleDefinition; + readonly clock?: FakeClock; readonly drivers?: StartDaemonOptions["drivers"]; readonly modules?: readonly FakeModule[]; readonly processRunner: ScriptedProcessRunner; @@ -2930,7 +2937,7 @@ describe("startDaemon with the agent-device edge", () => { readonly role?: "gateway"; }, ) { - const clock = new FakeClock(1_000); + const clock = ports.clock ?? new FakeClock(1_000); const sink = new MemoryLogSink(); const daemon = await startDaemon({ clock, @@ -3050,6 +3057,40 @@ describe("startDaemon with the agent-device edge", () => { return runner.calls[1]?.options.env ?? {}; } + it.each([ + ["teamId", "AGENT_DEVICE_IOS_TEAM_ID", "ABCDE12345"], + ["bundleId", "AGENT_DEVICE_IOS_BUNDLE_ID", "com.example.runner"], + ["provisioningProfile", "AGENT_DEVICE_IOS_PROVISIONING_PROFILE", "Simlock Runner Profile"], + ["signingIdentity", "AGENT_DEVICE_IOS_SIGNING_IDENTITY", "Apple Development: Ada (XYZ)"], + ])( + "a capabilities.agent-device.ios.%s the operator sets reaches the phone daemon's spawn environment as %s", + async (key, envName, value) => { + const setup = await setUp({ + capabilities: { "agent-device": { command, enabled: true, ios: { [key]: value } } }, + }); + const runner = versionAndDaemon(setup.directory, "phones"); + const clock = new FakeClock(1_000); + await startEdge(setup, { + clock, + processRunner: runner, + processSupervisor: new FakeProcessSupervisor(), + }); + // why: the simulator daemon's /health never answers, so the phone daemon starts when its ready window runs out. + for (let tick = 0; tick < 400 && runner.calls.length < 4; tick += 1) { + await new Promise((resolve) => setImmediate(resolve)); + clock.advance(100); + } + + expect(runner.calls[3]?.args).toEqual([ + entry, + `--simlock-home=${setup.directory}`, + "--simlock-role=phones", + ]); + expect(runner.calls[3]?.options.env?.[envName]).toBe(value); + expect(runner.calls[1]?.options.env?.[envName]).toBeUndefined(); + }, + ); + it("hands the drivers' lease environment to the agent-device daemon", async () => { const env = await spawnedEnvironment((clock) => [ new FakeDriver({ From afa0d793070ba34b05dd943a2b25c8694acb12cc Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 09:51:35 +0200 Subject: [PATCH 02/14] feat(agent-device): the worker starts a phone daemon with the configured iOS signing keys (#873) --- src/agent-device/definition.ts | 12 +++++ .../host/agent-device-supervisor.test.ts | 1 + .../host/agent-device-supervisor.ts | 53 ++++++++++++++++--- src/agent-device/host/upstream.test.ts | 1 + src/agent-device/worker.ts | 53 ++++++++++++------- 5 files changed, 93 insertions(+), 27 deletions(-) diff --git a/src/agent-device/definition.ts b/src/agent-device/definition.ts index aaa6fc30c..82d6fef13 100644 --- a/src/agent-device/definition.ts +++ b/src/agent-device/definition.ts @@ -4,6 +4,12 @@ import type { OptionalModuleDefinition } from "../modules/index.js"; export interface AgentDeviceModuleConfig { readonly command: string; readonly leaseTtlCapMs?: number; + readonly ios?: { + readonly teamId?: string; + readonly bundleId?: string; + readonly provisioningProfile?: string; + readonly signingIdentity?: string; + }; } /** why: agent-device's shortest lease window, so a cap below it would shorten leases past what agent-device keeps. */ @@ -21,6 +27,12 @@ export const agentDeviceModule: OptionalModuleDefinition; + export interface AgentDeviceSupervisorOptions { readonly baseEnvironment: NodeJS.ProcessEnv; readonly clock: Clock; @@ -62,6 +79,7 @@ export interface AgentDeviceSupervisorOptions { readonly filesystem: Filesystem; readonly healthProbe: AgentDeviceHealthProbe; readonly home: string; + readonly ios?: AgentDeviceIosSigning; readonly leaseMaxTtlMs: number; readonly logger: Logger; readonly nodePath: string; @@ -69,6 +87,7 @@ export interface AgentDeviceSupervisorOptions { readonly platforms: readonly AgentDevicePlatform[]; readonly processRunner: ProcessRunner; readonly processSupervisor: ProcessSupervisor; + readonly role: AgentDeviceRole; readonly tcpProbe: TcpProbe; } @@ -81,6 +100,7 @@ const KILL_GRACE_MS = 2_000; const RETRY_MS = 30_000; const STABLE_AFTER_READY_MS = 60_000; const MARKER = "--simlock-home="; +const PHONES_MARKER = "--simlock-role=phones"; const RESTART = "then restart the daemon (`simlock daemon stop`, then `simlock daemon start`)"; type RemedyKind = UnavailableReason | "node" | "protocol"; @@ -158,11 +178,22 @@ export class AgentDeviceSupervisor { constructor(options: AgentDeviceSupervisorOptions) { this.#o = options; - this.#stateDir = `${options.home}/agent-device`; - this.#recordPath = `${options.home}/agent-device-daemon.json`; + this.#stateDir = `${options.home}/${this.#stem}`; + this.#recordPath = `${options.home}/${this.#stem}-daemon.json`; this.#availability = { state: "starting" }; } + get #stem(): string { + return this.#o.role === "phones" ? "agent-device-phones" : "agent-device"; + } + + /** why: the words after the entry on the daemon's command line; a pid is signalled only when its line ends with them. */ + #markerArgs(realHome: string): readonly string[] { + return this.#o.role === "phones" + ? [`${MARKER}${realHome}`, PHONES_MARKER] + : [`${MARKER}${realHome}`]; + } + availability(): AgentDeviceAvailability { return this.#availability; } @@ -243,7 +274,7 @@ export class AgentDeviceSupervisor { #fail(reason: UnavailableReason, message: string, remedyKind?: RemedyKind): void { if (reason === "start-failed" && !this.#stopped) - this.#o.logger.warn(`agent-device start failed: ${message}`); + this.#o.logger.warn(`agent-device (${this.#o.role}) start failed: ${message}`); this.#availability = { state: "unavailable", reason, @@ -255,8 +286,8 @@ export class AgentDeviceSupervisor { async #startOnce(): Promise { const o = this.#o; const realHome = await o.filesystem.realpath(o.home); - this.#stateDir = `${realHome}/agent-device`; - this.#recordPath = `${realHome}/agent-device-daemon.json`; + this.#stateDir = `${realHome}/${this.#stem}`; + this.#recordPath = `${realHome}/${this.#stem}-daemon.json`; this.#availability = { state: "starting" }; if (!(await this.#reapStep(realHome))) return; const found = await this.#checkInstall(); @@ -333,7 +364,7 @@ export class AgentDeviceSupervisor { const o = this.#o; let handle: ProcessHandle; try { - handle = o.processRunner.spawn(o.nodePath, [entry, `${MARKER}${realHome}`], { + handle = o.processRunner.spawn(o.nodePath, [entry, ...this.#markerArgs(realHome)], { env, stdio: "ignore", }); @@ -501,6 +532,7 @@ export class AgentDeviceSupervisor { async #environment(policyPath: string): Promise { const o = this.#o; const env: NodeJS.ProcessEnv = {}; + const phones = o.role === "phones"; for (const [key, value] of Object.entries(o.baseEnvironment)) { if (!key.startsWith("AGENT_DEVICE_")) env[key] = value; } @@ -513,6 +545,13 @@ export class AgentDeviceSupervisor { stateDir: this.#stateDir, }), ); + if (phones) { + for (const [key, name] of Object.entries(IOS_SIGNING_ENVIRONMENT)) { + const value = o.ios?.[key as keyof AgentDeviceIosSigning]; + if (value !== undefined) env[name] = value; + } + return env; + } if (o.platforms.includes("ios")) { const deviceSet = o.driverEnvironment["SIMLOCK_IOS_DEVICE_SET"]; if (deviceSet !== undefined) env["AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET"] = deviceSet; @@ -673,7 +712,7 @@ export class AgentDeviceSupervisor { ): Promise<"own" | "other" | "unknown"> { const line = await this.#psLine(pid); if (line === undefined) return "unknown"; - if (!line.endsWith(` ${MARKER}${realHome}`)) return "other"; + if (!line.endsWith(` ${this.#markerArgs(realHome).join(" ")}`)) return "other"; if (entry !== undefined && !line.includes(entry)) return "other"; if (await this.#stateDirIsOurs()) { const named = (await this.#readDaemonJson())?.["pid"]; diff --git a/src/agent-device/host/upstream.test.ts b/src/agent-device/host/upstream.test.ts index b5c609b01..f52d9b200 100644 --- a/src/agent-device/host/upstream.test.ts +++ b/src/agent-device/host/upstream.test.ts @@ -80,6 +80,7 @@ async function arrange(version: string) { platforms: ["ios", "android"], processRunner: runner, processSupervisor: processes, + role: "simulators", tcpProbe: probe, }); return { clock, supervisor, upstream: new SupervisorAgentDeviceUpstream(supervisor) }; diff --git a/src/agent-device/worker.ts b/src/agent-device/worker.ts index c07870da6..028e89e11 100644 --- a/src/agent-device/worker.ts +++ b/src/agent-device/worker.ts @@ -6,7 +6,11 @@ import type { AgentDeviceModuleConfig } from "./definition.js"; import { FrontMap } from "./front/front-map.js"; import { InProcessHostLink, type LinkStatus } from "./front/host-link.js"; import { Renewals } from "./front/renewals.js"; -import { AgentDeviceSupervisor, type AgentDevicePlatform } from "./host/agent-device-supervisor.js"; +import { + AgentDeviceSupervisor, + type AgentDevicePlatform, + type AgentDeviceRole, +} from "./host/agent-device-supervisor.js"; import { agentDeviceFindings } from "./host/availability-findings.js"; import { type AgentDeviceHealthProbe, NodeAgentDeviceHealthProbe } from "./host/health.js"; import { AgentDeviceHost } from "./host/host.js"; @@ -86,23 +90,28 @@ export function createWorkerWith( fakes: AgentDeviceFakes, ): (ctx: WorkerContext) => WorkerModule { return (ctx) => { - const supervisor = new AgentDeviceSupervisor({ - baseEnvironment: ctx.environment, - clock: ctx.clock, - config: ctx.config, - driverEnvironment: ctx.leaseEnvironment, - filesystem: ctx.filesystem, - healthProbe: fakes.health ?? new NodeAgentDeviceHealthProbe(), - home: ctx.dataDirectory, - leaseMaxTtlMs: ctx.daemonConfig.lease.maxTtlMs, - logger: ctx.logger, - nodePath: ctx.nodePath, - nodeVersion: ctx.nodeVersion, - platforms: ctx.platforms, - processRunner: ctx.processRunner, - processSupervisor: ctx.processSupervisor, - tcpProbe: ctx.tcpProbe, - }); + const supervise = (role: AgentDeviceRole) => + new AgentDeviceSupervisor({ + baseEnvironment: ctx.environment, + clock: ctx.clock, + config: ctx.config, + driverEnvironment: ctx.leaseEnvironment, + filesystem: ctx.filesystem, + healthProbe: fakes.health ?? new NodeAgentDeviceHealthProbe(), + home: ctx.dataDirectory, + ...(ctx.config.ios === undefined ? {} : { ios: ctx.config.ios }), + leaseMaxTtlMs: ctx.daemonConfig.lease.maxTtlMs, + logger: ctx.logger, + nodePath: ctx.nodePath, + nodeVersion: ctx.nodeVersion, + platforms: ctx.platforms, + processRunner: ctx.processRunner, + processSupervisor: ctx.processSupervisor, + role, + tcpProbe: ctx.tcpProbe, + }); + const supervisor = supervise("simulators"); + const phoneSupervisor = supervise("phones"); const parts = createAgentDeviceEdgeParts( fakes.upstream ?? new SupervisorAgentDeviceUpstream(supervisor), ctx.clock, @@ -118,7 +127,9 @@ export function createWorkerWith( hooks: { // why: not awaited, since simlock's start never waits for agent-device, and a daemon that lost the socket race never gets here, so it reaps nothing. afterSocketClaimed: () => { - if (fakes.upstream === undefined) void supervisor.start(); + if (fakes.upstream === undefined) { + void supervisor.start().then(() => phoneSupervisor.start()); + } }, beforeDeviceReclaim: (ended, signal) => parts.leaseEnd.leaseEnded(ended, signal), beforeDrain: async () => { @@ -126,7 +137,9 @@ export function createWorkerWith( await cancelWaitingAllocates(parts, (id) => ctx.cancelPending(id)); }, // why: before the drivers: the Android driver stops simlock's adb server, which this daemon's agent-device uses, and a client that finds no server forks its own. - beforeDriversDispose: () => supervisor.stop(), + beforeDriversDispose: async () => { + await Promise.all([supervisor.stop(), phoneSupervisor.stop()]); + }, }, mount: (deps) => { const front = createAgentDeviceFront(parts, { From 4c31561fc1e29f4aa420f25cd16121c43af29991 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 09:52:25 +0200 Subject: [PATCH 03/14] test: simlock config set stores an iOS signing key and refuses an empty string or a number (#873) --- src/cli/index.test.ts | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 95501732e..9a0f1d440 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -3078,6 +3078,47 @@ describe("CLI: config set validates with the real config loader (ADR 0003 §11, expect(written).toEqual({ lease: { defaultTtlMs: 2400000 } }); }); + it.each(["teamId", "bundleId", "provisioningProfile", "signingIdentity"])( + "simlock config set capabilities.agent-device.ios.%s stores a non-empty string and refuses an empty string or a number with the usage error", + async (key) => { + const path = `capabilities.agent-device.ios.${key}`; + const set = async (value: string) => { + const output = outputCapture(realCliEnvironmentPorts()); + let written: Record | undefined; + const exitCode = await runCli( + ["config", "set", path, value], + output.environmentWith({ + readConfigFile: async () => ({}), + writeConfigFile: async (contents) => { + written = contents; + }, + }), + ); + return { exitCode, output, written }; + }; + + const stored = await set("ABCDE12345"); + expect(stored.exitCode).toBe(0); + expect(stored.output.stdout).toBe( + `Updated ${path} in /simlock/config.json; takes effect on daemon restart.\n`, + ); + expect(stored.written).toEqual({ + capabilities: { "agent-device": { ios: { [key]: "ABCDE12345" } } }, + }); + for (const value of ["", "42"]) { + const refused = await set(value); + expect(refused.exitCode).toBe(2); + expect(JSON.parse(refused.output.stderr)).toEqual({ + error: { + code: "USAGE", + message: `Invalid config after setting ${path}: Invalid config value for "${path}": expected a non-empty string`, + }, + }); + expect(refused.written).toBeUndefined(); + } + }, + ); + it("does not let a stray file at the scratch validation path change the outcome", async () => { // why: Guards against B9's second bug: the validation scratch path must never be able to read a // real file, whether one happens to already exist there or not. From ba682a94e0f1fe759c3a9247b3596cf1bf2c19f0 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 09:52:57 +0200 Subject: [PATCH 04/14] test: the phone daemon spawns with its own state, marker and environment (#873) --- .../host/agent-device-supervisor.test.ts | 87 ++++++++++++++++++- 1 file changed, 84 insertions(+), 3 deletions(-) diff --git a/src/agent-device/host/agent-device-supervisor.test.ts b/src/agent-device/host/agent-device-supervisor.test.ts index 469f662ee..8ba5ee3a2 100644 --- a/src/agent-device/host/agent-device-supervisor.test.ts +++ b/src/agent-device/host/agent-device-supervisor.test.ts @@ -15,7 +15,9 @@ import { FakeAgentDeviceHealth } from "../testing.js"; import { AgentDeviceSupervisor, type AgentDeviceAvailability, + type AgentDeviceIosSigning, type AgentDevicePlatform, + type AgentDeviceRole, } from "./agent-device-supervisor.js"; const home = "/home/simlock/.simlock"; @@ -68,12 +70,14 @@ interface Options { readonly expectations?: readonly ScriptedProcessExpectation[]; readonly filesystem?: MemoryFilesystem; readonly home?: string; + readonly ios?: AgentDeviceIosSigning; readonly layout?: (filesystem: MemoryFilesystem) => Promise; readonly leaseMaxTtlMs?: number; readonly listening?: boolean; readonly livePids?: readonly number[]; readonly nodeVersion?: string; readonly platforms?: readonly AgentDevicePlatform[]; + readonly role?: AgentDeviceRole; readonly record?: { readonly pid: number; readonly entry: string; readonly startedAt: number }; readonly spawnThrows?: Error; readonly stateDirContents?: (filesystem: MemoryFilesystem) => Promise; @@ -82,6 +86,7 @@ interface Options { async function arrange(options: Options = {}) { const clock = new FakeClock(1_000_000); + const stem = options.role === "phones" ? "agent-device-phones" : "agent-device"; const filesystem = options.filesystem ?? new MemoryFilesystem(); const simlockHome = options.home ?? home; const sink = new MemoryLogSink(); @@ -133,7 +138,7 @@ async function arrange(options: Options = {}) { const mode = options.daemonJson?.(startIndex) ?? "ready"; if (mode !== "none") { void filesystem.writeFileAtomic( - `${simlockHome}/agent-device/daemon.json`, + `${simlockHome}/${stem}/daemon.json`, JSON.stringify({ httpPort, pid: mode === "ready" ? pid : pid + 1_000, @@ -168,6 +173,7 @@ async function arrange(options: Options = {}) { filesystem, healthProbe: health, home: simlockHome, + ...(options.ios === undefined ? {} : { ios: options.ios }), leaseMaxTtlMs: options.leaseMaxTtlMs ?? 4 * 60 * 60_000, logger, nodePath, @@ -175,7 +181,7 @@ async function arrange(options: Options = {}) { platforms: options.platforms ?? ["ios", "android"], processRunner: runner, processSupervisor: processes, - role: "simulators", + role: options.role ?? "simulators", tcpProbe: probe, }); const harness = { @@ -244,14 +250,19 @@ function daemonSpawn( entry = internalEntry, extra: Partial = {}, simlockHome = home, + marker: readonly string[] = [], ): ScriptedProcessExpectation { return { hangs: true, - match: { args: [entry, `--simlock-home=${simlockHome}`], command: nodePath }, + match: { args: [entry, `--simlock-home=${simlockHome}`, ...marker], command: nodePath }, ...extra, }; } +function phoneSpawn(simlockHome = home): ScriptedProcessExpectation { + return daemonSpawn(internalEntry, {}, simlockHome, ["--simlock-role=phones"]); +} + function psRun(pid: number, line: string, code = 0): ScriptedProcessExpectation { return { match: { args: ["-ww", "-o", "args=", "-p", String(pid)], command: "ps" }, @@ -669,6 +680,76 @@ describe("AgentDeviceSupervisor spawning", () => { }); }); +describe("AgentDeviceSupervisor in the phones role", () => { + const phonesStateDir = `${home}/agent-device-phones`; + const signing = { + bundleId: "com.example.runner", + provisioningProfile: "Simlock Runner Profile", + signingIdentity: "Apple Development: Ada (XYZ)", + teamId: "ABCDE12345", + }; + const signingEnvironment = { + AGENT_DEVICE_IOS_BUNDLE_ID: "com.example.runner", + AGENT_DEVICE_IOS_PROVISIONING_PROFILE: "Simlock Runner Profile", + AGENT_DEVICE_IOS_SIGNING_IDENTITY: "Apple Development: Ada (XYZ)", + AGENT_DEVICE_IOS_TEAM_ID: "ABCDE12345", + }; + + it.each([ + ["iOS and Android on, keys set", ["ios", "android"], signing, signingEnvironment], + ["iOS and Android on, keys unset", ["ios", "android"], undefined, {}], + ["iOS off", ["android"], signing, signingEnvironment], + ["Android off", ["ios"], undefined, {}], + ] as const)( + "spawns the phone daemon with its own state directory, policy file, pid record and marker suffix, no simulator set and no driver lease key, adb on 5037 and the configured AGENT_DEVICE_IOS_ keys: %s", + async (_case, platforms, ios, signingKeys) => { + const harness = await run({ + baseEnvironment: { + ANDROID_ADB_SERVER_ADDRESS: "operator-host", + ANDROID_ADB_SERVER_PORT: "5038", + ANDROID_SERIAL: "emulator-5554", + HOME: "/home/operator", + PATH: "/usr/local/bin:/usr/bin", + }, + driverEnvironment: { + ANDROID_ADB_SERVER_PORT: "5038", + SIMLOCK_IOS_DEVICE_SET: "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/devices/ios", + }, + expectations: [versionRun(), phoneSpawn()], + ...(ios === undefined ? {} : { ios }), + platforms, + role: "phones", + }); + + expect(daemonSpawns(harness)).toEqual([ + [nodePath, internalEntry, `--simlock-home=${home}`, "--simlock-role=phones"], + ]); + expect(harness.runner.calls[1]?.options.env).toEqual({ + AGENT_DEVICE_CLAIMS_DIR: `${phonesStateDir}/device-claims`, + AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: "0", + AGENT_DEVICE_DAEMON_POLICY: `${phonesStateDir}/policy.json`, + AGENT_DEVICE_DAEMON_SERVER_MODE: "http", + AGENT_DEVICE_LEASE_MAX_TTL_MS: String(24 * 60 * 60_000), + AGENT_DEVICE_STATE_DIR: phonesStateDir, + ANDROID_ADB_SERVER_PORT: "5037", + HOME: "/home/operator", + PATH: "/usr/local/bin:/usr/bin", + ...signingKeys, + }); + await expect(harness.filesystem.readFile(`${phonesStateDir}/policy.json`)).resolves.toContain( + "device-shutdown", + ); + expect( + JSON.parse(await harness.filesystem.readFile(`${home}/agent-device-phones-daemon.json`)), + ).toMatchObject({ + entry: internalEntry, + }); + expect(await harness.filesystem.exists(`${stateDir}/policy.json`)).toBe(false); + expect(await harness.filesystem.exists(recordPath)).toBe(false); + }, + ); +}); + describe("AgentDeviceSupervisor state directory", () => { it("creates a missing state directory with mode 0700", async () => { const harness = await run(); From f0ba53d5e10769862900c7cec57a838826ad9435 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 09:53:20 +0200 Subject: [PATCH 05/14] feat(agent-device): the phone daemon sees no simulator set and the default adb server (#873) --- .../host/agent-device-supervisor.ts | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/agent-device/host/agent-device-supervisor.ts b/src/agent-device/host/agent-device-supervisor.ts index b5760b4db..c85bd2702 100644 --- a/src/agent-device/host/agent-device-supervisor.ts +++ b/src/agent-device/host/agent-device-supervisor.ts @@ -71,6 +71,17 @@ const IOS_SIGNING_ENVIRONMENT = { teamId: "AGENT_DEVICE_IOS_TEAM_ID", } as const satisfies Record; +/** why: the adb server the physical Android driver uses, the host's default one. */ +const DEFAULT_ADB_SERVER_PORT = "5037"; + +/** why: an operator shell that exported any of these would point the phone daemon at another adb server or device. */ +const ADB_SELECTION_KEYS = new Set([ + "ANDROID_ADB_SERVER_PORT", + "ANDROID_ADB_SERVER_ADDRESS", + "ADB_SERVER_SOCKET", + "ANDROID_SERIAL", +]); + export interface AgentDeviceSupervisorOptions { readonly baseEnvironment: NodeJS.ProcessEnv; readonly clock: Clock; @@ -534,11 +545,12 @@ export class AgentDeviceSupervisor { const env: NodeJS.ProcessEnv = {}; const phones = o.role === "phones"; for (const [key, value] of Object.entries(o.baseEnvironment)) { - if (!key.startsWith("AGENT_DEVICE_")) env[key] = value; + if (key.startsWith("AGENT_DEVICE_") || (phones && ADB_SELECTION_KEYS.has(key))) continue; + env[key] = value; } Object.assign( env, - o.driverEnvironment, + phones ? {} : o.driverEnvironment, agentDeviceDaemonEnvironment({ leaseMaxTtlMs: o.leaseMaxTtlMs, policyPath, @@ -546,6 +558,7 @@ export class AgentDeviceSupervisor { }), ); if (phones) { + env["ANDROID_ADB_SERVER_PORT"] = DEFAULT_ADB_SERVER_PORT; for (const [key, name] of Object.entries(IOS_SIGNING_ENVIRONMENT)) { const value = o.ios?.[key as keyof AgentDeviceIosSigning]; if (value !== undefined) env[name] = value; From 0e6cb0264f59df9e4d2f0cd108b0358d02565069 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 09:53:59 +0200 Subject: [PATCH 06/14] test: daemon start reaps by role (#873) --- .../host/agent-device-supervisor.test.ts | 72 ++++++++++++++++++- 1 file changed, 69 insertions(+), 3 deletions(-) diff --git a/src/agent-device/host/agent-device-supervisor.test.ts b/src/agent-device/host/agent-device-supervisor.test.ts index 8ba5ee3a2..6fd72e05c 100644 --- a/src/agent-device/host/agent-device-supervisor.test.ts +++ b/src/agent-device/host/agent-device-supervisor.test.ts @@ -104,7 +104,7 @@ async function arrange(options: Options = {}) { await installAgentDevice(filesystem, simlockHome, options); if (options.record !== undefined) { await filesystem.writeFileAtomic( - `${simlockHome}/agent-device-daemon.json`, + `${simlockHome}/${stem}-daemon.json`, JSON.stringify(options.record), ); } @@ -270,8 +270,9 @@ function psRun(pid: number, line: string, code = 0): ScriptedProcessExpectation }; } -function ownLine(entry = internalEntry, simlockHome = home): string { - return `${nodePath} ${entry} --simlock-home=${simlockHome}`; +function ownLine(entry = internalEntry, simlockHome = home, role?: "phones"): string { + const suffix = role === undefined ? "" : " --simlock-role=phones"; + return `${nodePath} ${entry} --simlock-home=${simlockHome}${suffix}`; } function record(pid: number, entry = internalEntry) { @@ -750,6 +751,71 @@ describe("AgentDeviceSupervisor in the phones role", () => { ); }); +describe("AgentDeviceSupervisor reaping by role", () => { + const phonesRecordPath = `${home}/agent-device-phones-daemon.json`; + const leftBehind = (path: string, pid: number) => async (filesystem: MemoryFilesystem) => { + await filesystem.writeFileAtomic(path, JSON.stringify(record(pid))); + }; + + it.each([ + { + name: "a phones record whose pid line ends with the phones suffix is signalled, with the simulator record left alone", + role: "phones", + line: ownLine(internalEntry, home, "phones"), + otherRecord: recordPath, + signalled: true, + survivingRecord: recordPath, + }, + { + name: "a simulators record whose pid line ends with the simulators suffix is signalled, with the phones record left alone", + role: "simulators", + line: ownLine(), + otherRecord: phonesRecordPath, + signalled: true, + survivingRecord: phonesRecordPath, + }, + { + name: "a phones record whose pid line is a simulator daemon's is not signalled", + role: "phones", + line: ownLine(), + otherRecord: undefined, + signalled: false, + survivingRecord: undefined, + }, + { + name: "a simulators record whose pid line is a phone daemon's is not signalled", + role: "simulators", + line: ownLine(internalEntry, home, "phones"), + otherRecord: undefined, + signalled: false, + survivingRecord: undefined, + }, + ] as const)( + "signals only a pid whose line ends with its own role's suffix, and never touches the other role's record: $name", + async ({ line, otherRecord, role, signalled, survivingRecord }) => { + const harness = await run({ + expectations: [ + psRun(900, line), + versionRun(), + role === "phones" ? phoneSpawn() : daemonSpawn(), + ], + layout: async (filesystem) => { + if (otherRecord !== undefined) await leftBehind(otherRecord, 901)(filesystem); + }, + livePids: [900, 901], + record: record(900), + role, + }); + + expect(harness.processes.signals).toEqual(signalled ? [{ pid: 900, signal: "SIGTERM" }] : []); + expect(stateOf(harness)).toBe("running"); + if (survivingRecord !== undefined) { + expect(await readJson(harness, survivingRecord)).toMatchObject({ pid: 901 }); + } + }, + ); +}); + describe("AgentDeviceSupervisor state directory", () => { it("creates a missing state directory with mode 0700", async () => { const harness = await run(); From aefdc3fe352edf7164f556dfdf717f908e068040 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 09:54:43 +0200 Subject: [PATCH 07/14] test: the phone daemon stops and restarts on its own schedule (#873) --- .../host/agent-device-supervisor.test.ts | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/agent-device/host/agent-device-supervisor.test.ts b/src/agent-device/host/agent-device-supervisor.test.ts index 6fd72e05c..cf438d616 100644 --- a/src/agent-device/host/agent-device-supervisor.test.ts +++ b/src/agent-device/host/agent-device-supervisor.test.ts @@ -816,6 +816,52 @@ describe("AgentDeviceSupervisor reaping by role", () => { ); }); +describe("AgentDeviceSupervisor stopping and restarting the phone daemon", () => { + const phonesRecordPath = `${home}/agent-device-phones-daemon.json`; + const phones = { + expectations: [versionRun(), phoneSpawn(), versionRun(), phoneSpawn()], + role: "phones", + } as const; + + it("stop signals the phone daemon and removes its record", async () => { + const harness = await run(phones); + const pid = harness.children[0]?.pid; + + await advancing(harness, harness.agentDevice.stop()); + + expect(harness.processes.signals).toEqual([{ pid, signal: "SIGTERM" }]); + await expect(harness.filesystem.exists(phonesRecordPath)).resolves.toBe(false); + expect(stateOf(harness)).toBe("off"); + }); + + it.each([ + { afterMs: 60_000, restartsAtOnce: true }, + { afterMs: 5_000, restartsAtOnce: false }, + ])( + "a phone daemon that exits $afterMs ms after it was ready restarts at once only when that is 60 s or more, else after 30 s with a warning that names its role", + async ({ afterMs, restartsAtOnce }) => { + const harness = await run(phones); + await advanceBy(harness, afterMs); + + harness.children[0]?.exit(9); + await flush(); + + if (restartsAtOnce) { + expect(stateOf(harness)).toBe("starting"); + } else { + expect(unavailable(harness)).toMatchObject({ reason: "start-failed" }); + expect( + warnings(harness).some((line) => line.includes("agent-device (phones) start failed")), + ).toBe(true); + await advanceBy(harness, 29_000); + expect(daemonSpawns(harness)).toHaveLength(1); + } + await advanceUntil(harness, () => stateOf(harness) === "running", 5_000); + expect(daemonSpawns(harness)).toHaveLength(2); + }, + ); +}); + describe("AgentDeviceSupervisor state directory", () => { it("creates a missing state directory with mode 0700", async () => { const harness = await run(); From be2ab3a448620e1e2cd393243ae6be01cb272eda Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 09:55:27 +0200 Subject: [PATCH 08/14] test: doctor lists the phone daemon's finding while the capability follows the simulator daemon (#873) --- src/daemon/main.test.ts | 115 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 113 insertions(+), 2 deletions(-) diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index f57ed54a4..ad3543a04 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -2935,6 +2935,7 @@ describe("startDaemon with the agent-device edge", () => { readonly processRunner: ScriptedProcessRunner; readonly processSupervisor: FakeProcessSupervisor; readonly role?: "gateway"; + readonly tcpProbe?: FakeTcpProbe; }, ) { const clock = ports.clock ?? new FakeClock(1_000); @@ -2958,11 +2959,11 @@ describe("startDaemon with the agent-device edge", () => { ], processRunner: ports.processRunner, processSupervisor: ports.processSupervisor, - tcpProbe: new FakeTcpProbe(), + tcpProbe: ports.tcpProbe ?? new FakeTcpProbe(), version: "1.2.3", }); runningDaemons.push(daemon); - return { daemon, sink }; + return { clock, daemon, sink }; } it("runs a module's beforeDriversDispose and stops agent-device's child, both before the drivers are disposed", async () => { @@ -3328,6 +3329,116 @@ describe("startDaemon with the agent-device edge", () => { .toEqual(["agent-device", "alpha"]); }); + it.each([ + { + name: "both daemons down: agent-device is found nowhere", + simulator: "missing", + phones: undefined, + findings: ["simulator", "phones", "alpha"], + capability: "unavailable", + }, + { + name: "the phone daemon finds a wrong version", + simulator: "running", + phones: "0.20.3\n", + findings: ["phones", "alpha"], + capability: "available", + }, + { + name: "the phone daemon cannot start", + simulator: "running", + phones: "unstartable", + findings: ["phones", "alpha"], + capability: "available", + }, + ] as const)( + "lists a phone daemon finding that starts with `phone daemon: ` after the simulator daemon's and before another module's, while the capability follows the simulator daemon: $name", + async ({ capability, findings, phones, simulator }) => { + const setup = await setUp({ + capabilities: { + "agent-device": { + command: simulator === "missing" ? "/opt/missing/agent-device" : command, + enabled: true, + }, + alpha: { enabled: true }, + }, + }); + const version = (stdout: string) => ({ + match: { args: [realCli, "--version"], command: process.execPath }, + result: { code: 0, stderr: "", stdout }, + }); + const health = new FakeAgentDeviceHealth(); + health.respondWith({ rpcProtocolVersion: 2, service: "agent-device-daemon" }); + const tcpProbe = new FakeTcpProbe(); + const runner = new ScriptedProcessRunner( + simulator === "missing" + ? [] + : [ + version("0.21.28\n"), + { + hangs: true, + match: { + args: [entry, `--simlock-home=${setup.directory}`], + command: process.execPath, + }, + onSpawn: async () => { + await setup.filesystem.writeFileAtomic( + join(setup.directory, "agent-device", "daemon.json"), + JSON.stringify({ httpPort: 4310, pid: 2, token: "t" }), + ); + tcpProbe.startListening(4310); + }, + }, + ...(phones === "unstartable" || phones === undefined + ? [version("0.21.28\n")] + : [version(phones)]), + ], + ); + const { clock, daemon } = await startEdge(setup, { + agentDevice: agentDeviceModuleWith({ health }), + clock: new FakeClock(1_000), + modules: [ + fakeModule({ + findings: () => [{ message: "it is down", remedy: "bring it up" }], + name: "alpha", + }), + ], + processRunner: runner, + processSupervisor: new FakeProcessSupervisor(), + tcpProbe, + }); + const unavailable = async () => + ( + (await daemon.dispatch("doctor.run", {}, operator)) as { + readonly findings: readonly { + readonly kind: string; + readonly module?: string; + readonly message?: string; + }[]; + } + ).findings.filter((finding) => finding.kind === "module-unavailable"); + const labelled = async () => + (await unavailable()).map((finding) => + finding.module === "alpha" + ? "alpha" + : finding.message?.startsWith("phone daemon: ") === true + ? "phones" + : "simulator", + ); + // why: the simulator daemon's polls sleep on the fake clock, so the test advances it until the findings settle. + for (let tick = 0; tick < 400; tick += 1) { + if (JSON.stringify(await labelled()) === JSON.stringify(findings)) break; + await new Promise((resolve) => setImmediate(resolve)); + clock.advance(100); + } + + expect(await labelled()).toEqual(findings); + const status = await daemon.dispatch("status.get", {}, operator); + expect(status.capabilities).toMatchObject([{ name: "agent-device", state: capability }]); + }, + 20_000, + ); + it("reports module-unavailable for agent-device, naming the command when capabilities.agent-device.command is found nowhere", async () => { const setup = await setUp({ capabilities: { "agent-device": { command: "/opt/missing/agent-device", enabled: true } }, From a49c40953aefc156ba7b49d32bd49fc30e315d60 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 09:56:57 +0200 Subject: [PATCH 09/14] feat(agent-device): doctor lists the phone daemon's finding beside the simulator daemon's (#873) --- src/agent-device/host/availability-findings.ts | 5 +++-- src/agent-device/worker.ts | 8 ++++---- src/daemon/main.test.ts | 8 +++++--- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/agent-device/host/availability-findings.ts b/src/agent-device/host/availability-findings.ts index f9e72fa69..568dd60f2 100644 --- a/src/agent-device/host/availability-findings.ts +++ b/src/agent-device/host/availability-findings.ts @@ -1,15 +1,16 @@ import type { OptionalModuleFinding } from "../../core/index.js"; -import type { AgentDeviceAvailability } from "./agent-device-supervisor.js"; +import type { AgentDeviceAvailability, AgentDeviceRole } from "./agent-device-supervisor.js"; export function agentDeviceFindings( availability: AgentDeviceAvailability, + role: AgentDeviceRole = "simulators", ): readonly OptionalModuleFinding[] { if (availability.state !== "unavailable") return []; return [ { kind: "module-unavailable", module: "agent-device", - message: availability.message, + message: role === "phones" ? `phone daemon: ${availability.message}` : availability.message, remedy: availability.remedy, }, ]; diff --git a/src/agent-device/worker.ts b/src/agent-device/worker.ts index 028e89e11..fcb9d3b22 100644 --- a/src/agent-device/worker.ts +++ b/src/agent-device/worker.ts @@ -120,10 +120,10 @@ export function createWorkerWith( return { capability: agentDeviceCapabilitySource(parts), findings: () => - agentDeviceFindings(supervisor.availability()).map(({ message, remedy }) => ({ - message, - remedy, - })), + [ + ...agentDeviceFindings(supervisor.availability()), + ...agentDeviceFindings(phoneSupervisor.availability(), "phones"), + ].map(({ message, remedy }) => ({ message, remedy })), hooks: { // why: not awaited, since simlock's start never waits for agent-device, and a daemon that lost the socket race never gets here, so it reaps nothing. afterSocketClaimed: () => { diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index ad3543a04..1d0473c38 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -3296,7 +3296,7 @@ describe("startDaemon with the agent-device edge", () => { }); }, 10_000); - it("lists agent-device's module-unavailable finding before a module's own", async () => { + it("lists agent-device's module-unavailable findings, one per daemon, before a module's own", async () => { const setup = await setUp({ capabilities: { "agent-device": { command: "/opt/missing/agent-device", enabled: true }, @@ -3326,7 +3326,7 @@ describe("startDaemon with the agent-device edge", () => { .map((finding) => finding.module), { timeout: 4_000 }, ) - .toEqual(["agent-device", "alpha"]); + .toEqual(["agent-device", "agent-device", "alpha"]); }); it.each([ @@ -3434,7 +3434,9 @@ describe("startDaemon with the agent-device edge", () => { expect(await labelled()).toEqual(findings); const status = await daemon.dispatch("status.get", {}, operator); - expect(status.capabilities).toMatchObject([{ name: "agent-device", state: capability }]); + expect(status.capabilities?.find((entry) => entry.name === "agent-device")?.state).toBe( + capability, + ); }, 20_000, ); From 14066ae956b98827b713c0e7d6adf4700a01460f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 09:57:24 +0200 Subject: [PATCH 10/14] test: the worker stops both agent-device daemons (#873) --- src/daemon/main.test.ts | 63 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 1d0473c38..266481a53 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -3016,6 +3016,69 @@ describe("startDaemon with the agent-device edge", () => { ]); }); + it("stops both agent-device daemons when the worker stops, the phone daemon and the simulator daemon each by its own pid", async () => { + const setup = await setUp({ capabilities: { "agent-device": { command, enabled: true } } }); + const health = new FakeAgentDeviceHealth(); + health.respondWith({ rpcProtocolVersion: 2, service: "agent-device-daemon" }); + const tcpProbe = new FakeTcpProbe(); + const processSupervisor = new KillingSupervisor(); + const version = { + match: { args: [realCli, "--version"], command: process.execPath }, + result: { code: 0, stderr: "", stdout: "0.21.28\n" }, + }; + const daemonAt = (stateDirName: string, pid: number, port: number, marker: string[]) => ({ + hangs: true, + match: { + args: [entry, `--simlock-home=${setup.directory}`, ...marker], + command: process.execPath, + }, + onSpawn: async () => { + processSupervisor.markAlive(pid); + await setup.filesystem.writeFileAtomic( + join(setup.directory, stateDirName, "daemon.json"), + JSON.stringify({ httpPort: port, pid, token: "t" }), + ); + tcpProbe.startListening(port); + }, + }); + const runner = new ScriptedProcessRunner([ + version, + daemonAt("agent-device", 2, 4310, []), + version, + daemonAt("agent-device-phones", 4, 4311, ["--simlock-role=phones"]), + ]); + const spawn = runner.spawn.bind(runner); + vi.spyOn(runner, "spawn").mockImplementation((spawned, args, options) => { + const handle = spawn(spawned, args, options); + if (args[0] === entry) processSupervisor.kills.set(handle.pid, () => handle.kill()); + return handle; + }); + const { clock, daemon } = await startEdge(setup, { + agentDevice: agentDeviceModuleWith({ health }), + clock: new FakeClock(1_000), + processRunner: runner, + processSupervisor, + tcpProbe, + }); + for (let tick = 0; tick < 400 && runner.calls.length < 4; tick += 1) { + await new Promise((resolve) => setImmediate(resolve)); + clock.advance(100); + } + for (let tick = 0; tick < 20; tick += 1) { + await new Promise((resolve) => setImmediate(resolve)); + clock.advance(100); + } + + const stopping = daemon.stop("test"); + for (let tick = 0; tick < 100; tick += 1) { + await new Promise((resolve) => setImmediate(resolve)); + clock.advance(100); + } + await stopping; + + expect(processSupervisor.signals.map((signal) => signal.pid).sort()).toEqual([2, 4]); + }); + it("resolves and grants a lease to an ordinary client while agent-device's /health never answers", async () => { const setup = await setUp({ capabilities: { "agent-device": { command, enabled: true } } }); const processSupervisor = new KillingSupervisor(); From 85b1824e1349b350635de911bb7d365531a9a58d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 09:58:25 +0200 Subject: [PATCH 11/14] docs(agent-device): the worker runs two daemons; teardown reads both pid records (#873) --- docs/internal/ARCHITECTURE.md | 2 +- e2e/helpers/env.ts | 18 ++++++---- src/agent-device/AGENTS.md | 35 ++++++++++++------- .../docs/docs/reference/configuration.mdx | 4 +++ .../docs/docs/using-devices/agent-device.mdx | 2 +- 5 files changed, 41 insertions(+), 20 deletions(-) diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 8b0dfc247..63bebe4d7 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -47,7 +47,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘ | gateway | Fleet queue, routing, forwarding to workers, relay | [gateway](../../src/gateway/AGENTS.md) · [routing](../../src/gateway/routing/AGENTS.md) | | alerts | Gateway only: chosen fleet events POSTed to webhook destinations | [alerts](../../src/alerts/AGENTS.md) | | link | Byte channels over the uplink | [link](../../src/link/AGENTS.md) | -| agent-device | Optional edge: the agent-device daemon beside a worker, its HTTP front | [agent-device](../../src/agent-device/AGENTS.md) | +| agent-device | Optional edge: the two agent-device daemons (simulators, phones) beside a worker, its HTTP front | [agent-device](../../src/agent-device/AGENTS.md) | | stream | Optional edge: a leased device's live screen over HTTP, relayed by a gateway | [stream](../../src/stream/AGENTS.md) | | auth | Credential → identity: tokens, admin secret, `hello`, uplink join token, HTTP strategies | [auth](../../src/auth/AGENTS.md) | | http | HTTP frontend: routes, SSE | [http](../../src/http/AGENTS.md) | diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index aa5c4a6cc..c97734dfe 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -429,12 +429,14 @@ export async function withSharedDaemon(options: WithDaemonOptions = {}): Promise }, async teardown() { // why: read before teardown deletes the home. - const pid = await readAgentDevicePid(state.dataDirectory); + const simulatorsPid = await readAgentDevicePid(state.dataDirectory, "agent-device"); + const phonesPid = await readAgentDevicePid(state.dataDirectory, "agent-device-phones"); const resolved = await realpath(state.dataDirectory).catch(() => state.dataDirectory); try { await teardown(state); } finally { - await killLeftoverAgentDevice(resolved, pid); + await killLeftoverAgentDevice(resolved, simulatorsPid, ""); + await killLeftoverAgentDevice(resolved, phonesPid, " --simlock-role=phones"); } }, }; @@ -520,8 +522,8 @@ async function teardown(state: TeardownState): Promise { } } -async function readAgentDevicePid(home: string): Promise { - const text = await readFileIfExists(join(home, "agent-device-daemon.json")); +async function readAgentDevicePid(home: string, stem: string): Promise { + const text = await readFileIfExists(join(home, `${stem}-daemon.json`)); if (text === undefined) return undefined; try { const record = JSON.parse(text) as { pid?: unknown }; @@ -531,13 +533,17 @@ async function readAgentDevicePid(home: string): Promise { } } -async function killLeftoverAgentDevice(home: string, pid: number | undefined): Promise { +async function killLeftoverAgentDevice( + home: string, + pid: number | undefined, + roleSuffix: string, +): Promise { if (pid === undefined || !(await isProcessAlive(pid))) return; const { stdout } = await execFileAsync("ps", ["-ww", "-o", "args=", "-p", String(pid)]).catch( () => ({ stdout: "" }), ); // why: the supervisor puts the resolved home in the marker; the caller resolved it before the home was removed. - const marker = `--simlock-home=${home}`; + const marker = `--simlock-home=${home}${roleSuffix}`; if (!stdout.trim().endsWith(marker)) return; try { process.kill(pid, "SIGKILL"); diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index 29537efec..ef2d8fe9c 100644 --- a/src/agent-device/AGENTS.md +++ b/src/agent-device/AGENTS.md @@ -1,7 +1,7 @@ # Agent-device edge -Does: runs one agent-device daemon per worker and serves the agent-device CLI at `/v1/agent-device/*`, one simlock lease per agent-device lease. -Entry: `index.ts` → `agentDeviceModule`. The front parts live in `front/edge-parts.ts` (`createGatewayAgentDeviceFrontParts`, `createAgentDeviceFront`, `disposeAgentDeviceEdge`, `cancelWaitingAllocates`). The gateway half is `gateway.ts` (`createGateway`, builds the `FleetPort` from the gateway context); the worker half is `worker.ts` (`createAgentDeviceEdgeParts`, builds `AgentDeviceSupervisor`). The module host loads both. +Does: runs two agent-device daemons per worker (the simulator daemon over Simlock's simulator set, the phone daemon beside it with no set) and serves the agent-device CLI at `/v1/agent-device/*`, one simlock lease per agent-device lease. +Entry: `index.ts` → `agentDeviceModule`. The front parts live in `front/edge-parts.ts` (`createGatewayAgentDeviceFrontParts`, `createAgentDeviceFront`, `disposeAgentDeviceEdge`, `cancelWaitingAllocates`). The gateway half is `gateway.ts` (`createGateway`, builds the `FleetPort` from the gateway context); the worker half is `worker.ts` (`createAgentDeviceEdgeParts`, builds one `AgentDeviceSupervisor` per role). The module host loads both. Uses: ports, auth (`Identity`), http (session, errors), contract types, core and leasing types. Never imports: gateway, drivers, `fs`, `child_process`. Imported by: the module registry (`index.ts` only); `daemon/main.ts` imports nothing from it (tests may use `testing.ts`). Pinned in `lint-rules.test.ts`. Off unless `capabilities.agent-device.enabled` (false). Off: nothing mounted, no daemon. @@ -11,11 +11,11 @@ Off unless `capabilities.agent-device.enabled` (false). Off: nothing mounted, no | File | Role | | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `definition.ts` | `agentDeviceModule`: config, defaults, cap check; loads `worker.ts` only when on | -| `worker.ts` | `createWorker`: supervisor, edge parts, capability, relay target, mount, hooks | -| `host/agent-device-supervisor.ts` | Reap, start, watch, stop the daemon; availability state | +| `worker.ts` | `createWorker`: both supervisors, edge parts, capability, relay target, mount, hooks | +| `host/agent-device-supervisor.ts` | Reap, start, watch, stop one role's daemon (`simulators` or `phones`); availability state | | `host/install.ts` | `findAgentDevice`: command → install root → daemon entry | | `host/health.ts` | `NodeAgentDeviceHealthProbe`: `GET /health`, 5 s | -| `host/availability-findings.ts` | `agentDeviceFindings` for `simlock doctor` | +| `host/availability-findings.ts` | `agentDeviceFindings` for `simlock doctor`; a phone daemon's message starts `phone daemon: ` | | `host/upstream.ts` | `AgentDeviceUpstream` port; `SupervisorAgentDeviceUpstream` | | `host/host.ts` | `AgentDeviceHost`: `@agent-device/proxy`, tenant, 2 GiB download cap | | `host/lease-end.ts` | `ReleaseScopeRecord`, `AgentDeviceLeaseEnd` (lease-end participant) | @@ -34,17 +34,28 @@ Off unless `capabilities.agent-device.enabled` (false). Off: nothing mounted, no ## How it works -Supervisor start (`AgentDeviceSupervisor.start`, at daemon start): - -1. Reap — pid from `/agent-device-daemon.json`, else the state dir's `daemon.json`. - Signal only if `ps` args end in `--simlock-home=`; SIGTERM, check again, SIGKILL. +A worker runs two supervisors, one per role. The `simulators` role is the simulator daemon: +state dir `/agent-device`, pid record `agent-device-daemon.json`, marker +`--simlock-home=`. The `phones` role is the phone daemon: state dir +`agent-device-phones`, record `agent-device-phones-daemon.json`, marker +`--simlock-home= --simlock-role=phones`; its env has no simulator set and no driver +lease key, `ANDROID_ADB_SERVER_PORT=5037` (the operator's adb selection keys dropped), and the +`AGENT_DEVICE_IOS_*` signing keys from `capabilities.agent-device.ios.*`. The phone daemon +starts when the simulator daemon's start has settled, never awaited by Simlock's start. The +`agent-device` capability follows the simulator daemon; doctor lists a finding per daemon. +Nothing is routed to the phone daemon yet. + +Supervisor start (`AgentDeviceSupervisor.start`, at daemon start), per role: + +1. Reap — pid from the role's record, else the state dir's `daemon.json`. + Signal only if `ps` args end in the role's marker; SIGTERM, check again, SIGKILL. 2. Find — `capabilities.agent-device.command` (`agent-device`) on `PATH` or as a path; `package.json` names `agent-device`; a daemon entry under `dist/src`. Never downloads. 3. Check — `--version` ≥ 0.21.28 (a prerelease of it is older); Node ≥ 22.12.0 (`shared/compatibility.ts`). 4. Prepare — state dir `/agent-device` (0700, ours), policy file denying `boot`, `shutdown`, `device-shutdown`; env from `agentDeviceDaemonEnvironment` plus every driver's lease env (iOS device set mapped; no-iOS and no-Android sentinels). -5. Spawn `node --simlock-home=`; write the pid record. +5. Spawn `node `; write the pid record. 6. Ready — `daemon.json` names our pid → port listens → `/health` says `agent-device-daemon`, RPC protocol 2. Then `running`, generation + 1. 7. Exit — after ≥ 60 s running: start again now. Sooner: `unavailable`, retry in 30 s. @@ -127,13 +138,13 @@ under leasing's signal (`lease.endWaitMs`). | Renewal tick | TTL / 3 | lease TTL | | Download cap; `/rpc` body | 2 GiB; 1 MiB | none | -Disk: `/agent-device/` (agent-device's own files) and the pid record. Front map, +Disk: `/agent-device/` and `/agent-device-phones/` (agent-device's own files) and the two pid records. Front map, renewals and release scopes: memory only. ## Rules - The simlock lease is the only clock; an agent-device lease never outlives it. -- A pid is signalled only after the `--simlock-home` marker matches. +- A pid is signalled only after its role's whole marker matches (`--simlock-home`, and `--simlock-role=phones` for the phone daemon). - The edge names no gateway type; the gateway side builds `FleetPort` from its gateway context. - A daemon stop cancels waiting allocates (`cancelWaitingAllocates`) and stops renewals. - Tests: `edge.test.ts`, `gateway-front.test.ts`, `front/*.test.ts`, `host/*.test.ts`. diff --git a/website/src/content/docs/docs/reference/configuration.mdx b/website/src/content/docs/docs/reference/configuration.mdx index 543488c89..8636cef1c 100644 --- a/website/src/content/docs/docs/reference/configuration.mdx +++ b/website/src/content/docs/docs/reference/configuration.mdx @@ -301,6 +301,10 @@ A name Simlock does not know is warned about and ignored. | `capabilities.agent-device.enabled` | boolean | `false` | On a worker: run an agent-device daemon that sees Simlock's devices. On a gateway: serve agent-device and send each agent to a worker that has it. | Both | | `capabilities.agent-device.command` | non-empty string | `agent-device` | The agent-device program: a name looked up on `PATH`, or a path. | Worker | | `capabilities.agent-device.leaseTtlCapMs` | integer from `5000` to `lease.maxTtlMs` | not set (no cap) | Longest TTL for leases agent-device takes through Simlock. A longer TTL is lowered to it; a lease with none gets it. | Both | +| `capabilities.agent-device.ios.teamId` | non-empty string | not set | Apple developer team ID agent-device signs its iPhone runner with. Passed to the phone daemon. | Worker | +| `capabilities.agent-device.ios.bundleId` | non-empty string | not set | Bundle ID of agent-device's iPhone runner. Passed to the phone daemon. | Worker | +| `capabilities.agent-device.ios.provisioningProfile` | non-empty string | not set | Provisioning profile for the iPhone runner. Passed to the phone daemon. | Worker | +| `capabilities.agent-device.ios.signingIdentity` | non-empty string | not set | Code-signing identity for the iPhone runner. Passed to the phone daemon. | Worker | | `capabilities.stream.enabled` | boolean | `false` | Let people watch a leased device's screen. On a gateway: pass each stream through from the worker. | Both | | `capabilities.stream.fps` | integer `1`–`60` | `30` | Highest frame rate. A still screen sends far fewer frames. | Worker | | `capabilities.stream.maxDimension` | integer `96`–`4096` | `720` | Longest side of the picture, in pixels. The setting that changes bandwidth most. | Worker | diff --git a/website/src/content/docs/docs/using-devices/agent-device.mdx b/website/src/content/docs/docs/using-devices/agent-device.mdx index b7d6d5e78..e909c9c8b 100644 --- a/website/src/content/docs/docs/using-devices/agent-device.mdx +++ b/website/src/content/docs/docs/using-devices/agent-device.mdx @@ -7,7 +7,7 @@ import { Steps, Aside } from '@astrojs/starlight/components'; [agent-device](https://github.com/callstack/agent-device) is Callstack's command-line tool for driving mobile apps: it opens an app, reads the screen as a tree of elements, taps, types and takes screenshots. With Simlock, `agent-device open` leases a simulator or emulator from Simlock, and every later command goes to that device. Each agent gets its own device, and a device is wiped when the agent closes it. -Simlock runs one agent-device daemon on each worker and watches it. Agents reach it over HTTP, on the worker or through a gateway, with a Simlock agent token. +Simlock runs two agent-device daemons on each worker and watches both: one over the simulators and emulators Simlock leases, and a phone daemon beside it that sees the phones plugged into the host. The phone daemon needs the iOS signing values agent-device uses for an iPhone, set with `simlock config set capabilities.agent-device.ios.teamId ` (also `bundleId`, `provisioningProfile` and `signingIdentity`), and takes effect on daemon restart. If it cannot start, `simlock doctor` prints a line starting `phone daemon:`; the simulator daemon and the worker's agent-device status are not affected. Agents cannot use the phone daemon yet. Agents reach it over HTTP, on the worker or through a gateway, with a Simlock agent token. ## Before you start From 924072ac3026ede594acb611ab1fce764e77b01d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:00:05 +0200 Subject: [PATCH 12/14] refactor(agent-device): split the supervisor's environment by role (#873) --- .../host/agent-device-supervisor.test.ts | 19 +++++++++++--- .../host/agent-device-supervisor.ts | 25 ++++++++++++------- 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/src/agent-device/host/agent-device-supervisor.test.ts b/src/agent-device/host/agent-device-supervisor.test.ts index cf438d616..3e4c6b15e 100644 --- a/src/agent-device/host/agent-device-supervisor.test.ts +++ b/src/agent-device/host/agent-device-supervisor.test.ts @@ -84,9 +84,23 @@ interface Options { readonly behaviours?: ReadonlyMap; } +function stemOf(role: AgentDeviceRole | undefined): string { + return role === "phones" ? "agent-device-phones" : "agent-device"; +} + +function supervisorRole(options: Options): { + readonly ios?: AgentDeviceIosSigning; + readonly role: AgentDeviceRole; +} { + return { + ...(options.ios === undefined ? {} : { ios: options.ios }), + role: options.role ?? "simulators", + }; +} + async function arrange(options: Options = {}) { const clock = new FakeClock(1_000_000); - const stem = options.role === "phones" ? "agent-device-phones" : "agent-device"; + const stem = stemOf(options.role); const filesystem = options.filesystem ?? new MemoryFilesystem(); const simlockHome = options.home ?? home; const sink = new MemoryLogSink(); @@ -173,7 +187,7 @@ async function arrange(options: Options = {}) { filesystem, healthProbe: health, home: simlockHome, - ...(options.ios === undefined ? {} : { ios: options.ios }), + ...supervisorRole(options), leaseMaxTtlMs: options.leaseMaxTtlMs ?? 4 * 60 * 60_000, logger, nodePath, @@ -181,7 +195,6 @@ async function arrange(options: Options = {}) { platforms: options.platforms ?? ["ios", "android"], processRunner: runner, processSupervisor: processes, - role: options.role ?? "simulators", tcpProbe: probe, }); const harness = { diff --git a/src/agent-device/host/agent-device-supervisor.ts b/src/agent-device/host/agent-device-supervisor.ts index c85bd2702..51f7d083c 100644 --- a/src/agent-device/host/agent-device-supervisor.ts +++ b/src/agent-device/host/agent-device-supervisor.ts @@ -542,8 +542,8 @@ export class AgentDeviceSupervisor { async #environment(policyPath: string): Promise { const o = this.#o; - const env: NodeJS.ProcessEnv = {}; const phones = o.role === "phones"; + const env: NodeJS.ProcessEnv = {}; for (const [key, value] of Object.entries(o.baseEnvironment)) { if (key.startsWith("AGENT_DEVICE_") || (phones && ADB_SELECTION_KEYS.has(key))) continue; env[key] = value; @@ -557,14 +557,22 @@ export class AgentDeviceSupervisor { stateDir: this.#stateDir, }), ); - if (phones) { - env["ANDROID_ADB_SERVER_PORT"] = DEFAULT_ADB_SERVER_PORT; - for (const [key, name] of Object.entries(IOS_SIGNING_ENVIRONMENT)) { - const value = o.ios?.[key as keyof AgentDeviceIosSigning]; - if (value !== undefined) env[name] = value; - } - return env; + if (phones) return Object.assign(env, this.#phoneEnvironment()); + await this.#hideUnusedPlatforms(env); + return env; + } + + #phoneEnvironment(): Record { + const signing: Record = { ANDROID_ADB_SERVER_PORT: DEFAULT_ADB_SERVER_PORT }; + for (const [key, name] of Object.entries(IOS_SIGNING_ENVIRONMENT)) { + const value = this.#o.ios?.[key as keyof AgentDeviceIosSigning]; + if (value !== undefined) signing[name] = value; } + return signing; + } + + async #hideUnusedPlatforms(env: NodeJS.ProcessEnv): Promise { + const o = this.#o; if (o.platforms.includes("ios")) { const deviceSet = o.driverEnvironment["SIMLOCK_IOS_DEVICE_SET"]; if (deviceSet !== undefined) env["AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET"] = deviceSet; @@ -581,7 +589,6 @@ export class AgentDeviceSupervisor { if (!o.platforms.includes("android")) { env["AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST"] = NO_ANDROID_DEVICE_SERIAL; } - return env; } async #waitReady( From 70b8820b9a04e3a3a2e5fe76604186a3e8b543a7 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:07:16 +0200 Subject: [PATCH 13/14] docs(agent-device): the configuration reference says a worker also runs a phone daemon (#873) --- website/src/content/docs/docs/reference/configuration.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/content/docs/docs/reference/configuration.mdx b/website/src/content/docs/docs/reference/configuration.mdx index 8636cef1c..ed2c5e314 100644 --- a/website/src/content/docs/docs/reference/configuration.mdx +++ b/website/src/content/docs/docs/reference/configuration.mdx @@ -298,7 +298,7 @@ A name Simlock does not know is warned about and ignored. | Key | Type | Default | Meaning | Applies to | | ------------------------------------------- | ------------------------------------ | ---------------- | ----------------------------------------------------------------------------------------------------------- | ---------- | -| `capabilities.agent-device.enabled` | boolean | `false` | On a worker: run an agent-device daemon that sees Simlock's devices. On a gateway: serve agent-device and send each agent to a worker that has it. | Both | +| `capabilities.agent-device.enabled` | boolean | `false` | On a worker: run an agent-device daemon that sees Simlock's devices, and a phone daemon beside it. On a gateway: serve agent-device and send each agent to a worker that has it. | Both | | `capabilities.agent-device.command` | non-empty string | `agent-device` | The agent-device program: a name looked up on `PATH`, or a path. | Worker | | `capabilities.agent-device.leaseTtlCapMs` | integer from `5000` to `lease.maxTtlMs` | not set (no cap) | Longest TTL for leases agent-device takes through Simlock. A longer TTL is lowered to it; a lease with none gets it. | Both | | `capabilities.agent-device.ios.teamId` | non-empty string | not set | Apple developer team ID agent-device signs its iPhone runner with. Passed to the phone daemon. | Worker | From b8f5ffe94045ce4ae2f6ac0e45695448bc268d5a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 10:19:11 +0200 Subject: [PATCH 14/14] fix(agent-device): the phone daemon honors platforms, every supervisor log line names its role (#873) --- src/agent-device/AGENTS.md | 32 ++++++--------- .../host/agent-device-supervisor.test.ts | 40 ++++++++++++++++--- .../host/agent-device-supervisor.ts | 20 +++++++--- src/daemon/main.test.ts | 38 +++--------------- 4 files changed, 66 insertions(+), 64 deletions(-) diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index ef2d8fe9c..edc5595e4 100644 --- a/src/agent-device/AGENTS.md +++ b/src/agent-device/AGENTS.md @@ -34,16 +34,14 @@ Off unless `capabilities.agent-device.enabled` (false). Off: nothing mounted, no ## How it works -A worker runs two supervisors, one per role. The `simulators` role is the simulator daemon: -state dir `/agent-device`, pid record `agent-device-daemon.json`, marker -`--simlock-home=`. The `phones` role is the phone daemon: state dir -`agent-device-phones`, record `agent-device-phones-daemon.json`, marker -`--simlock-home= --simlock-role=phones`; its env has no simulator set and no driver -lease key, `ANDROID_ADB_SERVER_PORT=5037` (the operator's adb selection keys dropped), and the -`AGENT_DEVICE_IOS_*` signing keys from `capabilities.agent-device.ios.*`. The phone daemon -starts when the simulator daemon's start has settled, never awaited by Simlock's start. The -`agent-device` capability follows the simulator daemon; doctor lists a finding per daemon. -Nothing is routed to the phone daemon yet. +A worker runs two supervisors, one per role. `simulators`: state dir `/agent-device`, +record `agent-device-daemon.json`, marker `--simlock-home=`. `phones`: state dir +`agent-device-phones`, record `agent-device-phones-daemon.json`, marker adds `--simlock-role=phones`; +its env has no simulator set or driver lease key, `ANDROID_ADB_SERVER_PORT=5037`, the +`AGENT_DEVICE_IOS_*` signing keys (`capabilities.agent-device.ios.*`), and the no-iOS and +no-Android sentinels when a platform is off. It starts once the simulator daemon's start has +settled, never awaited. The capability follows the simulator daemon; doctor lists a finding per +daemon. Nothing is routed to the phone daemon yet. Supervisor start (`AgentDeviceSupervisor.start`, at daemon start), per role: @@ -61,9 +59,7 @@ Supervisor start (`AgentDeviceSupervisor.start`, at daemon start), per role: 7. Exit — after ≥ 60 s running: start again now. Sooner: `unavailable`, retry in 30 s. 8. Stop — SIGTERM, SIGKILL, remove the record; a survivor keeps its record. -Availability: `off` | `starting` | `running` | `unavailable` (`not-found`, `not-agent-device`, -`wrong-version`, `state-dir`, `start-failed`). Only `start-failed` retries; the rest need a -daemon restart. Read by `agentDeviceFindings` (doctor) and `agentDeviceCapabilitySource` +Availability: `off` | `starting` | `running` | `unavailable` (`not-found`, `not-agent-device`, `wrong-version`, `state-dir`, `start-failed`). Only `start-failed` retries; the rest need a daemon restart. Read by `agentDeviceFindings` (doctor) and `agentDeviceCapabilitySource` (the `agent-device` capability in `status.get`). Unavailable: every route answers why. Front (`createFront`, prefix `agent-device`): @@ -72,23 +68,19 @@ Front (`createFront`, prefix `agent-device`): rebuilt into the map first. 2. Non-RPC: a fixed route list (`shared/routes.ts`), else 404. `/health` answers 200 even when unavailable. -3. `/rpc`: body ≤ 1 MiB, one JSON-RPC request; only `command` and `lease.*` methods, as - agent-device's proxy takes no other from a tenant; `classifyCall` → allocate, heartbeat, +3. `/rpc`: body ≤ 1 MiB, one JSON-RPC request; only `command` and `lease.*` methods, as agent-device's proxy takes no other from a tenant; `classifyCall` → allocate, heartbeat, release, command, or refused `wrapped-lease`. 4. `checkRequest`: iOS/Android only; no device selector but the leased one; no device set or allowlist; `install` only from an upload; `devices` alone, not streamed. 5. Allocate → `lease.request` (`front/allocate.ts`), see flow. 6. Heartbeat → forwarded with `ttlMs` raised to the ceiling; on success `renewLease` - (`lease.renew` only if it moves the deadline; a gateway list that trails the grant and omits the lease still relays agent-device's reply). agent-device says gone → `lease.release`, - reply "ended by simlock". + (`lease.renew` only if it moves the deadline; a gateway list that trails the grant and omits the lease still relays agent-device's reply). agent-device says gone → `lease.release`, reply "ended by simlock". 7. Release → forwarded; on success `lease.release`; map marks it ended by `agent`. 8. Command on a lease → `Renewals.begin`: renew every TTL/3 until the body ends, capped at `lease.maxTtlMs`. A reply naming `endedLeases` (in `data`, `error.details`, a streamed `type: "response"` line, or a batch's `data`) → `front/ended.ts` ends each simlock lease this token holds, as a release does. -Host (`AgentDeviceHost.forward`): one proxy per daemon generation. Tags the request, -and `authenticate` sets tenant = requester id, overwriting the client's. Rewrites -`/v1/agent-device` → `/agent-device`. Download: `Content-Length` > 2 GiB → 413 before +Host (`AgentDeviceHost.forward`): one proxy per daemon generation. Tags the request, and `authenticate` sets tenant = requester id, overwriting the client's. Rewrites `/v1/agent-device` → `/agent-device`. Download: `Content-Length` > 2 GiB → 413 before any byte; no length → counted, errors past 2 GiB. Lease end: `ReleaseScopeRecord` reads each allocate reply's scope (tenant, run id, …) diff --git a/src/agent-device/host/agent-device-supervisor.test.ts b/src/agent-device/host/agent-device-supervisor.test.ts index 3e4c6b15e..0bd35192c 100644 --- a/src/agent-device/host/agent-device-supervisor.test.ts +++ b/src/agent-device/host/agent-device-supervisor.test.ts @@ -712,8 +712,21 @@ describe("AgentDeviceSupervisor in the phones role", () => { it.each([ ["iOS and Android on, keys set", ["ios", "android"], signing, signingEnvironment], ["iOS and Android on, keys unset", ["ios", "android"], undefined, {}], - ["iOS off", ["android"], signing, signingEnvironment], - ["Android off", ["ios"], undefined, {}], + [ + "iOS off: the empty private set directory", + ["android"], + signing, + { + ...signingEnvironment, + AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET: `${phonesStateDir}/no-ios-devices`, + }, + ], + [ + "Android off: the allowlist sentinel", + ["ios"], + undefined, + { AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST: "simlock-no-android-device" }, + ], ] as const)( "spawns the phone daemon with its own state directory, policy file, pid record and marker suffix, no simulator set and no driver lease key, adb on 5037 and the configured AGENT_DEVICE_IOS_ keys: %s", async (_case, platforms, ios, signingKeys) => { @@ -1135,6 +1148,11 @@ describe("AgentDeviceSupervisor failed starts", () => { expect(harness.processes.signals.map((entry) => entry.signal)).toEqual(["SIGTERM", "SIGKILL"]); expect(unavailable(harness)).toMatchObject({ reason: "start-failed" }); expect(unavailable(harness).message).toContain(String(pid)); + expect( + warnings(harness).some((line) => + line.includes(`agent-device (simulators) daemon pid ${pid} is still alive after SIGKILL`), + ), + ).toBe(true); expect(await readJson(harness, recordPath)).toMatchObject({ pid }); }); @@ -1378,7 +1396,11 @@ describe("AgentDeviceSupervisor after the daemon is running", () => { expect(daemonSpawns(harness)).toHaveLength(2); expect(harness.runner.calls[3]?.options.env).toEqual(firstEnv); expect(running(harness).generation).toBe(2); - expect(warnings(harness).some((line) => line.includes("42"))).toBe(true); + expect( + warnings(harness).some( + (line) => line.includes("agent-device (simulators) daemon pid") && line.includes("42"), + ), + ).toBe(true); }); it("reports start-failed for a child that exits 5 s after ready, and starts it again only 30 s later", async () => { @@ -1557,7 +1579,11 @@ describe("AgentDeviceSupervisor.stop", () => { await advancing(harness, harness.agentDevice.stop()); expect(await readJson(harness, recordPath)).toMatchObject({ pid }); - expect(warnings(harness).some((line) => line.includes(String(pid)))).toBe(true); + expect( + warnings(harness).some((line) => + line.includes(`agent-device (simulators) daemon pid ${pid} is still alive after`), + ), + ).toBe(true); expect(stateOf(harness)).toBe("off"); }); @@ -1572,7 +1598,11 @@ describe("AgentDeviceSupervisor.stop", () => { await advancing(harness, harness.started as Promise); expect(await readJson(harness, recordPath)).toMatchObject({ pid }); - expect(warnings(harness).some((line) => line.includes(String(pid)))).toBe(true); + expect( + warnings(harness).some((line) => + line.includes(`agent-device (simulators) daemon pid ${pid} is still alive after`), + ), + ).toBe(true); expect(stateOf(harness)).toBe("off"); }); diff --git a/src/agent-device/host/agent-device-supervisor.ts b/src/agent-device/host/agent-device-supervisor.ts index 51f7d083c..b3ae1cabf 100644 --- a/src/agent-device/host/agent-device-supervisor.ts +++ b/src/agent-device/host/agent-device-supervisor.ts @@ -226,7 +226,7 @@ export class AgentDeviceSupervisor { await this.#removeRecord(); } else { this.#o.logger.warn( - `agent-device daemon pid ${child.pid} is still alive after stop; its record is kept for the next start`, + `agent-device (${this.#o.role}) daemon pid ${child.pid} is still alive after stop; its record is kept for the next start`, ); } } @@ -472,7 +472,9 @@ export class AgentDeviceSupervisor { this.#child = undefined; const result = child.exit as ProcessResult; const elapsedMs = this.#o.clock.now() - child.readyAt; - this.#o.logger.warn(`agent-device daemon pid ${child.pid} exited ${describeExit(result)}`); + this.#o.logger.warn( + `agent-device (${this.#o.role}) daemon pid ${child.pid} exited ${describeExit(result)}`, + ); if (elapsedMs >= STABLE_AFTER_READY_MS) { void this.#begin(); return; @@ -557,7 +559,7 @@ export class AgentDeviceSupervisor { stateDir: this.#stateDir, }), ); - if (phones) return Object.assign(env, this.#phoneEnvironment()); + if (phones) Object.assign(env, this.#phoneEnvironment()); await this.#hideUnusedPlatforms(env); return env; } @@ -575,7 +577,9 @@ export class AgentDeviceSupervisor { const o = this.#o; if (o.platforms.includes("ios")) { const deviceSet = o.driverEnvironment["SIMLOCK_IOS_DEVICE_SET"]; - if (deviceSet !== undefined) env["AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET"] = deviceSet; + if (o.role !== "phones" && deviceSet !== undefined) { + env["AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET"] = deviceSet; + } } else { const empty = `${this.#stateDir}/no-ios-devices`; try { @@ -586,7 +590,11 @@ export class AgentDeviceSupervisor { } env["AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET"] = empty; } - if (!o.platforms.includes("android")) { + this.#hideAndroid(env); + } + + #hideAndroid(env: NodeJS.ProcessEnv): void { + if (!this.#o.platforms.includes("android")) { env["AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST"] = NO_ANDROID_DEVICE_SERIAL; } } @@ -648,7 +656,7 @@ export class AgentDeviceSupervisor { return; } this.#o.logger.warn( - `agent-device daemon pid ${child.pid} is still alive after SIGKILL; its record is kept for the next start`, + `agent-device (${this.#o.role}) daemon pid ${child.pid} is still alive after SIGKILL; its record is kept for the next start`, ); this.#fail( reason, diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 266481a53..6d9543e30 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -3359,39 +3359,6 @@ describe("startDaemon with the agent-device edge", () => { }); }, 10_000); - it("lists agent-device's module-unavailable findings, one per daemon, before a module's own", async () => { - const setup = await setUp({ - capabilities: { - "agent-device": { command: "/opt/missing/agent-device", enabled: true }, - alpha: { enabled: true }, - }, - }); - const { daemon } = await startEdge(setup, { - modules: [ - fakeModule({ - findings: () => [{ message: "it is down", remedy: "bring it up" }], - name: "alpha", - }), - ], - processRunner: new ScriptedProcessRunner([]), - processSupervisor: new FakeProcessSupervisor(), - }); - - await expect - .poll( - async () => - ( - (await daemon.dispatch("doctor.run", {}, operator)) as { - readonly findings: readonly { readonly kind: string; readonly module?: string }[]; - } - ).findings - .filter((finding) => finding.kind === "module-unavailable") - .map((finding) => finding.module), - { timeout: 4_000 }, - ) - .toEqual(["agent-device", "agent-device", "alpha"]); - }); - it.each([ { name: "both daemons down: agent-device is found nowhere", @@ -3496,6 +3463,11 @@ describe("startDaemon with the agent-device edge", () => { } expect(await labelled()).toEqual(findings); + expect( + (await unavailable()) + .filter((finding) => finding.module !== "alpha") + .map((f) => f.module), + ).toEqual(findings.filter((label) => label !== "alpha").map(() => "agent-device")); const status = await daemon.dispatch("status.get", {}, operator); expect(status.capabilities?.find((entry) => entry.name === "agent-device")?.state).toBe( capability,