Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import type { SimlockDeviceHostConfig } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as Deferred from "effect/Deferred";
7import * as Exit from "effect/Exit";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Path from "effect/Path";
11import * as Scope from "effect/Scope";
12import * as TestClock from "effect/testing/TestClock";
13import { HttpClient, HttpClientResponse } from "effect/http";
14import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15
16import * as ServerConfig from "../config.ts";
17import * as ProcessRunner from "../processRunner.ts";
18import * as SimlockDeviceHost from "./SimlockDeviceHost.ts";
19
20const GATEWAY = "https://simlock.test:4700";
21
22const config = (overrides: Partial<SimlockDeviceHostConfig> = {}): SimlockDeviceHostConfig => ({
23 kind: "simlock",
24 id: "pool",
25 label: "Device pool",
26 gatewayUrl: `${GATEWAY}/`,
27 agentToken: "agent-token",
28 maxLeases: 2,
29 maxLeaseMinutes: 60,
30 ...overrides,
31});
32
33const CATALOG = {
34 platforms: [
35 {
36 platform: "ios",
37 modelRuntimes: { "iPhone 17 Pro": ["27.0"], "Apple TV 4K": ["27.0"], "iPhone 12": [] },
38 modelClasses: { "iPhone 17 Pro": "phone", "Apple TV 4K": "tv", "iPhone 12": "phone" },
39 },
40 {
41 platform: "android",
42 modelRuntimes: { "Pixel 9": ["36"], "Pixel 8": ["36"] },
43 modelWorkers: { "Pixel 9": ["worker-a"], "Pixel 8": [] },
44 },
45 ],
46};
47
48/** The gateway's HTTP API and T3's agent-device CLI, recording what was asked of them. */
49const fakePool = (
50 options: {
51 readonly failOpen?: boolean;
52 readonly holdOpen?: {
53 readonly entered: Deferred.Deferred<void>;
54 readonly proceed: Deferred.Deferred<void>;
55 };
56 } = {},
57) =>
58 Effect.gen(function* () {
59 const fs = yield* FileSystem.FileSystem;
60 const path = yield* Path.Path;
61 const requests: Array<string> = [];
62 const commands: Array<{ readonly args: ReadonlyArray<string>; readonly cwd?: string }> = [];
63 let leases = 0;
64 let renewStatus = 200;
65 const http = HttpClient.make((request) =>
66 Effect.sync(() => {
67 const url = new URL(request.url);
68 requests.push(`${request.method} ${url.pathname}`);
69 expect(request.headers.authorization).toBe("Bearer agent-token");
70 const json = (body: unknown, status = 200) =>
71 HttpClientResponse.fromWeb(request, Response.json(body, { status }));
72 if (url.pathname === "/v1/catalog") return json(CATALOG);
73 if (url.pathname.endsWith("/renew")) return json({}, renewStatus);
74 if (request.method === "DELETE") return json({}, 202);
75 return json({}, 404);
76 }),
77 );
78 const runner = ProcessRunner.ProcessRunner.of({
79 run: (input) =>
80 Effect.gen(function* () {
81 const args = input.args.slice(1);
82 commands.push({ args, ...(input.cwd ? { cwd: input.cwd } : {}) });
83 const command = args[0];
84 const session = args[args.indexOf("--session") + 1]!;
85 const configFile = args[args.indexOf("--config") + 1]!;
86 const stateDir = (
87 JSON.parse(yield* fs.readFileString(configFile)) as { stateDir: string }
88 ).stateDir;
89 if (command === "open") {
90 if (options.failOpen) {
91 return {
92 stdout: JSON.stringify({
93 error: { message: "No device matches.", hint: "Retry." },
94 }),
95 stderr: "",
96 code: ChildProcessSpawner.ExitCode(1),
97 timedOut: false,
98 stdoutTruncated: false,
99 stderrTruncated: false,
100 stdoutInvalidUtf8: false,
101 stderrInvalidUtf8: false,
102 };
103 }
104 if (options.holdOpen) {
105 yield* Deferred.succeed(options.holdOpen.entered, undefined);
106 yield* Deferred.await(options.holdOpen.proceed);
107 }
108 const dir = path.join(stateDir, "remote-connections");
109 yield* fs.makeDirectory(dir, { recursive: true });
110 yield* fs.writeFileString(
111 path.join(dir, `${session}.json`),
112 JSON.stringify({ leaseId: `lease-${++leases}` }),
113 );
114 }
115 if (command === "screenshot") yield* fs.writeFile(args[1]!, new Uint8Array([1, 2, 3]));
116 return {
117 stdout: "{}",
118 stderr: "",
119 code: ChildProcessSpawner.ExitCode(0),
120 timedOut: false,
121 stdoutTruncated: false,
122 stderrTruncated: false,
123 stdoutInvalidUtf8: false,
124 stderrInvalidUtf8: false,
125 };
126 }).pipe(Effect.orDie),
127 });
128 const ran = (command: string) => commands.filter(({ args }) => args[0] === command);
129 return {
130 http,
131 runner,
132 requests,
133 ran,
134 endLeases: () => {
135 renewStatus = 404;
136 },
137 };
138 });
139
140const layer = Layer.mergeAll(
141 ServerConfig.layerTest(process.cwd(), { prefix: "t3-simlock-host-" }),
142).pipe(Layer.provideMerge(NodeServices.layer));
143
144const makeHost = (
145 pool: Effect.Success<ReturnType<typeof fakePool>>,
146 hostConfig: SimlockDeviceHostConfig,
147 scope: Scope.Scope,
148) =>
149 SimlockDeviceHost.make(
150 hostConfig,
151 Effect.succeed({ nodePath: "node", entryPath: "/tools/agent-device.mjs" }),
152 ).pipe(
153 Effect.provideService(HttpClient.HttpClient, pool.http),
154 Effect.provideService(ProcessRunner.ProcessRunner, pool.runner),
155 Effect.provideService(Scope.Scope, scope),
156 );
157
158describe("Simlock device host", () => {
159 it.effect("leases a pool device for agents and serves its screen and input to the panel", () =>
160 Effect.gen(function* () {
161 const pool = yield* fakePool();
162 const fs = yield* FileSystem.FileSystem;
163 const workspace = yield* fs.makeTempDirectoryScoped();
164 const scope = yield* Scope.make();
165 const host = yield* makeHost(pool, config(), scope);
166 const ready = yield* host.ensureReady(() => Effect.void);
167
168 const catalog = (yield* ready.devices.list).devices;
169 // Only models a worker can make right now, and only phones and tablets.
170 expect(catalog.map((device) => [device.id, device.version])).toEqual([
171 ["simlock:ios:iPhone 17 Pro", "iOS 27.0"],
172 ["simlock:android:Pixel 9", "Android 36"],
173 ]);
174
175 const leaseId = yield* ready.devices.boot(catalog[1]!, { workspaceRoot: workspace });
176 expect(leaseId).toBe("lease-1");
177 const [open] = pool.ran("open");
178 expect(open?.args.slice(0, 5)).toEqual([
179 "open",
180 "--platform",
181 "android",
182 "--device",
183 "Pixel 9",
184 ]);
185 expect(open?.cwd).toBe(yield* fs.realPath(workspace));
186 expect(pool.ran("connect")[0]?.args).toContain(`${GATEWAY}/v1/agent-device`);
187
188 const binding = yield* ready.devices.agentEndpoint!(leaseId);
189 expect(binding).toMatchObject({
190 baseUrl: `${GATEWAY}/v1/agent-device`,
191 token: "agent-token",
192 agentDeviceId: null,
193 session: open?.args[open.args.indexOf("--session") + 1],
194 installDirectory: yield* fs.realPath(workspace),
195 });
196 expect((yield* ready.devices.list).devices.at(-1)).toMatchObject({
197 id: "lease-1",
198 name: "Pixel 9",
199 booted: true,
200 });
201
202 expect(
203 yield* ready.upstream!(
204 "/vendor/serve-sim/helper/lease-1/stream.avcc",
205 new URLSearchParams(),
206 ),
207 ).toEqual({
208 url: `${GATEWAY}/v1/leases/lease-1/stream`,
209 headers: { authorization: "Bearer agent-token" },
210 protocols: [],
211 });
212 expect(
213 yield* ready.upstream!(
214 "/vendor/serve-sim/helper/ws",
215 new URLSearchParams({ device: "lease-1" }),
216 ),
217 ).toEqual({
218 url: `${GATEWAY}/v1/leases/lease-1/input`,
219 headers: { authorization: "Bearer agent-token" },
220 protocols: [],
221 });
222 expect(
223 yield* ready.upstream!("/vendor/serve-sim/helper/lease-1/config", new URLSearchParams()),
224 ).toBeNull();
225 expect(
226 yield* ready.upstream!(
227 "/vendor/serve-sim/helper/ws",
228 new URLSearchParams({ device: "lease-2" }),
229 ),
230 ).toBeNull();
231 expect([...(yield* ready.devices.screenshot({ ...catalog[1]!, id: leaseId }))]).toEqual([
232 1, 2, 3,
233 ]);
234
235 yield* ready.devices.shutdown({ id: leaseId, platform: "android" });
236 expect(pool.ran("close")).toHaveLength(1);
237 expect((yield* ready.devices.list).devices.some((device) => device.booted)).toBe(false);
238 yield* Scope.close(scope, Exit.void);
239 expect(pool.ran("close")).toHaveLength(1);
240 }).pipe(Effect.scoped, Effect.provide(layer)),
241 );
242
243 it.effect("caps leases at the limit", () =>
244 Effect.gen(function* () {
245 const pool = yield* fakePool();
246 const scope = yield* Scope.make();
247 const host = yield* makeHost(pool, config({ maxLeases: 1 }), scope);
248 const ready = yield* host.ensureReady(() => Effect.void);
249 const [iphone] = (yield* ready.devices.list).devices;
250 yield* ready.devices.boot(iphone!);
251
252 const refused = yield* ready.devices.boot(iphone!).pipe(Effect.flip);
253 expect(refused.message).toContain("limited to 1 device");
254 expect(pool.ran("open")).toHaveLength(1);
255 yield* Scope.close(scope, Exit.void);
256 expect(pool.ran("close")).toHaveLength(1);
257 }).pipe(Effect.scoped, Effect.provide(layer)),
258 );
259
260 it.effect("closes the session of a failed open so no lease is left behind", () =>
261 Effect.gen(function* () {
262 const pool = yield* fakePool({ failOpen: true });
263 const scope = yield* Scope.make();
264 const host = yield* makeHost(pool, config(), scope);
265 const ready = yield* host.ensureReady(() => Effect.void);
266 const [iphone] = (yield* ready.devices.list).devices;
267 const failure = yield* ready.devices.boot(iphone!).pipe(Effect.flip);
268 expect(String(failure.cause)).toContain("No device matches. Retry.");
269 expect(pool.ran("close")).toHaveLength(1);
270 // The failed open freed its slot.
271 expect(yield* ready.devices.boot(iphone!).pipe(Effect.flip)).toBeDefined();
272 yield* Scope.close(scope, Exit.void);
273 }).pipe(Effect.scoped, Effect.provide(layer)),
274 );
275
276 it.effect("keeps a watched lease renewed and stops listing it once Simlock ends it", () =>
277 Effect.gen(function* () {
278 const pool = yield* fakePool();
279 const scope = yield* Scope.make();
280 const host = yield* makeHost(pool, config(), scope);
281 const ready = yield* host.ensureReady(() => Effect.void);
282 const [iphone] = (yield* ready.devices.list).devices;
283 const leaseId = yield* ready.devices.boot(iphone!);
284
285 yield* TestClock.adjust("2 minutes");
286 expect(pool.requests).toContain(`POST /v1/leases/${leaseId}/renew`);
287 expect((yield* ready.devices.list).devices.some((device) => device.id === leaseId)).toBe(
288 true,
289 );
290
291 pool.endLeases();
292 yield* TestClock.adjust("2 minutes");
293 expect((yield* ready.devices.list).devices.some((device) => device.id === leaseId)).toBe(
294 false,
295 );
296 yield* Scope.close(scope, Exit.void);
297 expect(pool.ran("close")).toHaveLength(0);
298 }).pipe(Effect.scoped, Effect.provide(layer)),
299 );
300
301 it.effect("returns a lease whose open finishes after the host stopped", () =>
302 Effect.gen(function* () {
303 const holdOpen = {
304 entered: yield* Deferred.make<void>(),
305 proceed: yield* Deferred.make<void>(),
306 };
307 const pool = yield* fakePool({ holdOpen });
308 const host = yield* makeHost(pool, config(), yield* Scope.make());
309 const ready = yield* host.ensureReady(() => Effect.void);
310 const [iphone] = (yield* ready.devices.list).devices;
311 const opening = yield* Effect.forkChild(ready.devices.boot(iphone!));
312 yield* Deferred.await(holdOpen.entered);
313 yield* host.stop;
314 yield* Deferred.succeed(holdOpen.proceed, undefined);
315 expect(Exit.isFailure(yield* Fiber.await(opening))).toBe(true);
316 expect(pool.ran("close")).toHaveLength(1);
317 expect((yield* ready.devices.list).devices.every((device) => !device.booted)).toBe(true);
318 }).pipe(Effect.scoped, Effect.provide(layer)),
319 );
320
321 it.effect("holds a lease for its full maximum age, then returns it", () =>
322 Effect.gen(function* () {
323 const pool = yield* fakePool();
324 const host = yield* makeHost(pool, config({ maxLeaseMinutes: 5 }), yield* Scope.make());
325 const ready = yield* host.ensureReady(() => Effect.void);
326 const [iphone] = (yield* ready.devices.list).devices;
327 yield* ready.devices.boot(iphone!);
328
329 yield* TestClock.adjust("299 seconds");
330 expect(pool.ran("close")).toHaveLength(0);
331 yield* TestClock.adjust("1 second");
332 expect(pool.ran("close")).toHaveLength(1);
333 }).pipe(Effect.scoped, Effect.provide(layer)),
334 );
335});