diff --git a/apps/server/src/device/LocalDeviceHost.test.ts b/apps/server/src/device/LocalDeviceHost.test.ts index b29b80a647837..62964ebb38caa 100644 --- a/apps/server/src/device/LocalDeviceHost.test.ts +++ b/apps/server/src/device/LocalDeviceHost.test.ts @@ -52,6 +52,7 @@ const agentFixture = Effect.fn("agentFixture")(function* ( const daemonStopRequested = yield* Deferred.make>(); const stateDir = agentDeviceStateDir(path, path.join(baseDir, "userdata")); const daemonHealthy = yield* Ref.make(true); + const daemonStop = { retainsRecord: false }; const runs: Array = []; for (const [name, version, entry] of [ ["expo-device-hub", DEVICE_HUB_VERSION, "dist/server/cli.mjs"], @@ -109,7 +110,16 @@ const agentFixture = Effect.fn("agentFixture")(function* ( return input.args.includes("devices") ? startup(stateDir) : input.args.includes("daemon") - ? Deferred.succeed(daemonStopRequested, input.args).pipe(Effect.as(processOutput(0))) + ? Deferred.succeed(daemonStopRequested, input.args).pipe( + Effect.andThen(() => + daemonStop.retainsRecord + ? Effect.void + : fs + .remove(path.join(stateDir, "daemon.json"), { force: true }) + .pipe(Effect.orDie), + ), + Effect.as(processOutput(0)), + ) : Effect.succeed(input.args.includes("-list-avds") ? avdOutput : processOutput(0)); }, }), @@ -130,27 +140,36 @@ const agentFixture = Effect.fn("agentFixture")(function* ( ), ); yield* host.ensureReady(() => Effect.void); - return { host, fs, baseDir, stateDir, hub, daemonHealthy, daemonStopRequested, runs }; + return { host, fs, baseDir, stateDir, hub, daemonHealthy, daemonStop, daemonStopRequested, runs }; }); describe("AgentDevice startup", () => { - it.effect("restarts a cached daemon that no longer answers its health check", () => + it.effect("replaces an inherited daemon and reuses only its own healthy daemon", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; let attempts = 0; - const { host, daemonHealthy } = yield* agentFixture((stateDir) => - Effect.gen(function* () { - attempts++; - yield* fs - .writeFileString( - `${stateDir}/daemon.json`, - JSON.stringify({ httpPort: 12345 + attempts, token: `token-${attempts}` }), - ) - .pipe(Effect.orDie); - return processOutput(0); - }), + const { host, daemonHealthy, runs } = yield* agentFixture( + (stateDir) => + Effect.gen(function* () { + attempts++; + yield* fs + .writeFileString( + `${stateDir}/daemon.json`, + JSON.stringify({ httpPort: 12345 + attempts, token: `token-${attempts}` }), + ) + .pipe(Effect.orDie); + return processOutput(0); + }), + processOutput(0), + { + httpPort: 12345, + token: "previous-token", + pid: process.pid, + version: AGENT_DEVICE_VERSION, + }, ); const first = yield* host.ensureAgentReady(() => Effect.void); + expect(first.agentDevice?.token).toBe("token-1"); expect((yield* host.ensureAgentReady(() => Effect.void)).agentDevice).toEqual( first.agentDevice, ); @@ -159,6 +178,7 @@ describe("AgentDevice startup", () => { yield* Ref.set(daemonHealthy, false); const restarted = yield* host.ensureAgentReady(() => Effect.void); expect(attempts).toBe(2); + expect(runs.filter((run) => run.args.includes("daemon"))).toHaveLength(1); expect(restarted.agentDevice).toMatchObject({ baseUrl: "http://127.0.0.1:12347", token: "token-2", @@ -166,6 +186,29 @@ describe("AgentDevice startup", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + it.effect("does not adopt an inherited daemon that keeps its registration after stop", () => + Effect.gen(function* () { + const previous = { + httpPort: 12345, + token: "previous-token", + pid: process.pid, + version: AGENT_DEVICE_VERSION, + }; + const { host, fs, stateDir, daemonStop } = yield* agentFixture( + () => Effect.die("Do not start a replacement until the old daemon has retired"), + processOutput(0), + previous, + ); + daemonStop.retainsRecord = true; + const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip); + expect(error).toMatchObject({ + _tag: "AgentDeviceStartError", + reason: "daemon_retirement_unconfirmed", + }); + expect(JSON.parse(yield* fs.readFileString(`${stateDir}/daemon.json`))).toEqual(previous); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + it.effect("uses the SDK a later shell environment selects", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.ts index 50089af431ff8..6e27faad1134c 100644 --- a/apps/server/src/device/LocalDeviceHost.ts +++ b/apps/server/src/device/LocalDeviceHost.ts @@ -55,6 +55,8 @@ import { const HUB_READY_TIMEOUT_MS = 30_000; const DAEMON_READY_TIMEOUT_MS = 30_000; const DAEMON_POLL_MS = 100; +// `daemon stop` waits 10s after SIGTERM and 2s after SIGKILL before it retires the registration. +const DAEMON_STOP_TIMEOUT_MS = 15_000; const HUB_RESTART_STABLE_UPTIME_MS = 60_000; const HUB_RESTART_MAX_DELAY_MS = 30_000; @@ -530,6 +532,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { const startAgentDeviceDaemon = Effect.fn("LocalDeviceHost.startAgentDeviceDaemon")(function* ( agentTool: Pick, nodePath: string, + currentEndpoint?: DeviceHost.AgentDaemonEndpoint, ): Effect.fn.Return< DeviceHost.AgentDeviceEndpoint, | DeviceHost.DeviceHostError @@ -567,8 +570,28 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { Effect.scoped, Effect.orElseSucceed(() => false), ); - if (alive) return toEndpoint(existing.value); - yield* fs.remove(daemonFilePath(), { force: true }).pipe(Effect.ignore); + if (alive) { + const endpoint = toEndpoint(existing.value); + if ( + currentEndpoint?.baseUrl === endpoint.baseUrl && + currentEndpoint.token === endpoint.token + ) { + return endpoint; + } + // A previous server's in-memory device sessions cannot be recovered by this host. + yield* stopAgentDeviceDaemon; + if (yield* fs.exists(daemonFilePath()).pipe(Effect.orElseSucceed(() => true))) { + return yield* new DeviceHost.AgentDeviceStartError({ + hostId, + stateDir, + exitCode: null, + reason: "daemon_retirement_unconfirmed", + cause: new Error("The previous agent-device daemon retained its registration."), + }); + } + } else { + yield* fs.remove(daemonFilePath(), { force: true }).pipe(Effect.ignore); + } } // No `daemon start` exists; `devices` is the cheapest command that starts and awaits it. const runResult = yield* runner @@ -661,7 +684,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { agentDeviceStateDir(path, config.stateDir), ], env: { ...hostEnvironment, AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1" }, - timeout: Duration.seconds(10), + timeout: Duration.millis(DAEMON_STOP_TIMEOUT_MS), timeoutBehavior: "timedOutResult", }); }).pipe( @@ -758,6 +781,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { const agentDevice = yield* startAgentDeviceDaemon( running.agentDevice, running.hub.nodePath, + running.agentDevice, ); yield* Ref.set(runningRef, { ...running, agentDevice }); return { ...toReady(running), agentDevice };