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

SimlockDeviceHost.test.ts

470 lines18.5 KB

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