The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 12:00 UTC
fix(server): release agent-device sessions when device_close runs (#21478)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net>
Victor Vogel committed
Oct 30, 2026 at 15:26 UTC
a17ab2e98438ea4507cd5d86bd978090ed3e2fcc
13 files changed
+711
-81
apps/server/src/device/AgentDeviceTarget.ts
+36
@@ -1,9 +1,12 @@
1
+import { DeviceOperationError } from "@t3tools/contracts";
2
import * as Crypto from "effect/Crypto";
3
+import * as Duration from "effect/Duration";
4
import * as Effect from "effect/Effect";
5
import * as Hex from "effect/encoding/Hex";
6
import * as Schema from "effect/Schema";
7
import * as FileSystem from "effect/FileSystem";
8
import * as Path from "effect/Path";
9
+import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
10
11
import type { AgentDaemonEndpoint } from "./DeviceHost.ts";
12
@@ -62,3 +65,36 @@ export const writeAgentDeviceConfig = Effect.fn("AgentDeviceTarget.writeConfig")
65
yield* fs.rename(temporary, file);
66
}).pipe(Effect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.ignore)));
67
});
68
+
69
+const AgentCloseResult = Schema.Union([
70
+ Schema.Struct({ result: Schema.Struct({ ok: Schema.Literal(true) }) }),
71
+ Schema.Struct({
72
+ error: Schema.Struct({
73
+ data: Schema.Struct({ code: Schema.Literal("SESSION_NOT_FOUND") }),
74
+ }),
75
+ }),
76
+]);
77
+
78
+/** Ends an agent-device session on a running daemon; an already-released session succeeds. */
79
+export const releaseAgentDeviceSession =
80
+ (http: HttpClient.HttpClient, endpoint: AgentDaemonEndpoint) => (session: string) =>
81
+ HttpClientRequest.post(`${endpoint.baseUrl}/rpc`).pipe(
82
+ HttpClientRequest.bearerToken(endpoint.token),
83
+ HttpClientRequest.bodyJson({
84
+ jsonrpc: "2.0",
85
+ id: session,
86
+ method: "agent_device.command",
87
+ params: { command: "close", session, positionals: [], flags: {} },
88
+ }),
89
+ Effect.flatMap((request) => http.pipe(HttpClient.withScope).execute(request)),
90
+ // agent-device reports an already-released session as HTTP 404.
91
+ Effect.filterOrElse((response) => response.status === 404, HttpClientResponse.filterStatusOk),
92
+ Effect.flatMap(HttpClientResponse.schemaBodyJson(AgentCloseResult)),
93
+ Effect.scoped,
94
+ Effect.timeout(Duration.seconds(15)),
95
+ Effect.asVoid,
96
+ Effect.mapError(
97
+ (cause) =>
98
+ new DeviceOperationError({ operation: "close", reason: "request_failed", cause }),
99
+ ),
100
+ );
apps/server/src/device/DeviceHost.ts
+10
@@ -145,6 +145,16 @@ export interface DeviceOperations {
145
146
export interface DeviceHostReady {
147
readonly nodePath: string;
148
+ /**
149
+ * Ends an agent-device session on the daemon that serves `deviceId`. Hosts
150
+ * with a shared daemon provide it only while that daemon runs; hosts with a
151
+ * daemon per device succeed when the device's daemon is gone. Cleanup never
152
+ * starts a daemon or a device.
153
+ */
154
+ readonly releaseAgentSession?: (
155
+ session: string,
156
+ deviceId: string,
157
+ ) => Effect.Effect<void, DeviceOperationError>;
158
readonly hub: DeviceHubEndpoint;
159
readonly devices: DeviceOperations;
160
readonly run: (
apps/server/src/device/DeviceMultiHost.test.ts
+22
-13
@@ -6,6 +6,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
6
import * as Effect from "effect/Effect";
7
import { HttpClient, HttpClientResponse } from "effect/http";
8
import * as ServerSettings from "../serverSettings.ts";
9
+import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";
10
import * as DeviceHost from "./DeviceHost.ts";
11
import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";
12
import * as DeviceService from "./DeviceService.ts";
@@ -16,19 +17,23 @@ it.effect("keeps hosts independent when serials collide and another host fails",
17
Effect.succeed(
18
HttpClientResponse.fromWeb(
19
request,
19
- Response.json({
20
- simulators: [],
21
- emulators: [
22
- {
23
- id: "emulator-5554",
24
- name: "Pixel",
25
- version: "36",
26
- platform: "android",
27
- booted: true,
28
- physical: false,
29
- },
30
- ],
31
- }),
20
+ Response.json(
21
+ request.url.endsWith("/rpc")
22
+ ? { result: { ok: true } }
23
+ : {
24
+ simulators: [],
25
+ emulators: [
26
+ {
27
+ id: "emulator-5554",
28
+ name: "Pixel",
29
+ version: "36",
30
+ platform: "android",
31
+ booted: true,
32
+ physical: false,
33
+ },
34
+ ],
35
+ },
36
+ ),
37
),
38
),
39
);
@@ -50,6 +55,10 @@ it.effect("keeps hosts independent when serials collide and another host fails",
55
androidAvailable: Effect.succeed(true),
56
}),
57
agentDevice: { baseUrl: `http://${id}`, token: "test", entryPath: "/agent-device" },
58
+ releaseAgentSession: releaseAgentDeviceSession(http, {
59
+ baseUrl: `http://${id}`,
60
+ token: "test",
61
+ }),
62
run,
63
helpers: { serveSimAxSettings: null, serveSimCli: null },
64
};
apps/server/src/device/DeviceService.test.ts
+291
-10
@@ -36,7 +36,7 @@ import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";
36
import { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
37
38
import * as DeviceService from "./DeviceService.ts";
39
-import { agentDeviceSession } from "./AgentDeviceTarget.ts";
39
+import { agentDeviceSession, releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";
40
41
const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
42
const decodeBootError = Schema.decodeUnknownSync(Schema.fromJsonString(DeviceBootError));
@@ -52,26 +52,65 @@ const fixture = Effect.fn("fixture")(function* (
52
| DeviceHost.AgentDeviceStartError,
53
inspectError = false,
54
installTool?: Parameters<typeof DeviceService.makeWithHosts>[3],
55
- options: { readonly endsDevices?: boolean; readonly routesStreams?: boolean } = {},
55
+ options: {
56
+ readonly endsDevices?: boolean;
57
+ readonly routesStreams?: boolean;
58
+ readonly onClose?: Effect.Effect<"ok" | "missing" | "reject" | "http_error" | "malformed">;
59
+ readonly onPlatformAvailability?: Effect.Effect<void>;
60
+ } = {},
61
) {
62
const settings = yield* Ref.make(DEFAULT_SERVER_SETTINGS);
63
const starts: string[] = [];
64
const agentStarts: string[] = [];
65
const agentStops: string[] = [];
66
const requests: string[] = [];
67
+ const closedSessions: unknown[] = [];
68
const devices: Array<Omit<DeviceSummary, "hostId">> = [];
69
const discoveryErrors = yield* Ref.make<Array<{ message: string; error?: string }>>([]);
70
const androidAvailable = yield* Ref.make(true);
71
const encoderResult = yield* Ref.make({ code: 0, stdout: " V....D libx264", stderr: "" });
72
let booted = false;
73
let shutDown = false;
74
+ const connection = { online: true, kind: "local" as "local" | "ssh", failShutdown: false };
75
const http = HttpClient.make((request) =>
76
Effect.gen(function* () {
77
requests.push(request.url);
78
+ if (request.url === "http://agent.test/rpc") {
79
+ if (request.body._tag !== "Uint8Array") throw new Error("Missing close body");
80
+ const body = decodeJson(new TextDecoder().decode(request.body.body));
81
+ closedSessions.push(body);
82
+ expect(request.headers.authorization).toBe("Bearer test");
83
+ const outcome = yield* options.onClose ?? Effect.succeed("ok");
84
+ return HttpClientResponse.fromWeb(
85
+ request,
86
+ outcome === "missing"
87
+ ? Response.json(
88
+ {
89
+ error: {
90
+ code: -32000,
91
+ message: "No active session",
92
+ data: { code: "SESSION_NOT_FOUND" },
93
+ },
94
+ },
95
+ { status: 404 },
96
+ )
97
+ : outcome === "http_error"
98
+ ? new Response("Offline", { status: 503 })
99
+ : outcome === "malformed"
100
+ ? new Response("not JSON")
101
+ : Response.json(
102
+ outcome === "ok"
103
+ ? { result: { ok: true } }
104
+ : { error: { code: -32000, message: "offline" } },
105
+ ),
106
+ );
107
+ }
108
if (request.url.includes("/api/screenshot")) {
109
return HttpClientResponse.fromWeb(request, new Response(new Uint8Array([137, 80, 78, 71])));
110
}
111
if (request.url.endsWith("/shutdown")) {
112
+ if (connection.failShutdown)
113
+ return HttpClientResponse.fromWeb(request, Response.json({ ok: false }));
114
shutDown = true;
115
booted = false;
116
return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
@@ -153,9 +192,9 @@ const fixture = Effect.fn("fixture")(function* (
192
: {}),
193
id: LOCAL_DEVICE_HOST_ID,
194
label: "This machine",
156
- summary: Effect.succeed({
195
+ summary: Effect.sync(() => ({
196
id: LOCAL_DEVICE_HOST_ID,
158
- kind: "local",
197
+ kind: connection.kind,
198
label: "Test server",
199
platforms: [
200
{ platform: "android", available: true },
@@ -163,8 +202,11 @@ const fixture = Effect.fn("fixture")(function* (
202
],
203
hubInstalled: true,
204
agentDeviceInstalled: false,
166
- }),
167
- platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
205
+ })),
206
+ platformAvailability: (platform) =>
207
+ (options.onPlatformAvailability ?? Effect.void).pipe(
208
+ Effect.as({ platform, available: true }),
209
+ ),
210
ensureReady: (onPhase) =>
211
Effect.gen(function* () {
212
if (runtimeFailure && runtimeFailure._tag !== "AgentDeviceStartError")
@@ -183,7 +225,21 @@ const fixture = Effect.fn("fixture")(function* (
225
agentDevice: { baseUrl: "http://agent.test", token: "test", entryPath: "/agent" },
226
};
227
}),
186
- current: Effect.succeed(null),
228
+ current: Effect.sync(() =>
229
+ connection.online
230
+ ? {
231
+ ...ready,
232
+ ...(agentStarts.length > agentStops.length
233
+ ? {
234
+ releaseAgentSession: releaseAgentDeviceSession(http, {
235
+ baseUrl: "http://agent.test",
236
+ token: "test",
237
+ }),
238
+ }
239
+ : {}),
240
+ }
241
+ : null,
242
+ ),
243
stopAgent: Effect.sync(() => {
244
agentStops.push("stop");
245
}),
@@ -194,7 +250,7 @@ const fixture = Effect.fn("fixture")(function* (
250
const service = yield* DeviceService.makeWithHosts(
251
new Map([[host.id, host]]),
252
undefined,
197
- undefined,
253
+ () => Effect.succeed("/host.json"),
254
installTool,
255
).pipe(
256
Effect.provide(NodeCrypto.layer),
@@ -232,6 +288,8 @@ const fixture = Effect.fn("fixture")(function* (
288
agentStops,
289
requests,
290
settings,
291
+ closedSessions,
292
+ connection,
293
devices,
294
encoderResult,
295
discoveryErrors,
@@ -801,8 +859,8 @@ it.effect.each(["shutdown", "close"] as const)(
859
operation === "shutdown" ? service.shutdown(input) : service.close({ threadId }),
860
);
861
expect((yield* PubSub.take(updates)).sessions).toEqual([]);
804
- // list writes through the same state lock, so the retirement has committed.
805
- expect((yield* service.list).sessions).toEqual([]);
862
+ yield* service.refreshHosts;
863
+ expect((yield* service.state).sessions).toEqual([]);
864
yield* Effect.sync(() => retiring.interruptUnsafe());
865
yield* Deferred.succeed(pauseBind.proceed, undefined);
866
yield* Fiber.join(binding);
@@ -1363,6 +1421,229 @@ it.effect("a failed tool update reports npm's exit code but not its output", ()
1421
),
1422
);
1423
1424
+describe("agent session release on close", () => {
1425
+ const openClaim = (
1426
+ service: DeviceService.DeviceService["Service"],
1427
+ threadId: ThreadId,
1428
+ deviceId = "Pixel_API_35",
1429
+ ) => service.open({ threadId, deviceId, platform: "android" });
1430
+
1431
+ it.effect("releases only the caller's session, keeps the device booted, and is idempotent", () =>
1432
+ Effect.gen(function* () {
1433
+ const { service, closedSessions, requests } = yield* fixture();
1434
+ yield* service.configure({ enabled: true, agentAccessEnabled: true });
1435
+ const threadId = ThreadId.make("closing");
1436
+ const other = ThreadId.make("other");
1437
+ const session = yield* openClaim(service, threadId);
1438
+ yield* openClaim(service, other, session.deviceId);
1439
+ yield* service.close({ threadId, deviceId: session.deviceId });
1440
+ yield* service.close({ threadId, deviceId: session.deviceId });
1441
+ const name = yield* agentDeviceSession(threadId, session.hostId, session.deviceId).pipe(
1442
+ Effect.provide(NodeCrypto.layer),
1443
+ );
1444
+ expect(closedSessions).toEqual([
1445
+ {
1446
+ jsonrpc: "2.0",
1447
+ id: name,
1448
+ method: "agent_device.command",
1449
+ params: { command: "close", session: name, positionals: [], flags: {} },
1450
+ },
1451
+ ]);
1452
+ const state = yield* service.state;
1453
+ expect(state.sessions.map((entry) => entry.threadId)).toEqual([other]);
1454
+ expect(state.devices.find((entry) => entry.id === session.deviceId)?.booted).toBe(true);
1455
+ expect(requests.some((url) => url.endsWith("/shutdown"))).toBe(false);
1456
+ }),
1457
+ );
1458
+
1459
+ it.effect.each(["reject", "http_error", "malformed"] as const)(
1460
+ "retains retryable state on %s",
1461
+ (failure) =>
1462
+ Effect.gen(function* () {
1463
+ let fail = true;
1464
+ const { service, requests, closedSessions } = yield* fixture(
1465
+ Effect.void,
1466
+ undefined,
1467
+ false,
1468
+ undefined,
1469
+ false,
1470
+ undefined,
1471
+ { onClose: Effect.sync(() => (fail ? failure : "ok")) },
1472
+ );
1473
+ yield* service.configure({ enabled: true, agentAccessEnabled: true });
1474
+ const threadId = ThreadId.make("retry");
1475
+ yield* openClaim(service, threadId);
1476
+ const exit = yield* Effect.exit(service.close({ threadId, shutdown: true }));
1477
+ expect(Exit.isFailure(exit)).toBe(true);
1478
+ expect((yield* service.state).sessions).toHaveLength(1);
1479
+ expect(requests.some((url) => url.endsWith("/shutdown"))).toBe(false);
1480
+ fail = false;
1481
+ yield* service.close({ threadId });
1482
+ expect((yield* service.state).sessions).toHaveLength(0);
1483
+ expect(closedSessions).toHaveLength(2);
1484
+ }),
1485
+ );
1486
+
1487
+ it.effect.each([false, true])("accepts a missing agent session, shutdown=%s", (shutdown) =>
1488
+ Effect.gen(function* () {
1489
+ const { service, requests } = yield* fixture(
1490
+ Effect.void,
1491
+ undefined,
1492
+ false,
1493
+ undefined,
1494
+ false,
1495
+ undefined,
1496
+ { onClose: Effect.succeed("missing") },
1497
+ );
1498
+ yield* service.configure({ enabled: true, agentAccessEnabled: true });
1499
+ const threadId = ThreadId.make("no-claim");
1500
+ yield* openClaim(service, threadId);
1501
+ yield* service.close({ threadId, shutdown });
1502
+ expect((yield* service.state).sessions).toHaveLength(0);
1503
+ expect(requests.some((url) => url.endsWith("/shutdown"))).toBe(shutdown);
1504
+ }),
1505
+ );
1506
+
1507
+ it.effect("retries shutdown after the first attempt already released the agent session", () =>
1508
+ Effect.gen(function* () {
1509
+ let released = false;
1510
+ const { service, connection } = yield* fixture(
1511
+ Effect.void,
1512
+ undefined,
1513
+ false,
1514
+ undefined,
1515
+ false,
1516
+ undefined,
1517
+ {
1518
+ onClose: Effect.sync(() => {
1519
+ const result = released ? "missing" : "ok";
1520
+ released = true;
1521
+ return result;
1522
+ }),
1523
+ },
1524
+ );
1525
+ yield* service.configure({ enabled: true, agentAccessEnabled: true });
1526
+ const threadId = ThreadId.make("retry-shutdown");
1527
+ yield* openClaim(service, threadId);
1528
+ connection.failShutdown = true;
1529
+ expect(Exit.isFailure(yield* Effect.exit(service.close({ threadId, shutdown: true })))).toBe(
1530
+ true,
1531
+ );
1532
+ expect((yield* service.state).sessions).toHaveLength(1);
1533
+ connection.failShutdown = false;
1534
+ yield* service.close({ threadId, shutdown: true });
1535
+ expect((yield* service.state).sessions).toHaveLength(0);
1536
+ }),
1537
+ );
1538
+
1539
+ it.effect("releases the post-boot agentTarget session for a cold Android AVD", () =>
1540
+ Effect.gen(function* () {
1541
+ const { service, closedSessions } = yield* fixture();
1542
+ yield* service.configure({ enabled: true, agentAccessEnabled: true });
1543
+ const threadId = ThreadId.make("cold-avd");
1544
+ const before = yield* service.agentTarget({
1545
+ threadId,
1546
+ hostId: "local",
1547
+ deviceId: "Pixel_API_35",
1548
+ });
1549
+ const session = yield* openClaim(service, threadId);
1550
+ const after = yield* service.agentTarget({
1551
+ threadId,
1552
+ hostId: session.hostId,
1553
+ deviceId: session.deviceId,
1554
+ });
1555
+ expect(session.deviceId).toBe("emulator-5554");
1556
+ expect(after.args[3]).not.toBe(before.args[3]);
1557
+ yield* service.close({ threadId });
1558
+ expect(closedSessions).toEqual([
1559
+ expect.objectContaining({ params: expect.objectContaining({ session: after.args[3] }) }),
1560
+ ]);
1561
+ }),
1562
+ );
1563
+
1564
+ it.effect("retains an SSH record during reconnect and releases it on retry", () =>
1565
+ Effect.gen(function* () {
1566
+ const { service, connection, closedSessions, agentStarts } = yield* fixture();
1567
+ connection.kind = "ssh";
1568
+ yield* service.configure({ enabled: true, agentAccessEnabled: true });
1569
+ const threadId = ThreadId.make("ssh-reconnect");
1570
+ yield* openClaim(service, threadId);
1571
+ const starts = agentStarts.length;
1572
+ connection.online = false;
1573
+ expect(Exit.isFailure(yield* Effect.exit(service.close({ threadId })))).toBe(true);
1574
+ expect((yield* service.state).sessions).toHaveLength(1);
1575
+ expect(closedSessions).toHaveLength(0);
1576
+ expect(agentStarts).toHaveLength(starts);
1577
+ connection.online = true;
1578
+ yield* service.close({ threadId });
1579
+ expect((yield* service.state).sessions).toHaveLength(0);
1580
+ expect(closedSessions).toHaveLength(1);
1581
+ }),
1582
+ );
1583
+ it.effect("releases peer claims before a close shuts down", () =>
1584
+ Effect.gen(function* () {
1585
+ const { service, closedSessions } = yield* fixture();
1586
+ yield* service.configure({ enabled: true, agentAccessEnabled: true });
1587
+ const threadId = ThreadId.make("shutting-down");
1588
+ const other = ThreadId.make("peer");
1589
+ const session = yield* openClaim(service, threadId);
1590
+ yield* openClaim(service, other, session.deviceId);
1591
+ yield* service.close({ threadId, shutdown: true });
1592
+ expect((yield* service.state).sessions).toHaveLength(0);
1593
+ yield* service.close({ threadId: other });
1594
+ expect((yield* service.state).sessions).toHaveLength(0);
1595
+ const names = yield* Effect.forEach([threadId, other], (thread) =>
1596
+ agentDeviceSession(thread, session.hostId, session.deviceId),
1597
+ ).pipe(Effect.provide(NodeCrypto.layer));
1598
+ expect(
1599
+ closedSessions.map((body) => (body as { params: { session: string } }).params.session),
1600
+ ).toEqual(names);
1601
+ }),
1602
+ );
1603
+
1604
+ it.effect("publishes a reopened session only after the old claim is released and removed", () =>
1605
+ Effect.gen(function* () {
1606
+ const entered = yield* Queue.unbounded<void>();
1607
+ const releasing = yield* Deferred.make<void>();
1608
+ const finish = yield* Deferred.make<void>();
1609
+ const { service } = yield* fixture(
1610
+ Effect.void,
1611
+ undefined,
1612
+ false,
1613
+ undefined,
1614
+ false,
1615
+ undefined,
1616
+ {
1617
+ onClose: Effect.gen(function* () {
1618
+ yield* Deferred.succeed(releasing, undefined);
1619
+ yield* Deferred.await(finish);
1620
+ return "ok" as const;
1621
+ }),
1622
+ onPlatformAvailability: Queue.offer(entered, undefined),
1623
+ },
1624
+ );
1625
+ yield* service.configure({ enabled: true, agentAccessEnabled: true });
1626
+ const threadId = ThreadId.make("reopen");
1627
+ const session = yield* openClaim(service, threadId);
1628
+ yield* Queue.take(entered);
1629
+ const publications = yield* service.subscribe;
1630
+ const closing = yield* service.close({ threadId }).pipe(Effect.forkChild);
1631
+ yield* Deferred.await(releasing);
1632
+ const opening = yield* openClaim(service, threadId, session.deviceId).pipe(Effect.forkChild);
1633
+ yield* Queue.take(entered);
1634
+ yield* Deferred.succeed(finish, undefined);
1635
+ yield* Fiber.join(closing);
1636
+ const reopened = yield* Fiber.join(opening);
1637
+ const published = (yield* PubSub.takeAll(publications))
1638
+ .map(({ sessions }) =>
1639
+ sessions.includes(session) ? "old" : sessions.includes(reopened) ? "reopened" : "none",
1640
+ )
1641
+ .filter((label, index, labels) => label !== labels[index - 1]);
1642
+ expect(published).toEqual(["none", "reopened"]);
1643
+ }).pipe(Effect.scoped),
1644
+ );
1645
+});
1646
+
1647
describe("locating a device id across hosts", () => {
1648
const threadId = ThreadId.make("thread-locate");
1649
const thisMachine = { id: LOCAL_DEVICE_HOST_ID, label: "This machine" };
apps/server/src/device/DeviceService.ts
+91
-33
@@ -338,6 +338,26 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
338
}),
339
);
340
341
+ const releaseLaunchers = (sessions: ReadonlyArray<DeviceSession>) =>
342
+ launcherLock.withPermit(
343
+ Effect.forEach(
344
+ sessions,
345
+ (session) =>
346
+ Effect.gen(function* () {
347
+ const name = yield* agentDeviceSession(
348
+ session.threadId,
349
+ session.hostId,
350
+ session.deviceId,
351
+ ).pipe(Effect.provideService(Crypto.Crypto, crypto));
352
+ const launcher = boundLaunchers.get(name);
353
+ if (!launcher || hostSessionLaunchers.has(name) || !launchers?.release) return;
354
+ yield* launchers.release(launcher);
355
+ boundLaunchers.delete(name);
356
+ }),
357
+ { discard: true },
358
+ ),
359
+ );
360
+
361
// Uninterruptible so a committed retirement always prunes, even if its caller is cancelled.
362
const publish = (update: (state: DeviceServiceState) => DeviceServiceState) =>
363
SynchronizedRef.modifyEffect(stateRef, ({ state }) => {
@@ -817,12 +837,18 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
837
},
838
);
839
840
+ const refreshAfterShutdown = (ready: DeviceReadiness) =>
841
+ refresh(ready).pipe(
842
+ Effect.catch((cause) =>
843
+ Effect.logWarning("Device discovery unavailable after shutdown", { cause }),
844
+ ),
845
+ );
846
+
847
const shutdownDevice = Effect.fn("DeviceService.shutdownDevice")(function* (
821
- hostId: DeviceHostId,
848
+ ready: DeviceReadiness,
849
deviceId: DeviceId,
850
platform: DevicePlatform,
851
) {
825
- const ready = yield* readiness(hostId);
852
yield* ready.devices.shutdown({ id: deviceId, platform });
853
yield* publish((state) => ({
854
...state,
@@ -831,46 +857,76 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
857
? { ...device, booted: false }
858
: device,
859
),
834
- sessions: state.sessions.filter(
835
- (session) => !(session.hostId === ready.hostId && session.deviceId === deviceId),
836
- ),
860
}));
838
- // Snapshot saves can stall discovery; refresh failure must not fail an accepted shutdown.
839
- yield* refresh(ready).pipe(
840
- Effect.catch((cause) =>
841
- Effect.logWarning("Device discovery unavailable after shutdown", { cause }),
842
- ),
843
- );
861
});
862
863
const close: DeviceService["Service"]["close"] = Effect.fn("DeviceService.close")(
864
function* (input) {
848
- const { state } = yield* SynchronizedRef.get(stateRef);
849
- const closing = state.sessions.filter(
850
- (session) =>
851
- session.threadId === input.threadId &&
852
- (input.hostId === undefined || session.hostId === input.hostId) &&
853
- (input.deviceId === undefined || session.deviceId === input.deviceId),
865
+ // Open publishes under the same lock; an old close must not release a reopened claim.
866
+ const closing = yield* lifecycleLock.withPermit(
867
+ Effect.gen(function* () {
868
+ const { state } = yield* SynchronizedRef.get(stateRef);
869
+ const closing = state.sessions.filter(
870
+ (session) =>
871
+ session.threadId === input.threadId &&
872
+ (input.hostId === undefined || session.hostId === input.hostId) &&
873
+ (input.deviceId === undefined || session.deviceId === input.deviceId),
874
+ );
875
+ const ending = input.shutdown
876
+ ? state.sessions.filter((session) =>
877
+ closing.some(
878
+ (closed) =>
879
+ closed.hostId === session.hostId && closed.deviceId === session.deviceId,
880
+ ),
881
+ )
882
+ : closing;
883
+ for (const session of ending) {
884
+ const host = yield* resolveHost(session.hostId);
885
+ const ready = yield* host.current;
886
+ // A lost SSH tunnel does not establish that the remote daemon stopped.
887
+ if (!ready && (yield* host.summary).kind === "ssh")
888
+ return yield* new DeviceHostUnavailableError({
889
+ hostId: session.hostId,
890
+ hostLabel: host.label,
891
+ reason: "Device host is reconnecting. Retry close after it reconnects.",
892
+ });
893
+ if (ready?.releaseAgentSession) {
894
+ const name = yield* agentDeviceSession(
895
+ session.threadId,
896
+ session.hostId,
897
+ session.deviceId,
898
+ ).pipe(Effect.provideService(Crypto.Crypto, crypto));
899
+ yield* ready.releaseAgentSession(name, session.deviceId);
900
+ }
901
+ }
902
+ if (input.shutdown) yield* releaseLaunchers(ending);
903
+ if (input.shutdown) {
904
+ for (const session of closing) {
905
+ const ready = yield* currentReadiness(session.hostId);
906
+ if (!ready)
907
+ return yield* new DeviceHostUnavailableError({
908
+ hostId: session.hostId,
909
+ reason: "Device host is not running. Reconnect before retrying close.",
910
+ });
911
+ yield* shutdownDevice(ready, session.deviceId, session.platform);
912
+ }
913
+ }
914
+ yield* publish((current) => ({
915
+ ...current,
916
+ sessions: current.sessions.filter((session) => !ending.includes(session)),
917
+ }));
918
+ return closing;
919
+ }),
920
);
855
- if (closing.length === 0) return;
856
- // Powering off ends every session on the device, so all of them retire, and release, while it is on.
857
- const ending = (session: DeviceSession) =>
858
- closing.includes(session) ||
859
- (input.shutdown === true &&
860
- closing.some(
861
- (closed) => closed.hostId === session.hostId && closed.deviceId === session.deviceId,
862
- ));
863
- yield* publish((current) => ({
864
- ...current,
865
- sessions: current.sessions.filter((session) => !ending(session)),
866
- }));
867
- if (input.shutdown) {
921
+ if (input.shutdown)
922
yield* Effect.forEach(
923
closing,
870
- (session) => shutdownDevice(session.hostId, session.deviceId, session.platform),
924
+ (session) =>
925
+ currentReadiness(session.hostId).pipe(
926
+ Effect.flatMap((ready) => (ready ? refreshAfterShutdown(ready) : Effect.void)),
927
+ ),
928
{ discard: true },
929
);
873
- }
930
},
931
);
932
@@ -885,7 +941,9 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
941
(session) => !(session.hostId === host.id && session.deviceId === input.deviceId),
942
),
943
}));
888
- yield* shutdownDevice(host.id, input.deviceId, input.platform);
944
+ const ready = yield* readiness(host.id);
945
+ yield* shutdownDevice(ready, input.deviceId, input.platform);
946
+ yield* refreshAfterShutdown(ready);
947
},
948
);
949
apps/server/src/device/EasDeviceHost.test.ts
+79
-2
@@ -1,6 +1,7 @@
1
import { describe, expect, it } from "@effect/vitest";
2
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3
import * as NodeServices from "@effect/platform-node/NodeServices";
3
-import type { EasDeviceHostConfig } from "@t3tools/contracts";
4
+import { type EasDeviceHostConfig, ThreadId } from "@t3tools/contracts";
5
import * as HostProcess from "@t3tools/shared/HostProcess";
6
import * as Deferred from "effect/Deferred";
7
import * as Effect from "effect/Effect";
@@ -15,6 +16,8 @@ import { HttpClient, HttpClientResponse } from "effect/http";
16
17
import * as ServerConfig from "../config.ts";
18
import * as ProcessRunner from "../processRunner.ts";
19
+import * as ServerSettings from "../serverSettings.ts";
20
+import * as DeviceService from "./DeviceService.ts";
21
import * as EasDeviceHost from "./EasDeviceHost.ts";
22
23
const APP_ID = "d763fcb8-d37c-41ea-a773-b54a0ab4a454";
@@ -57,9 +60,12 @@ const fakeExpo = (
60
readonly activeIncludesCreated?: boolean;
61
readonly failPreview?: boolean;
62
readonly omitCreatedFromActive?: boolean;
63
+ /** The session's agent-device daemon answers with a server error. */
64
+ readonly failAgent?: () => boolean;
65
} = {},
66
) => {
67
const calls: Array<{ operation: string; variables: Record<string, unknown> }> = [];
68
+ const releases: Array<unknown> = [];
69
let created = 0;
70
let createdName = "";
71
const previews: string[] = [];
@@ -91,6 +97,18 @@ const fakeExpo = (
97
),
98
);
99
}
100
+ if (url.origin === "https://agent.test") {
101
+ expect(request.headers.authorization).toBe("Bearer agent-token");
102
+ if (request.body._tag === "Uint8Array") {
103
+ const rpc = JSON.parse(new TextDecoder().decode(request.body.body)) as {
104
+ params: { command: string; session: string };
105
+ };
106
+ if (rpc.params.command === "close") releases.push(rpc.params.session);
107
+ }
108
+ if (options.failAgent?.())
109
+ return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
110
+ return HttpClientResponse.fromWeb(request, Response.json({ result: { ok: true } }));
111
+ }
112
const body =
113
request.body._tag === "Uint8Array"
114
? (JSON.parse(new TextDecoder().decode(request.body.body)) as {
@@ -207,7 +225,7 @@ const fakeExpo = (
225
const allowCreate = () => {
226
createFails = false;
227
};
210
- return { http, named, stopped, allowPreview, allowCreate, previews };
228
+ return { http, named, stopped, allowPreview, allowCreate, releases, previews };
229
};
230
231
const layer = Layer.mergeAll(
@@ -566,4 +584,63 @@ describe("EAS Simulator host", () => {
584
]);
585
}).pipe(Effect.scoped, Effect.provide(layer)),
586
);
587
+
588
+ it.effect("releases each thread's agent session on close and keeps the session running", () =>
589
+ Effect.gen(function* () {
590
+ let agentFails = false;
591
+ const expo = fakeExpo({ failAgent: () => agentFails });
592
+ const host = yield* makeHost(expo, config(), yield* Scope.make());
593
+ const service = yield* DeviceService.makeWithHosts(new Map([["eas", host]]), undefined, () =>
594
+ Effect.succeed("/eas-agent.json"),
595
+ );
596
+ const first = ThreadId.make("first");
597
+ const second = ThreadId.make("second");
598
+ const opened = yield* service.open({
599
+ threadId: first,
600
+ hostId: "eas",
601
+ deviceId: "eas-ios",
602
+ platform: "ios",
603
+ });
604
+ expect(opened.deviceId).toBe("session-1");
605
+ yield* service.open({
606
+ threadId: second,
607
+ hostId: "eas",
608
+ deviceId: opened.deviceId,
609
+ platform: "ios",
610
+ });
611
+ const sessionOf = (threadId: ThreadId) =>
612
+ service
613
+ .agentTarget({ threadId, hostId: "eas", deviceId: opened.deviceId })
614
+ .pipe(Effect.map((target) => target.args[3]));
615
+ const firstSession = yield* sessionOf(first);
616
+ const secondSession = yield* sessionOf(second);
617
+
618
+ yield* service.close({ threadId: first });
619
+ expect(expo.releases).toEqual([firstSession]);
620
+ expect((yield* service.state).sessions.map((entry) => entry.threadId)).toEqual([second]);
621
+
622
+ agentFails = true;
623
+ const failed = yield* Effect.exit(service.close({ threadId: second, shutdown: false }));
624
+ expect(Exit.isFailure(failed)).toBe(true);
625
+ expect((yield* service.state).sessions.map((entry) => entry.threadId)).toEqual([second]);
626
+
627
+ agentFails = false;
628
+ yield* service.close({ threadId: second, shutdown: false });
629
+ expect(expo.releases).toEqual([firstSession, secondSession, secondSession]);
630
+ expect((yield* service.state).sessions).toEqual([]);
631
+ expect(expo.stopped()).not.toContain("session-1");
632
+ expect(
633
+ (yield* service.state).devices.find((device) => device.id === "session-1")?.booted,
634
+ ).toBe(true);
635
+ }).pipe(
636
+ Effect.scoped,
637
+ Effect.provide(
638
+ Layer.mergeAll(
639
+ layer,
640
+ NodeCrypto.layer,
641
+ ServerSettings.layerTest({ enableDeviceSupport: true, enableAgentDeviceAccess: true }),
642
+ ),
643
+ ),
644
+ ),
645
+ );
646
});
apps/server/src/device/EasDeviceHost.ts
+7
@@ -32,6 +32,7 @@ import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
32
import * as HostProcess from "@t3tools/shared/HostProcess";
33
34
import * as ServerConfig from "../config.ts";
35
+import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";
36
import * as DeviceHost from "./DeviceHost.ts";
37
import { findEasProjectId } from "./easProjectId.ts";
38
import { type ExpoApi, makeExpoApi, resolveExpoCredential } from "./ExpoApi.ts";
@@ -827,6 +828,12 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice
828
hub: { origin: "https://api.expo.dev" },
829
devices,
830
upstream,
831
+ // Each session runs its own daemon, so one that has ended holds no agent sessions.
832
+ releaseAgentSession: (session, deviceId) =>
833
+ Option.match(sessionFor(deviceId), {
834
+ onNone: () => Effect.void,
835
+ onSome: (running) => releaseAgentDeviceSession(http, running.agent)(session),
836
+ }),
837
// Device settings run simctl on the simulator's own machine, which EAS does not expose.
838
run: () =>
839
Effect.succeed({
apps/server/src/device/LocalDeviceHost.test.ts
+50
-16
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
5
import * as Layer from "effect/Layer";
6
import * as Option from "effect/Option";
7
import * as Path from "effect/Path";
8
+import * as PlatformError from "effect/PlatformError";
9
import * as FileSystem from "effect/FileSystem";
10
import * as Sink from "effect/Sink";
11
import * as Stream from "effect/Stream";
@@ -42,6 +43,7 @@ const agentFixture = Effect.fn("agentFixture")(function* (
43
const fs = yield* FileSystem.FileSystem;
44
const path = yield* Path.Path;
45
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-agent-start-" });
46
+ const hub = { running: true, spawnFails: false };
47
const stateDir = agentDeviceStateDir(path, path.join(baseDir, "userdata"));
48
for (const [name, version, entry] of [
49
["expo-device-hub", DEVICE_HUB_VERSION, "dist/server/cli.mjs"],
@@ -61,21 +63,30 @@ const agentFixture = Effect.fn("agentFixture")(function* (
63
Effect.provideService(
64
ChildProcessSpawner.ChildProcessSpawner,
65
ChildProcessSpawner.make(() =>
64
- Effect.succeed(
65
- ChildProcessSpawner.makeHandle({
66
- pid: ChildProcessSpawner.ProcessId(123),
67
- stdout: Stream.empty,
68
- stderr: Stream.empty,
69
- all: Stream.empty,
70
- exitCode: Effect.never,
71
- isRunning: Effect.succeed(true),
72
- kill: () => Effect.void,
73
- stdin: Sink.drain,
74
- getInputFd: () => Sink.drain,
75
- getOutputFd: () => Stream.empty,
76
- unref: Effect.succeed(Effect.void),
77
- }),
78
- ),
66
+ hub.spawnFails
67
+ ? Effect.fail(
68
+ PlatformError.systemError({
69
+ _tag: "NotFound",
70
+ module: "ChildProcess",
71
+ method: "spawn",
72
+ description: "Hub entry missing",
73
+ }),
74
+ )
75
+ : Effect.succeed(
76
+ ChildProcessSpawner.makeHandle({
77
+ pid: ChildProcessSpawner.ProcessId(123),
78
+ stdout: Stream.empty,
79
+ stderr: Stream.empty,
80
+ all: Stream.empty,
81
+ exitCode: Effect.never,
82
+ isRunning: Effect.sync(() => hub.running),
83
+ kill: () => Effect.void,
84
+ stdin: Sink.drain,
85
+ getInputFd: () => Sink.drain,
86
+ getOutputFd: () => Stream.empty,
87
+ unref: Effect.succeed(Effect.void),
88
+ }),
89
+ ),
90
),
91
),
92
Effect.provideService(ProcessRunner.ProcessRunner, {
@@ -92,7 +103,7 @@ const agentFixture = Effect.fn("agentFixture")(function* (
103
),
104
);
105
yield* host.ensureReady(() => Effect.void);
95
- return { host, fs, stateDir };
106
+ return { host, fs, stateDir, hub };
107
});
108
109
describe("AgentDevice startup", () => {
@@ -196,9 +207,32 @@ describe("AgentDevice startup", () => {
207
expect((yield* host.ensureAgentReady(() => Effect.void)).agentDevice).toEqual(
208
ready.agentDevice,
209
);
210
+ expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
211
expect(attempts).toBe(1);
212
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
213
);
214
+
215
+ it.effect("keeps releasing agent sessions while a dead hub fails to restart and after", () =>
216
+ Effect.gen(function* () {
217
+ const fs = yield* FileSystem.FileSystem;
218
+ const { host, hub } = yield* agentFixture((stateDir) =>
219
+ fs
220
+ .writeFileString(
221
+ `${stateDir}/daemon.json`,
222
+ JSON.stringify({ httpPort: 12345, token: "test-token" }),
223
+ )
224
+ .pipe(Effect.orDie, Effect.as(processOutput(0))),
225
+ );
226
+ yield* host.ensureAgentReady(() => Effect.void);
227
+ hub.running = false;
228
+ hub.spawnFails = true;
229
+ expect((yield* host.ensureReady(() => Effect.void).pipe(Effect.result))._tag).toBe("Failure");
230
+ expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
231
+ hub.spawnFails = false;
232
+ yield* host.ensureReady(() => Effect.void);
233
+ expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function");
234
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
235
+ );
236
});
237
238
const diagnose = (
apps/server/src/device/LocalDeviceHost.ts
+7
-2
@@ -36,6 +36,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
36
import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
37
import * as ServerConfig from "../config.ts";
38
import * as ProcessRunner from "../processRunner.ts";
39
+import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";
40
import * as DeviceHost from "./DeviceHost.ts";
41
import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";
42
import {
@@ -650,10 +651,11 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
651
onPhase: (phase: "installing" | "starting", detail?: string) => Effect.Effect<void>,
652
): Effect.fn.Return<RunningHost, DeviceHost.DeviceHostError | NodeRuntimeUnavailableError> {
653
const running = yield* Ref.get(runningRef);
654
+ // A dead hub's record stays until a replacement is published: the agent
655
+ // daemon outlives the hub, and close needs its endpoint if the restart fails.
656
if (running) {
657
const alive = yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false));
658
if (alive) return running;
656
- yield* Ref.set(runningRef, null);
659
}
660
const nodePath = yield* resolveNodeExecutable("Local device support", hostEnvironment).pipe(
661
Effect.provideService(FileSystem.FileSystem, fs),
@@ -696,7 +698,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
698
]);
699
const next: RunningHost = {
700
hub,
699
- agentDevice: null,
701
+ agentDevice: running?.agentDevice ?? null,
702
helpers: {
703
serveSimAxSettings: axExists ? candidate.serveSimAxSettings : null,
704
serveSimCli: cliExists ? candidate.serveSimCli : null,
@@ -821,6 +823,9 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
823
nodePath: running.hub.nodePath,
824
run,
825
helpers: running.helpers,
826
+ ...(running.agentDevice
827
+ ? { releaseAgentSession: releaseAgentDeviceSession(httpClient, running.agentDevice) }
828
+ : {}),
829
});
830
831
const current: DeviceHost.DeviceHost["Service"]["current"] = Ref.get(runningRef).pipe(
apps/server/src/device/SshDeviceHost.test.ts
+11
-1
@@ -26,6 +26,7 @@ it.effect("preserves installed status after probes and cleans failed agent activ
26
let forwards = 0;
27
let failForward = true;
28
let rejectConfig = true;
29
+ const releases: Array<string | undefined> = [];
30
const spawner = ChildProcessSpawner.make((command) =>
31
Effect.gen(function* () {
32
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 activ
119
Effect.provideService(
120
HttpClient.HttpClient,
121
HttpClient.make((request) =>
121
- Effect.succeed(HttpClientResponse.fromWeb(request, new Response("ok"))),
122
+ Effect.sync(() => {
123
+ if (!request.url.endsWith("/rpc"))
124
+ return HttpClientResponse.fromWeb(request, new Response("ok"));
125
+ releases.push(request.headers.authorization);
126
+ return HttpClientResponse.fromWeb(request, Response.json({ result: { ok: true } }));
127
+ }),
128
),
129
),
130
);
@@ -156,6 +162,10 @@ it.effect("preserves installed status after probes and cleans failed agent activ
162
yield* host.ensureAgentReady(() => Effect.void);
163
yield* host.platformAvailability("ios");
164
expect((yield* host.summary).agentDeviceInstalled).toBe(true);
165
+ // Close releases agent sessions through the forwarded daemon.
166
+ const agentReady = yield* host.current;
167
+ yield* agentReady!.releaseAgentSession!("t3-session", "device");
168
+ expect(releases).toEqual(["Bearer fixture"]);
169
yield* host.stopAgent;
170
expect(forwards).toBe(1);
171
const multiplexingOff = ["ControlMaster=no", "ControlPath=none", "ControlPersist=no"];
apps/server/src/device/SshDeviceHost.ts
+4
-1
@@ -22,6 +22,7 @@ import * as HttpClient from "effect/http/HttpClient";
22
import * as ChildProcess from "effect/process/ChildProcess";
23
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
24
import * as ServerConfig from "../config.ts";
25
+import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";
26
import * as DeviceHost from "./DeviceHost.ts";
27
import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";
28
import { quoteRemoteArg, remoteDeviceEnvironment, remoteDeviceScript } from "./sshDeviceScript.ts";
@@ -351,7 +352,9 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (
352
}).pipe(Effect.provideService(HttpClient.HttpClient, http));
353
}
354
if (next.agentDevice) yield* onReady({ ...next, agentDevice: next.agentDevice });
354
- ready = next;
355
+ ready = next.agentDevice
356
+ ? { ...next, releaseAgentSession: releaseAgentDeviceSession(http, next.agentDevice) }
357
+ : next;
358
yield* onStatus("ready");
359
// Reconnect also repairs helpers that died while SSH itself stayed connected.
360
const unhealthy = Effect.gen(function* () {
apps/server/src/device/sshDeviceScript.test.ts
+88
-1
@@ -7,7 +7,7 @@ import * as NodeFSP from "node:fs/promises";
7
import * as NodeOS from "node:os";
8
import * as NodePath from "node:path";
9
import * as NodeUtil from "node:util";
10
-import { quoteRemoteArg, remoteDeviceEnvironment } from "./sshDeviceScript.ts";
10
+import { quoteRemoteArg, remoteDeviceEnvironment, remoteDeviceScript } from "./sshDeviceScript.ts";
11
12
const exec = NodeUtil.promisify(NodeChildProcess.execFile);
13
@@ -45,3 +45,90 @@ it.effect("preserves shell metacharacters and newlines in remote arguments", ()
45
});
46
}),
47
);
48
+
49
+it.effect("stops a daemon left for its owner when starting without agent tools", () =>
50
+ Effect.gen(function* () {
51
+ if ((yield* HostProcess.Platform) === "win32") return;
52
+ yield* Effect.promise(async () => {
53
+ const home = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-ssh-start-"));
54
+ try {
55
+ const state = NodePath.join(home, ".t3/device/hosts/owner");
56
+ const daemonFile = NodePath.join(state, "daemon.json");
57
+ const calls = NodePath.join(home, "calls");
58
+ const failMarker = NodePath.join(home, "fail-stop");
59
+ const entry = NodePath.join(home, "agent-device.mjs");
60
+ await NodeFSP.mkdir(NodePath.join(home, "bin"));
61
+ await NodeFSP.mkdir(state, { recursive: true });
62
+ await NodeFSP.writeFile(
63
+ entry,
64
+ `import * as fs from "node:fs";
65
+fs.appendFileSync(${JSON.stringify(calls)}, process.argv.slice(2).join(" ") + "\\n");
66
+if (fs.existsSync(${JSON.stringify(failMarker)})) process.exitCode = 1;`,
67
+ );
68
+ await NodeFSP.writeFile(
69
+ NodePath.join(state, "agent.json"),
70
+ JSON.stringify({ entryPath: entry }),
71
+ );
72
+ await NodeFSP.writeFile(daemonFile, JSON.stringify({ httpPort: 1, token: "claims" }));
73
+ // An empty PATH leaves no platforms, so the script ends right after the daemon check.
74
+ const start = () =>
75
+ NodeChildProcess.spawnSync(process.execPath, [], {
76
+ input: remoteDeviceScript("owner", "start"),
77
+ env: { HOME: home, PATH: NodePath.join(home, "bin") },
78
+ encoding: "utf8",
79
+ });
80
+ await NodeFSP.writeFile(failMarker, "");
81
+ expect(start().stderr).toContain("Could not stop the agent-device daemon");
82
+ expect(await NodeFSP.readFile(daemonFile, "utf8")).toContain("claims");
83
+ await NodeFSP.rm(failMarker);
84
+ expect(start().stderr).toContain("Android SDK missing");
85
+ await expect(NodeFSP.access(daemonFile)).rejects.toThrow();
86
+ expect(await NodeFSP.readFile(calls, "utf8")).toBe(
87
+ `daemon stop --state-dir ${state}\ndaemon stop --state-dir ${state}\n`,
88
+ );
89
+ } finally {
90
+ await NodeFSP.rm(home, { recursive: true, force: true });
91
+ }
92
+ });
93
+ }),
94
+);
95
+
96
+it.effect("keeps a daemon record its missing agent CLI cannot stop", () =>
97
+ Effect.gen(function* () {
98
+ if ((yield* HostProcess.Platform) === "win32") return;
99
+ yield* Effect.promise(async () => {
100
+ const home = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-ssh-start-"));
101
+ try {
102
+ const state = NodePath.join(home, ".t3/device/hosts/owner");
103
+ const daemonFile = NodePath.join(state, "daemon.json");
104
+ await NodeFSP.mkdir(NodePath.join(home, "bin"));
105
+ await NodeFSP.mkdir(state, { recursive: true });
106
+ await NodeFSP.writeFile(
107
+ NodePath.join(state, "agent.json"),
108
+ JSON.stringify({ entryPath: NodePath.join(home, "missing/agent-device.mjs") }),
109
+ );
110
+ const start = async (pid: number) => {
111
+ await NodeFSP.writeFile(
112
+ daemonFile,
113
+ JSON.stringify({ pid, httpPort: 1, token: "claims" }),
114
+ );
115
+ return NodeChildProcess.spawnSync(process.execPath, [], {
116
+ input: remoteDeviceScript("owner", "start"),
117
+ env: { HOME: home, PATH: NodePath.join(home, "bin") },
118
+ encoding: "utf8",
119
+ });
120
+ };
121
+ // This test process stands in for a daemon that is still running.
122
+ expect((await start(process.pid)).stderr).toContain(
123
+ "Could not stop the agent-device daemon",
124
+ );
125
+ expect(await NodeFSP.readFile(daemonFile, "utf8")).toContain("claims");
126
+ const exited = NodeChildProcess.spawnSync(process.execPath, ["-e", ""]).pid;
127
+ expect((await start(exited)).stderr).toContain("Android SDK missing");
128
+ await expect(NodeFSP.access(daemonFile)).rejects.toThrow();
129
+ } finally {
130
+ await NodeFSP.rm(home, { recursive: true, force: true });
131
+ }
132
+ });
133
+ }),
134
+);
apps/server/src/device/sshDeviceScript.ts
+15
-2
@@ -151,16 +151,29 @@ async function install(name, version, entry) {
151
const hubFile = path.join(state, 'hub.json');
152
const daemonFile = path.join(state, 'daemon.json');
153
const agentFile = path.join(state, 'agent.json');
154
+ const stopAgent = () => {
155
+ const entry = read(agentFile)?.entryPath || path.join(root, 'tools', 'agent-device@' + agentVersion, 'node_modules', 'agent-device', 'bin', 'agent-device.mjs');
156
+ if (fs.existsSync(entry)) return run(process.execPath, [entry, 'daemon', 'stop', '--state-dir', state]).status === 0;
157
+ // A running daemon outlives its deleted CLI, so without one only a recorded pid that is gone counts as stopped.
158
+ const pid = read(daemonFile)?.pid;
159
+ return Number.isSafeInteger(pid) && pid > 0 && !maintenanceAlive(pid);
160
+ };
161
if (mode === 'stop' || mode === 'stop-agent') {
162
const hub = read(hubFile);
163
if (mode === 'stop' && hub && hub.owner === owner) {
164
stopHub(hub);
165
fs.rmSync(hubFile, { force: true });
166
}
160
- const entry = read(agentFile)?.entryPath || path.join(root, 'tools', 'agent-device@' + agentVersion, 'node_modules', 'agent-device', 'bin', 'agent-device.mjs');
161
- if (fs.existsSync(entry)) run(process.execPath, [entry, 'daemon', 'stop', '--state-dir', state]);
167
+ stopAgent();
168
return;
169
}
170
+ // A start without agent tools means the server holds no claims, so a daemon still here is
171
+ // orphaned. Agent access was turned off while the tunnel was down, or a server crashed.
172
+ // Close skips the release when start returns no endpoint, so the claims must end here.
173
+ if (mode === 'start' && read(daemonFile)) {
174
+ if (!stopAgent()) throw Error('Could not stop the agent-device daemon in ' + state);
175
+ fs.rmSync(daemonFile, { force: true });
176
+ }
177
if (!ios && !android) throw Error(platforms.map(p => p.reason).join(' '));
178
fs.mkdirSync(state, { recursive: true, mode: 0o700 });
179
const hubEntry = await install('expo-device-hub', hubVersion, 'dist/server/cli.mjs');