TypeScript
fix(server): release agent-device sessions when device_close runs (#21478)
Victor Vogela17ab2e98438
diff --git a/apps/server/src/device/AgentDeviceTarget.ts b/apps/server/src/device/AgentDeviceTarget.tsindex ac66a52f6d2..54affde4eca 100644--- a/apps/server/src/device/AgentDeviceTarget.ts+++ b/apps/server/src/device/AgentDeviceTarget.ts@@ -1,9 +1,12 @@+import { DeviceOperationError } from "@t3tools/contracts";import * as Crypto from "effect/Crypto";+import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as Hex from "effect/encoding/Hex";import * as Schema from "effect/Schema";import * as FileSystem from "effect/FileSystem";import * as Path from "effect/Path";+import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";import type { AgentDaemonEndpoint } from "./DeviceHost.ts";@@ -62,3 +65,36 @@ export const writeAgentDeviceConfig = Effect.fn("AgentDeviceTarget.writeConfig")yield* fs.rename(temporary, file);}).pipe(Effect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.ignore)));});++const AgentCloseResult = Schema.Union([+ Schema.Struct({ result: Schema.Struct({ ok: Schema.Literal(true) }) }),+ Schema.Struct({+ error: Schema.Struct({+ data: Schema.Struct({ code: Schema.Literal("SESSION_NOT_FOUND") }),+ }),+ }),+]);++/** Ends an agent-device session on a running daemon; an already-released session succeeds. */+export const releaseAgentDeviceSession =+ (http: HttpClient.HttpClient, endpoint: AgentDaemonEndpoint) => (session: string) =>+ HttpClientRequest.post(`${endpoint.baseUrl}/rpc`).pipe(+ HttpClientRequest.bearerToken(endpoint.token),+ HttpClientRequest.bodyJson({+ jsonrpc: "2.0",+ id: session,+ method: "agent_device.command",+ params: { command: "close", session, positionals: [], flags: {} },+ }),+ Effect.flatMap((request) => http.pipe(HttpClient.withScope).execute(request)),+ // agent-device reports an already-released session as HTTP 404.+ Effect.filterOrElse((response) => response.status === 404, HttpClientResponse.filterStatusOk),+ Effect.flatMap(HttpClientResponse.schemaBodyJson(AgentCloseResult)),+ Effect.scoped,+ Effect.timeout(Duration.seconds(15)),+ Effect.asVoid,+ Effect.mapError(+ (cause) =>+ new DeviceOperationError({ operation: "close", reason: "request_failed", cause }),+ ),+ );diff --git a/apps/server/src/device/DeviceHost.ts b/apps/server/src/device/DeviceHost.tsindex c168ba657af..7a0962e06f1 100644--- a/apps/server/src/device/DeviceHost.ts+++ b/apps/server/src/device/DeviceHost.ts@@ -145,6 +145,16 @@ export interface DeviceOperations {export interface DeviceHostReady {readonly nodePath: string;+ /**+ * Ends an agent-device session on the daemon that serves `deviceId`. Hosts+ * with a shared daemon provide it only while that daemon runs; hosts with a+ * daemon per device succeed when the device's daemon is gone. Cleanup never+ * starts a daemon or a device.+ */+ readonly releaseAgentSession?: (+ session: string,+ deviceId: string,+ ) => Effect.Effect<void, DeviceOperationError>;readonly hub: DeviceHubEndpoint;readonly devices: DeviceOperations;readonly run: (diff --git a/apps/server/src/device/DeviceMultiHost.test.ts b/apps/server/src/device/DeviceMultiHost.test.tsindex 7bbd8418de7..44115303e7b 100644--- a/apps/server/src/device/DeviceMultiHost.test.ts+++ b/apps/server/src/device/DeviceMultiHost.test.ts@@ -6,6 +6,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto";import * as Effect from "effect/Effect";import { HttpClient, HttpClientResponse } from "effect/http";import * as ServerSettings from "../serverSettings.ts";+import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";import * as DeviceHost from "./DeviceHost.ts";import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";import * as DeviceService from "./DeviceService.ts";@@ -16,19 +17,23 @@ it.effect("keeps hosts independent when serials collide and another host fails",Effect.succeed(HttpClientResponse.fromWeb(request,- Response.json({- simulators: [],- emulators: [- {- id: "emulator-5554",- name: "Pixel",- version: "36",- platform: "android",- booted: true,- physical: false,- },- ],- }),+ Response.json(+ request.url.endsWith("/rpc")+ ? { result: { ok: true } }+ : {+ simulators: [],+ emulators: [+ {+ id: "emulator-5554",+ name: "Pixel",+ version: "36",+ platform: "android",+ booted: true,+ physical: false,+ },+ ],+ },+ ),),),);@@ -50,6 +55,10 @@ it.effect("keeps hosts independent when serials collide and another host fails",androidAvailable: Effect.succeed(true),}),agentDevice: { baseUrl: `http://${id}`, token: "test", entryPath: "/agent-device" },+ releaseAgentSession: releaseAgentDeviceSession(http, {+ baseUrl: `http://${id}`,+ token: "test",+ }),run,helpers: { serveSimAxSettings: null, serveSimCli: null },};diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.tsindex a9ff957b919..59a1892f9b1 100644--- a/apps/server/src/device/DeviceService.test.ts+++ b/apps/server/src/device/DeviceService.test.ts@@ -36,7 +36,7 @@ import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";import { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";import * as DeviceService from "./DeviceService.ts";-import { agentDeviceSession } from "./AgentDeviceTarget.ts";+import { agentDeviceSession, releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));const decodeBootError = Schema.decodeUnknownSync(Schema.fromJsonString(DeviceBootError));@@ -52,26 +52,65 @@ const fixture = Effect.fn("fixture")(function* (| DeviceHost.AgentDeviceStartError,inspectError = false,installTool?: Parameters<typeof DeviceService.makeWithHosts>[3],- options: { readonly endsDevices?: boolean; readonly routesStreams?: boolean } = {},+ options: {+ readonly endsDevices?: boolean;+ readonly routesStreams?: boolean;+ readonly onClose?: Effect.Effect<"ok" | "missing" | "reject" | "http_error" | "malformed">;+ readonly onPlatformAvailability?: Effect.Effect<void>;+ } = {},) {const settings = yield* Ref.make(DEFAULT_SERVER_SETTINGS);const starts: string[] = [];const agentStarts: string[] = [];const agentStops: string[] = [];const requests: string[] = [];+ const closedSessions: unknown[] = [];const devices: Array<Omit<DeviceSummary, "hostId">> = [];const discoveryErrors = yield* Ref.make<Array<{ message: string; error?: string }>>([]);const androidAvailable = yield* Ref.make(true);const encoderResult = yield* Ref.make({ code: 0, stdout: " V....D libx264", stderr: "" });let booted = false;let shutDown = false;+ const connection = { online: true, kind: "local" as "local" | "ssh", failShutdown: false };const http = HttpClient.make((request) =>Effect.gen(function* () {requests.push(request.url);+ if (request.url === "http://agent.test/rpc") {+ if (request.body._tag !== "Uint8Array") throw new Error("Missing close body");+ const body = decodeJson(new TextDecoder().decode(request.body.body));+ closedSessions.push(body);+ expect(request.headers.authorization).toBe("Bearer test");+ const outcome = yield* options.onClose ?? Effect.succeed("ok");+ return HttpClientResponse.fromWeb(+ request,+ outcome === "missing"+ ? Response.json(+ {+ error: {+ code: -32000,+ message: "No active session",+ data: { code: "SESSION_NOT_FOUND" },+ },+ },+ { status: 404 },+ )+ : outcome === "http_error"+ ? new Response("Offline", { status: 503 })+ : outcome === "malformed"+ ? new Response("not JSON")+ : Response.json(+ outcome === "ok"+ ? { result: { ok: true } }+ : { error: { code: -32000, message: "offline" } },+ ),+ );+ }if (request.url.includes("/api/screenshot")) {return HttpClientResponse.fromWeb(request, new Response(new Uint8Array([137, 80, 78, 71])));}if (request.url.endsWith("/shutdown")) {+ if (connection.failShutdown)+ return HttpClientResponse.fromWeb(request, Response.json({ ok: false }));shutDown = true;booted = false;return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));@@ -153,9 +192,9 @@ const fixture = Effect.fn("fixture")(function* (: {}),id: LOCAL_DEVICE_HOST_ID,label: "This machine",- summary: Effect.succeed({+ summary: Effect.sync(() => ({id: LOCAL_DEVICE_HOST_ID,- kind: "local",+ kind: connection.kind,label: "Test server",platforms: [{ platform: "android", available: true },@@ -163,8 +202,11 @@ const fixture = Effect.fn("fixture")(function* (],hubInstalled: true,agentDeviceInstalled: false,- }),- platformAvailability: (platform) => Effect.succeed({ platform, available: true }),+ })),+ platformAvailability: (platform) =>+ (options.onPlatformAvailability ?? Effect.void).pipe(+ Effect.as({ platform, available: true }),+ ),ensureReady: (onPhase) =>Effect.gen(function* () {if (runtimeFailure && runtimeFailure._tag !== "AgentDeviceStartError")@@ -183,7 +225,21 @@ const fixture = Effect.fn("fixture")(function* (agentDevice: { baseUrl: "http://agent.test", token: "test", entryPath: "/agent" },};}),- current: Effect.succeed(null),+ current: Effect.sync(() =>+ connection.online+ ? {+ ...ready,+ ...(agentStarts.length > agentStops.length+ ? {+ releaseAgentSession: releaseAgentDeviceSession(http, {+ baseUrl: "http://agent.test",+ token: "test",+ }),+ }+ : {}),+ }+ : null,+ ),stopAgent: Effect.sync(() => {agentStops.push("stop");}),@@ -194,7 +250,7 @@ const fixture = Effect.fn("fixture")(function* (const service = yield* DeviceService.makeWithHosts(new Map([[host.id, host]]),undefined,- undefined,+ () => Effect.succeed("/host.json"),installTool,).pipe(Effect.provide(NodeCrypto.layer),@@ -232,6 +288,8 @@ const fixture = Effect.fn("fixture")(function* (agentStops,requests,settings,+ closedSessions,+ connection,devices,encoderResult,discoveryErrors,@@ -801,8 +859,8 @@ it.effect.each(["shutdown", "close"] as const)(operation === "shutdown" ? service.shutdown(input) : service.close({ threadId }),);expect((yield* PubSub.take(updates)).sessions).toEqual([]);- // list writes through the same state lock, so the retirement has committed.- expect((yield* service.list).sessions).toEqual([]);+ yield* service.refreshHosts;+ expect((yield* service.state).sessions).toEqual([]);yield* Effect.sync(() => retiring.interruptUnsafe());yield* Deferred.succeed(pauseBind.proceed, undefined);yield* Fiber.join(binding);@@ -1363,6 +1421,229 @@ it.effect("a failed tool update reports npm's exit code but not its output", ()),);+describe("agent session release on close", () => {+ const openClaim = (+ service: DeviceService.DeviceService["Service"],+ threadId: ThreadId,+ deviceId = "Pixel_API_35",+ ) => service.open({ threadId, deviceId, platform: "android" });++ it.effect("releases only the caller's session, keeps the device booted, and is idempotent", () =>+ Effect.gen(function* () {+ const { service, closedSessions, requests } = yield* fixture();+ yield* service.configure({ enabled: true, agentAccessEnabled: true });+ const threadId = ThreadId.make("closing");+ const other = ThreadId.make("other");+ const session = yield* openClaim(service, threadId);+ yield* openClaim(service, other, session.deviceId);+ yield* service.close({ threadId, deviceId: session.deviceId });+ yield* service.close({ threadId, deviceId: session.deviceId });+ const name = yield* agentDeviceSession(threadId, session.hostId, session.deviceId).pipe(+ Effect.provide(NodeCrypto.layer),+ );+ expect(closedSessions).toEqual([+ {+ jsonrpc: "2.0",+ id: name,+ method: "agent_device.command",+ params: { command: "close", session: name, positionals: [], flags: {} },+ },+ ]);+ const state = yield* service.state;+ expect(state.sessions.map((entry) => entry.threadId)).toEqual([other]);+ expect(state.devices.find((entry) => entry.id === session.deviceId)?.booted).toBe(true);+ expect(requests.some((url) => url.endsWith("/shutdown"))).toBe(false);+ }),+ );++ it.effect.each(["reject", "http_error", "malformed"] as const)(+ "retains retryable state on %s",+ (failure) =>+ Effect.gen(function* () {+ let fail = true;+ const { service, requests, closedSessions } = yield* fixture(+ Effect.void,+ undefined,+ false,+ undefined,+ false,+ undefined,+ { onClose: Effect.sync(() => (fail ? failure : "ok")) },+ );+ yield* service.configure({ enabled: true, agentAccessEnabled: true });+ const threadId = ThreadId.make("retry");+ yield* openClaim(service, threadId);+ const exit = yield* Effect.exit(service.close({ threadId, shutdown: true }));+ expect(Exit.isFailure(exit)).toBe(true);+ expect((yield* service.state).sessions).toHaveLength(1);+ expect(requests.some((url) => url.endsWith("/shutdown"))).toBe(false);+ fail = false;+ yield* service.close({ threadId });+ expect((yield* service.state).sessions).toHaveLength(0);+ expect(closedSessions).toHaveLength(2);+ }),+ );++ it.effect.each([false, true])("accepts a missing agent session, shutdown=%s", (shutdown) =>+ Effect.gen(function* () {+ const { service, requests } = yield* fixture(+ Effect.void,+ undefined,+ false,+ undefined,+ false,+ undefined,+ { onClose: Effect.succeed("missing") },+ );+ yield* service.configure({ enabled: true, agentAccessEnabled: true });+ const threadId = ThreadId.make("no-claim");+ yield* openClaim(service, threadId);+ yield* service.close({ threadId, shutdown });+ expect((yield* service.state).sessions).toHaveLength(0);+ expect(requests.some((url) => url.endsWith("/shutdown"))).toBe(shutdown);+ }),+ );++ it.effect("retries shutdown after the first attempt already released the agent session", () =>+ Effect.gen(function* () {+ let released = false;+ const { service, connection } = yield* fixture(+ Effect.void,+ undefined,+ false,+ undefined,+ false,+ undefined,+ {+ onClose: Effect.sync(() => {+ const result = released ? "missing" : "ok";+ released = true;+ return result;+ }),+ },+ );+ yield* service.configure({ enabled: true, agentAccessEnabled: true });+ const threadId = ThreadId.make("retry-shutdown");+ yield* openClaim(service, threadId);+ connection.failShutdown = true;+ expect(Exit.isFailure(yield* Effect.exit(service.close({ threadId, shutdown: true })))).toBe(+ true,+ );+ expect((yield* service.state).sessions).toHaveLength(1);+ connection.failShutdown = false;+ yield* service.close({ threadId, shutdown: true });+ expect((yield* service.state).sessions).toHaveLength(0);+ }),+ );++ it.effect("releases the post-boot agentTarget session for a cold Android AVD", () =>+ Effect.gen(function* () {+ const { service, closedSessions } = yield* fixture();+ yield* service.configure({ enabled: true, agentAccessEnabled: true });+ const threadId = ThreadId.make("cold-avd");+ const before = yield* service.agentTarget({+ threadId,+ hostId: "local",+ deviceId: "Pixel_API_35",+ });+ const session = yield* openClaim(service, threadId);+ const after = yield* service.agentTarget({+ threadId,+ hostId: session.hostId,+ deviceId: session.deviceId,+ });+ expect(session.deviceId).toBe("emulator-5554");+ expect(after.args[3]).not.toBe(before.args[3]);+ yield* service.close({ threadId });+ expect(closedSessions).toEqual([+ expect.objectContaining({ params: expect.objectContaining({ session: after.args[3] }) }),+ ]);+ }),+ );++ it.effect("retains an SSH record during reconnect and releases it on retry", () =>+ Effect.gen(function* () {+ const { service, connection, closedSessions, agentStarts } = yield* fixture();+ connection.kind = "ssh";+ yield* service.configure({ enabled: true, agentAccessEnabled: true });+ const threadId = ThreadId.make("ssh-reconnect");+ yield* openClaim(service, threadId);+ const starts = agentStarts.length;+ connection.online = false;+ expect(Exit.isFailure(yield* Effect.exit(service.close({ threadId })))).toBe(true);+ expect((yield* service.state).sessions).toHaveLength(1);+ expect(closedSessions).toHaveLength(0);+ expect(agentStarts).toHaveLength(starts);+ connection.online = true;+ yield* service.close({ threadId });+ expect((yield* service.state).sessions).toHaveLength(0);+ expect(closedSessions).toHaveLength(1);+ }),+ );+ it.effect("releases peer claims before a close shuts down", () =>+ Effect.gen(function* () {+ const { service, closedSessions } = yield* fixture();+ yield* service.configure({ enabled: true, agentAccessEnabled: true });+ const threadId = ThreadId.make("shutting-down");+ const other = ThreadId.make("peer");+ const session = yield* openClaim(service, threadId);+ yield* openClaim(service, other, session.deviceId);+ yield* service.close({ threadId, shutdown: true });+ expect((yield* service.state).sessions).toHaveLength(0);+ yield* service.close({ threadId: other });+ expect((yield* service.state).sessions).toHaveLength(0);+ const names = yield* Effect.forEach([threadId, other], (thread) =>+ agentDeviceSession(thread, session.hostId, session.deviceId),+ ).pipe(Effect.provide(NodeCrypto.layer));+ expect(+ closedSessions.map((body) => (body as { params: { session: string } }).params.session),+ ).toEqual(names);+ }),+ );++ it.effect("publishes a reopened session only after the old claim is released and removed", () =>+ Effect.gen(function* () {+ const entered = yield* Queue.unbounded<void>();+ const releasing = yield* Deferred.make<void>();+ const finish = yield* Deferred.make<void>();+ const { service } = yield* fixture(+ Effect.void,+ undefined,+ false,+ undefined,+ false,+ undefined,+ {+ onClose: Effect.gen(function* () {+ yield* Deferred.succeed(releasing, undefined);+ yield* Deferred.await(finish);+ return "ok" as const;+ }),+ onPlatformAvailability: Queue.offer(entered, undefined),+ },+ );+ yield* service.configure({ enabled: true, agentAccessEnabled: true });+ const threadId = ThreadId.make("reopen");+ const session = yield* openClaim(service, threadId);+ yield* Queue.take(entered);+ const publications = yield* service.subscribe;+ const closing = yield* service.close({ threadId }).pipe(Effect.forkChild);+ yield* Deferred.await(releasing);+ const opening = yield* openClaim(service, threadId, session.deviceId).pipe(Effect.forkChild);+ yield* Queue.take(entered);+ yield* Deferred.succeed(finish, undefined);+ yield* Fiber.join(closing);+ const reopened = yield* Fiber.join(opening);+ const published = (yield* PubSub.takeAll(publications))+ .map(({ sessions }) =>+ sessions.includes(session) ? "old" : sessions.includes(reopened) ? "reopened" : "none",+ )+ .filter((label, index, labels) => label !== labels[index - 1]);+ expect(published).toEqual(["none", "reopened"]);+ }).pipe(Effect.scoped),+ );+});+describe("locating a device id across hosts", () => {const threadId = ThreadId.make("thread-locate");const thisMachine = { id: LOCAL_DEVICE_HOST_ID, label: "This machine" };diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.tsindex b2ef41f148a..d91c9d8d0b5 100644--- a/apps/server/src/device/DeviceService.ts+++ b/apps/server/src/device/DeviceService.ts@@ -338,6 +338,26 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*}),);+ const releaseLaunchers = (sessions: ReadonlyArray<DeviceSession>) =>+ launcherLock.withPermit(+ Effect.forEach(+ sessions,+ (session) =>+ Effect.gen(function* () {+ const name = yield* agentDeviceSession(+ session.threadId,+ session.hostId,+ session.deviceId,+ ).pipe(Effect.provideService(Crypto.Crypto, crypto));+ const launcher = boundLaunchers.get(name);+ if (!launcher || hostSessionLaunchers.has(name) || !launchers?.release) return;+ yield* launchers.release(launcher);+ boundLaunchers.delete(name);+ }),+ { discard: true },+ ),+ );+// Uninterruptible so a committed retirement always prunes, even if its caller is cancelled.const publish = (update: (state: DeviceServiceState) => DeviceServiceState) =>SynchronizedRef.modifyEffect(stateRef, ({ state }) => {@@ -817,12 +837,18 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*},);+ const refreshAfterShutdown = (ready: DeviceReadiness) =>+ refresh(ready).pipe(+ Effect.catch((cause) =>+ Effect.logWarning("Device discovery unavailable after shutdown", { cause }),+ ),+ );+const shutdownDevice = Effect.fn("DeviceService.shutdownDevice")(function* (- hostId: DeviceHostId,+ ready: DeviceReadiness,deviceId: DeviceId,platform: DevicePlatform,) {- const ready = yield* readiness(hostId);yield* ready.devices.shutdown({ id: deviceId, platform });yield* publish((state) => ({...state,@@ -831,46 +857,76 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*? { ...device, booted: false }: device,),- sessions: state.sessions.filter(- (session) => !(session.hostId === ready.hostId && session.deviceId === deviceId),- ),}));- // Snapshot saves can stall discovery; refresh failure must not fail an accepted shutdown.- yield* refresh(ready).pipe(- Effect.catch((cause) =>- Effect.logWarning("Device discovery unavailable after shutdown", { cause }),- ),- );});const close: DeviceService["Service"]["close"] = Effect.fn("DeviceService.close")(function* (input) {- const { state } = yield* SynchronizedRef.get(stateRef);- const closing = state.sessions.filter(- (session) =>- session.threadId === input.threadId &&- (input.hostId === undefined || session.hostId === input.hostId) &&- (input.deviceId === undefined || session.deviceId === input.deviceId),+ // Open publishes under the same lock; an old close must not release a reopened claim.+ const closing = yield* lifecycleLock.withPermit(+ Effect.gen(function* () {+ const { state } = yield* SynchronizedRef.get(stateRef);+ const closing = state.sessions.filter(+ (session) =>+ session.threadId === input.threadId &&+ (input.hostId === undefined || session.hostId === input.hostId) &&+ (input.deviceId === undefined || session.deviceId === input.deviceId),+ );+ const ending = input.shutdown+ ? state.sessions.filter((session) =>+ closing.some(+ (closed) =>+ closed.hostId === session.hostId && closed.deviceId === session.deviceId,+ ),+ )+ : closing;+ for (const session of ending) {+ const host = yield* resolveHost(session.hostId);+ const ready = yield* host.current;+ // A lost SSH tunnel does not establish that the remote daemon stopped.+ if (!ready && (yield* host.summary).kind === "ssh")+ return yield* new DeviceHostUnavailableError({+ hostId: session.hostId,+ hostLabel: host.label,+ reason: "Device host is reconnecting. Retry close after it reconnects.",+ });+ if (ready?.releaseAgentSession) {+ const name = yield* agentDeviceSession(+ session.threadId,+ session.hostId,+ session.deviceId,+ ).pipe(Effect.provideService(Crypto.Crypto, crypto));+ yield* ready.releaseAgentSession(name, session.deviceId);+ }+ }+ if (input.shutdown) yield* releaseLaunchers(ending);+ if (input.shutdown) {+ for (const session of closing) {+ const ready = yield* currentReadiness(session.hostId);+ if (!ready)+ return yield* new DeviceHostUnavailableError({+ hostId: session.hostId,+ reason: "Device host is not running. Reconnect before retrying close.",+ });+ yield* shutdownDevice(ready, session.deviceId, session.platform);+ }+ }+ yield* publish((current) => ({+ ...current,+ sessions: current.sessions.filter((session) => !ending.includes(session)),+ }));+ return closing;+ }),);- if (closing.length === 0) return;- // Powering off ends every session on the device, so all of them retire, and release, while it is on.- const ending = (session: DeviceSession) =>- closing.includes(session) ||- (input.shutdown === true &&- closing.some(- (closed) => closed.hostId === session.hostId && closed.deviceId === session.deviceId,- ));- yield* publish((current) => ({- ...current,- sessions: current.sessions.filter((session) => !ending(session)),- }));- if (input.shutdown) {+ if (input.shutdown)yield* Effect.forEach(closing,- (session) => shutdownDevice(session.hostId, session.deviceId, session.platform),+ (session) =>+ currentReadiness(session.hostId).pipe(+ Effect.flatMap((ready) => (ready ? refreshAfterShutdown(ready) : Effect.void)),+ ),{ discard: true },);- }},);@@ -885,7 +941,9 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*(session) => !(session.hostId === host.id && session.deviceId === input.deviceId),),}));- yield* shutdownDevice(host.id, input.deviceId, input.platform);+ const ready = yield* readiness(host.id);+ yield* shutdownDevice(ready, input.deviceId, input.platform);+ yield* refreshAfterShutdown(ready);},);diff --git a/apps/server/src/device/EasDeviceHost.test.ts b/apps/server/src/device/EasDeviceHost.test.tsindex 62a6a0c247a..b5825d3f973 100644--- a/apps/server/src/device/EasDeviceHost.test.ts+++ b/apps/server/src/device/EasDeviceHost.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "@effect/vitest";+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";import * as NodeServices from "@effect/platform-node/NodeServices";-import type { EasDeviceHostConfig } from "@t3tools/contracts";+import { type EasDeviceHostConfig, ThreadId } from "@t3tools/contracts";import * as HostProcess from "@t3tools/shared/HostProcess";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";@@ -15,6 +16,8 @@ import { HttpClient, HttpClientResponse } from "effect/http";import * as ServerConfig from "../config.ts";import * as ProcessRunner from "../processRunner.ts";+import * as ServerSettings from "../serverSettings.ts";+import * as DeviceService from "./DeviceService.ts";import * as EasDeviceHost from "./EasDeviceHost.ts";const APP_ID = "d763fcb8-d37c-41ea-a773-b54a0ab4a454";@@ -57,9 +60,12 @@ const fakeExpo = (readonly activeIncludesCreated?: boolean;readonly failPreview?: boolean;readonly omitCreatedFromActive?: boolean;+ /** The session's agent-device daemon answers with a server error. */+ readonly failAgent?: () => boolean;} = {},) => {const calls: Array<{ operation: string; variables: Record<string, unknown> }> = [];+ const releases: Array<unknown> = [];let created = 0;let createdName = "";const previews: string[] = [];@@ -91,6 +97,18 @@ const fakeExpo = (),);}+ if (url.origin === "https://agent.test") {+ expect(request.headers.authorization).toBe("Bearer agent-token");+ if (request.body._tag === "Uint8Array") {+ const rpc = JSON.parse(new TextDecoder().decode(request.body.body)) as {+ params: { command: string; session: string };+ };+ if (rpc.params.command === "close") releases.push(rpc.params.session);+ }+ if (options.failAgent?.())+ return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));+ return HttpClientResponse.fromWeb(request, Response.json({ result: { ok: true } }));+ }const body =request.body._tag === "Uint8Array"? (JSON.parse(new TextDecoder().decode(request.body.body)) as {@@ -207,7 +225,7 @@ const fakeExpo = (const allowCreate = () => {createFails = false;};- return { http, named, stopped, allowPreview, allowCreate, previews };+ return { http, named, stopped, allowPreview, allowCreate, releases, previews };};const layer = Layer.mergeAll(@@ -566,4 +584,63 @@ describe("EAS Simulator host", () => {]);}).pipe(Effect.scoped, Effect.provide(layer)),);++ it.effect("releases each thread's agent session on close and keeps the session running", () =>+ Effect.gen(function* () {+ let agentFails = false;+ const expo = fakeExpo({ failAgent: () => agentFails });+ const host = yield* makeHost(expo, config(), yield* Scope.make());+ const service = yield* DeviceService.makeWithHosts(new Map([["eas", host]]), undefined, () =>+ Effect.succeed("/eas-agent.json"),+ );+ const first = ThreadId.make("first");+ const second = ThreadId.make("second");+ const opened = yield* service.open({+ threadId: first,+ hostId: "eas",+ deviceId: "eas-ios",+ platform: "ios",+ });+ expect(opened.deviceId).toBe("session-1");+ yield* service.open({+ threadId: second,+ hostId: "eas",+ deviceId: opened.deviceId,+ platform: "ios",+ });+ const sessionOf = (threadId: ThreadId) =>+ service+ .agentTarget({ threadId, hostId: "eas", deviceId: opened.deviceId })+ .pipe(Effect.map((target) => target.args[3]));+ const firstSession = yield* sessionOf(first);+ const secondSession = yield* sessionOf(second);++ yield* service.close({ threadId: first });+ expect(expo.releases).toEqual([firstSession]);+ expect((yield* service.state).sessions.map((entry) => entry.threadId)).toEqual([second]);++ agentFails = true;+ const failed = yield* Effect.exit(service.close({ threadId: second, shutdown: false }));+ expect(Exit.isFailure(failed)).toBe(true);+ expect((yield* service.state).sessions.map((entry) => entry.threadId)).toEqual([second]);++ agentFails = false;+ yield* service.close({ threadId: second, shutdown: false });+ expect(expo.releases).toEqual([firstSession, secondSession, secondSession]);+ expect((yield* service.state).sessions).toEqual([]);+ expect(expo.stopped()).not.toContain("session-1");+ expect(+ (yield* service.state).devices.find((device) => device.id === "session-1")?.booted,+ ).toBe(true);+ }).pipe(+ Effect.scoped,+ Effect.provide(+ Layer.mergeAll(+ layer,+ NodeCrypto.layer,+ ServerSettings.layerTest({ enableDeviceSupport: true, enableAgentDeviceAccess: true }),+ ),+ ),+ ),+ );});diff --git a/apps/server/src/device/EasDeviceHost.ts b/apps/server/src/device/EasDeviceHost.tsindex a1137fe5156..e82638dbd76 100644--- a/apps/server/src/device/EasDeviceHost.ts+++ b/apps/server/src/device/EasDeviceHost.ts@@ -32,6 +32,7 @@ import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";import * as HostProcess from "@t3tools/shared/HostProcess";import * as ServerConfig from "../config.ts";+import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";import * as DeviceHost from "./DeviceHost.ts";import { findEasProjectId } from "./easProjectId.ts";import { type ExpoApi, makeExpoApi, resolveExpoCredential } from "./ExpoApi.ts";@@ -827,6 +828,12 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevicehub: { origin: "https://api.expo.dev" },devices,upstream,+ // Each session runs its own daemon, so one that has ended holds no agent sessions.+ releaseAgentSession: (session, deviceId) =>+ Option.match(sessionFor(deviceId), {+ onNone: () => Effect.void,+ onSome: (running) => releaseAgentDeviceSession(http, running.agent)(session),+ }),// Device settings run simctl on the simulator's own machine, which EAS does not expose.run: () =>Effect.succeed({diff --git a/apps/server/src/device/LocalDeviceHost.test.ts b/apps/server/src/device/LocalDeviceHost.test.tsindex bffd912a398..57468c98878 100644--- a/apps/server/src/device/LocalDeviceHost.test.ts+++ b/apps/server/src/device/LocalDeviceHost.test.ts@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Path from "effect/Path";+import * as PlatformError from "effect/PlatformError";import * as FileSystem from "effect/FileSystem";import * as Sink from "effect/Sink";import * as Stream from "effect/Stream";@@ -42,6 +43,7 @@ const agentFixture = Effect.fn("agentFixture")(function* (const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-agent-start-" });+ const hub = { running: true, spawnFails: false };const stateDir = agentDeviceStateDir(path, path.join(baseDir, "userdata"));for (const [name, version, entry] of [["expo-device-hub", DEVICE_HUB_VERSION, "dist/server/cli.mjs"],@@ -61,21 +63,30 @@ const agentFixture = Effect.fn("agentFixture")(function* (Effect.provideService(ChildProcessSpawner.ChildProcessSpawner,ChildProcessSpawner.make(() =>- Effect.succeed(- ChildProcessSpawner.makeHandle({- pid: ChildProcessSpawner.ProcessId(123),- stdout: Stream.empty,- stderr: Stream.empty,- all: Stream.empty,- exitCode: Effect.never,- isRunning: Effect.succeed(true),- kill: () => Effect.void,- stdin: Sink.drain,- getInputFd: () => Sink.drain,- getOutputFd: () => Stream.empty,- unref: Effect.succeed(Effect.void),- }),- ),+ hub.spawnFails+ ? Effect.fail(+ PlatformError.systemError({+ _tag: "NotFound",+ module: "ChildProcess",+ method: "spawn",+ description: "Hub entry missing",+ }),+ )+ : Effect.succeed(+ ChildProcessSpawner.makeHandle({+ pid: ChildProcessSpawner.ProcessId(123),+ stdout: Stream.empty,+ stderr: Stream.empty,+ all: Stream.empty,+ exitCode: Effect.never,+ isRunning: Effect.sync(() => hub.running),+ kill: () => Effect.void,+ stdin: Sink.drain,+ getInputFd: () => Sink.drain,+ getOutputFd: () => Stream.empty,+ unref: Effect.succeed(Effect.void),+ }),+ ),),),Effect.provideService(ProcessRunner.ProcessRunner, {@@ -92,7 +103,7 @@ const agentFixture = Effect.fn("agentFixture")(function* (),);yield* host.ensureReady(() => Effect.void);- return { host, fs, stateDir };+ return { host, fs, stateDir, hub };});describe("AgentDevice startup", () => {@@ -196,9 +207,32 @@ describe("AgentDevice startup", () => {expect((yield* host.ensureAgentReady(() => Effect.void)).agentDevice).toEqual(ready.agentDevice,);+ expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");expect(attempts).toBe(1);}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),);++ it.effect("keeps releasing agent sessions while a dead hub fails to restart and after", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const { host, hub } = yield* agentFixture((stateDir) =>+ fs+ .writeFileString(+ `${stateDir}/daemon.json`,+ JSON.stringify({ httpPort: 12345, token: "test-token" }),+ )+ .pipe(Effect.orDie, Effect.as(processOutput(0))),+ );+ yield* host.ensureAgentReady(() => Effect.void);+ hub.running = false;+ hub.spawnFails = true;+ expect((yield* host.ensureReady(() => Effect.void).pipe(Effect.result))._tag).toBe("Failure");+ expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");+ hub.spawnFails = false;+ yield* host.ensureReady(() => Effect.void);+ expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );});const diagnose = (diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.tsindex 051803bd496..34250bc199f 100644--- a/apps/server/src/device/LocalDeviceHost.ts+++ b/apps/server/src/device/LocalDeviceHost.ts@@ -36,6 +36,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";import * as ServerConfig from "../config.ts";import * as ProcessRunner from "../processRunner.ts";+import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";import * as DeviceHost from "./DeviceHost.ts";import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";import {@@ -650,10 +651,11 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {onPhase: (phase: "installing" | "starting", detail?: string) => Effect.Effect<void>,): Effect.fn.Return<RunningHost, DeviceHost.DeviceHostError | NodeRuntimeUnavailableError> {const running = yield* Ref.get(runningRef);+ // A dead hub's record stays until a replacement is published: the agent+ // daemon outlives the hub, and close needs its endpoint if the restart fails.if (running) {const alive = yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false));if (alive) return running;- yield* Ref.set(runningRef, null);}const nodePath = yield* resolveNodeExecutable("Local device support", hostEnvironment).pipe(Effect.provideService(FileSystem.FileSystem, fs),@@ -696,7 +698,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {]);const next: RunningHost = {hub,- agentDevice: null,+ agentDevice: running?.agentDevice ?? null,helpers: {serveSimAxSettings: axExists ? candidate.serveSimAxSettings : null,serveSimCli: cliExists ? candidate.serveSimCli : null,@@ -821,6 +823,9 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {nodePath: running.hub.nodePath,run,helpers: running.helpers,+ ...(running.agentDevice+ ? { releaseAgentSession: releaseAgentDeviceSession(httpClient, running.agentDevice) }+ : {}),});const current: DeviceHost.DeviceHost["Service"]["current"] = Ref.get(runningRef).pipe(diff --git a/apps/server/src/device/SshDeviceHost.test.ts b/apps/server/src/device/SshDeviceHost.test.tsindex cde68d1b50c..193df164c30 100644--- a/apps/server/src/device/SshDeviceHost.test.ts+++ b/apps/server/src/device/SshDeviceHost.test.ts@@ -26,6 +26,7 @@ it.effect("preserves installed status after probes and cleans failed agent activlet forwards = 0;let failForward = true;let rejectConfig = true;+ const releases: Array<string | undefined> = [];const spawner = ChildProcessSpawner.make((command) =>Effect.gen(function* () {if (command._tag !== "StandardCommand") return yield* Effect.die("Unexpected command");@@ -118,7 +119,12 @@ it.effect("preserves installed status after probes and cleans failed agent activEffect.provideService(HttpClient.HttpClient,HttpClient.make((request) =>- Effect.succeed(HttpClientResponse.fromWeb(request, new Response("ok"))),+ Effect.sync(() => {+ if (!request.url.endsWith("/rpc"))+ return HttpClientResponse.fromWeb(request, new Response("ok"));+ releases.push(request.headers.authorization);+ return HttpClientResponse.fromWeb(request, Response.json({ result: { ok: true } }));+ }),),),);@@ -156,6 +162,10 @@ it.effect("preserves installed status after probes and cleans failed agent activyield* host.ensureAgentReady(() => Effect.void);yield* host.platformAvailability("ios");expect((yield* host.summary).agentDeviceInstalled).toBe(true);+ // Close releases agent sessions through the forwarded daemon.+ const agentReady = yield* host.current;+ yield* agentReady!.releaseAgentSession!("t3-session", "device");+ expect(releases).toEqual(["Bearer fixture"]);yield* host.stopAgent;expect(forwards).toBe(1);const multiplexingOff = ["ControlMaster=no", "ControlPath=none", "ControlPersist=no"];diff --git a/apps/server/src/device/SshDeviceHost.ts b/apps/server/src/device/SshDeviceHost.tsindex d7324d515b0..1eb0b713983 100644--- a/apps/server/src/device/SshDeviceHost.ts+++ b/apps/server/src/device/SshDeviceHost.ts@@ -22,6 +22,7 @@ import * as HttpClient from "effect/http/HttpClient";import * as ChildProcess from "effect/process/ChildProcess";import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";import * as ServerConfig from "../config.ts";+import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";import * as DeviceHost from "./DeviceHost.ts";import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";import { quoteRemoteArg, remoteDeviceEnvironment, remoteDeviceScript } from "./sshDeviceScript.ts";@@ -351,7 +352,9 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (}).pipe(Effect.provideService(HttpClient.HttpClient, http));}if (next.agentDevice) yield* onReady({ ...next, agentDevice: next.agentDevice });- ready = next;+ ready = next.agentDevice+ ? { ...next, releaseAgentSession: releaseAgentDeviceSession(http, next.agentDevice) }+ : next;yield* onStatus("ready");// Reconnect also repairs helpers that died while SSH itself stayed connected.const unhealthy = Effect.gen(function* () {diff --git a/apps/server/src/device/sshDeviceScript.test.ts b/apps/server/src/device/sshDeviceScript.test.tsindex e3af344e637..d855320d310 100644--- a/apps/server/src/device/sshDeviceScript.test.ts+++ b/apps/server/src/device/sshDeviceScript.test.ts@@ -7,7 +7,7 @@ import * as NodeFSP from "node:fs/promises";import * as NodeOS from "node:os";import * as NodePath from "node:path";import * as NodeUtil from "node:util";-import { quoteRemoteArg, remoteDeviceEnvironment } from "./sshDeviceScript.ts";+import { quoteRemoteArg, remoteDeviceEnvironment, remoteDeviceScript } from "./sshDeviceScript.ts";const exec = NodeUtil.promisify(NodeChildProcess.execFile);@@ -45,3 +45,90 @@ it.effect("preserves shell metacharacters and newlines in remote arguments", ()});}),);++it.effect("stops a daemon left for its owner when starting without agent tools", () =>+ Effect.gen(function* () {+ if ((yield* HostProcess.Platform) === "win32") return;+ yield* Effect.promise(async () => {+ const home = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-ssh-start-"));+ try {+ const state = NodePath.join(home, ".t3/device/hosts/owner");+ const daemonFile = NodePath.join(state, "daemon.json");+ const calls = NodePath.join(home, "calls");+ const failMarker = NodePath.join(home, "fail-stop");+ const entry = NodePath.join(home, "agent-device.mjs");+ await NodeFSP.mkdir(NodePath.join(home, "bin"));+ await NodeFSP.mkdir(state, { recursive: true });+ await NodeFSP.writeFile(+ entry,+ `import * as fs from "node:fs";+fs.appendFileSync(${JSON.stringify(calls)}, process.argv.slice(2).join(" ") + "\\n");+if (fs.existsSync(${JSON.stringify(failMarker)})) process.exitCode = 1;`,+ );+ await NodeFSP.writeFile(+ NodePath.join(state, "agent.json"),+ JSON.stringify({ entryPath: entry }),+ );+ await NodeFSP.writeFile(daemonFile, JSON.stringify({ httpPort: 1, token: "claims" }));+ // An empty PATH leaves no platforms, so the script ends right after the daemon check.+ const start = () =>+ NodeChildProcess.spawnSync(process.execPath, [], {+ input: remoteDeviceScript("owner", "start"),+ env: { HOME: home, PATH: NodePath.join(home, "bin") },+ encoding: "utf8",+ });+ await NodeFSP.writeFile(failMarker, "");+ expect(start().stderr).toContain("Could not stop the agent-device daemon");+ expect(await NodeFSP.readFile(daemonFile, "utf8")).toContain("claims");+ await NodeFSP.rm(failMarker);+ expect(start().stderr).toContain("Android SDK missing");+ await expect(NodeFSP.access(daemonFile)).rejects.toThrow();+ expect(await NodeFSP.readFile(calls, "utf8")).toBe(+ `daemon stop --state-dir ${state}\ndaemon stop --state-dir ${state}\n`,+ );+ } finally {+ await NodeFSP.rm(home, { recursive: true, force: true });+ }+ });+ }),+);++it.effect("keeps a daemon record its missing agent CLI cannot stop", () =>+ Effect.gen(function* () {+ if ((yield* HostProcess.Platform) === "win32") return;+ yield* Effect.promise(async () => {+ const home = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-ssh-start-"));+ try {+ const state = NodePath.join(home, ".t3/device/hosts/owner");+ const daemonFile = NodePath.join(state, "daemon.json");+ await NodeFSP.mkdir(NodePath.join(home, "bin"));+ await NodeFSP.mkdir(state, { recursive: true });+ await NodeFSP.writeFile(+ NodePath.join(state, "agent.json"),+ JSON.stringify({ entryPath: NodePath.join(home, "missing/agent-device.mjs") }),+ );+ const start = async (pid: number) => {+ await NodeFSP.writeFile(+ daemonFile,+ JSON.stringify({ pid, httpPort: 1, token: "claims" }),+ );+ return NodeChildProcess.spawnSync(process.execPath, [], {+ input: remoteDeviceScript("owner", "start"),+ env: { HOME: home, PATH: NodePath.join(home, "bin") },+ encoding: "utf8",+ });+ };+ // This test process stands in for a daemon that is still running.+ expect((await start(process.pid)).stderr).toContain(+ "Could not stop the agent-device daemon",+ );+ expect(await NodeFSP.readFile(daemonFile, "utf8")).toContain("claims");+ const exited = NodeChildProcess.spawnSync(process.execPath, ["-e", ""]).pid;+ expect((await start(exited)).stderr).toContain("Android SDK missing");+ await expect(NodeFSP.access(daemonFile)).rejects.toThrow();+ } finally {+ await NodeFSP.rm(home, { recursive: true, force: true });+ }+ });+ }),+);diff --git a/apps/server/src/device/sshDeviceScript.ts b/apps/server/src/device/sshDeviceScript.tsindex ffe8097bae3..2e3e895293f 100644--- a/apps/server/src/device/sshDeviceScript.ts+++ b/apps/server/src/device/sshDeviceScript.ts@@ -151,16 +151,29 @@ async function install(name, version, entry) {const hubFile = path.join(state, 'hub.json');const daemonFile = path.join(state, 'daemon.json');const agentFile = path.join(state, 'agent.json');+ const stopAgent = () => {+ const entry = read(agentFile)?.entryPath || path.join(root, 'tools', 'agent-device@' + agentVersion, 'node_modules', 'agent-device', 'bin', 'agent-device.mjs');+ if (fs.existsSync(entry)) return run(process.execPath, [entry, 'daemon', 'stop', '--state-dir', state]).status === 0;+ // A running daemon outlives its deleted CLI, so without one only a recorded pid that is gone counts as stopped.+ const pid = read(daemonFile)?.pid;+ return Number.isSafeInteger(pid) && pid > 0 && !maintenanceAlive(pid);+ };if (mode === 'stop' || mode === 'stop-agent') {const hub = read(hubFile);if (mode === 'stop' && hub && hub.owner === owner) {stopHub(hub);fs.rmSync(hubFile, { force: true });}- const entry = read(agentFile)?.entryPath || path.join(root, 'tools', 'agent-device@' + agentVersion, 'node_modules', 'agent-device', 'bin', 'agent-device.mjs');- if (fs.existsSync(entry)) run(process.execPath, [entry, 'daemon', 'stop', '--state-dir', state]);+ stopAgent();return;}+ // A start without agent tools means the server holds no claims, so a daemon still here is+ // orphaned. Agent access was turned off while the tunnel was down, or a server crashed.+ // Close skips the release when start returns no endpoint, so the claims must end here.+ if (mode === 'start' && read(daemonFile)) {+ if (!stopAgent()) throw Error('Could not stop the agent-device daemon in ' + state);+ fs.rmSync(daemonFile, { force: true });+ }if (!ios && !android) throw Error(platforms.map(p => p.reason).join(' '));fs.mkdirSync(state, { recursive: true, mode: 0o700 });const hubEntry = await install('expo-device-hub', hubVersion, 'dist/server/cli.mjs');