Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SimlockDeviceHost.test.ts

419 lines16.2 KB

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