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

McpDeviceToolkit.test.ts

723 lines27.1 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import {
4 DeviceHostUnavailableError,
5 DeviceId,
6 EnvironmentId,
7 ProviderInstanceId,
8 ThreadId,
9} from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import { McpSchema, McpServer } from "effect/ai";
14​
15import * as ServerConfig from "../config.ts";
16import * as DeviceService from "../device/DeviceService.ts";
17import * as ProjectService from "../project/ProjectService.ts";
18import * as McpHttpServer from "./McpHttpServer.ts";
19import * as McpInvocationContext from "./McpInvocationContext.ts";
20import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts";
21​
22const environmentId = EnvironmentId.make("environment-device-test");
23const threadId = ThreadId.make("thread-device-test");
24const invocation = (capabilities: ReadonlyArray<McpInvocationContext.McpCapability>) => ({
25 environmentId,
26 requestNamespace: "provider-session-device-test",
27 thread: {
28 threadId,
29 providerSessionId: "provider-session-device-test",
30 providerInstanceId: ProviderInstanceId.make("codex"),
31 },
32 client: undefined,
33 capabilities: new Set(capabilities),
34 issuedAt: 1,
35});
36const client = McpSchema.McpServerClient.of({
37 clientId: 1,
38 clientCapabilities: {},
39 clientInfo: { name: "mcp-test", version: "1.0.0" },
40 protocolVersion: "2025-06-18",
41 initializePayload: {
42 protocolVersion: "2025-06-18",
43 capabilities: {},
44 clientInfo: { name: "mcp-test", version: "1.0.0" },
45 },
46 getClient: Effect.die("unused"),
47});
48​
49const device = {
50 hostId: "local",
51 id: "UDID-1",
52 platform: "ios" as const,
53 name: "iPhone 17 Pro",
54 version: "iOS 27.0",
55 booted: true,
56 physical: false,
57};
58const state = {
59 hosts: [
60 {
61 id: "local",
62 kind: "local" as const,
63 label: "This machine",
64 platforms: [
65 { platform: "ios" as const, available: true },
66 { platform: "android" as const, available: false, reason: "No SDK" },
67 ],
68 hubInstalled: true,
69 agentDeviceInstalled: true,
70 },
71 ],
72 hostStatus: "ready" as const,
73 hostStatuses: { local: { status: "ready" as const } },
74 devices: [device],
75 sessions: [],
76 onboardingCompleted: true,
77 agentAccessEnabled: true,
78 hubBasePath: "/api/device-hub",
79 revision: 1,
80};
81const png = new Uint8Array(24);
82new DataView(png.buffer).setUint32(0, 0x89504e47);
83new DataView(png.buffer).setUint32(4, 0x0d0a1a0a);
84new DataView(png.buffer).setUint32(12, 0x49484452);
85new DataView(png.buffer).setUint32(16, 1206);
86new DataView(png.buffer).setUint32(20, 2622);
87​
88const unused = Effect.die("not used");
89const readiness = {
90 hostId: "local",
91 nodePath: process.execPath,
92 hub: { origin: "http://hub.test" },
93 devices: {
94 list: unused,
95 boot: () => unused,
96 attach: () => unused,
97 shutdown: () => unused,
98 screenshot: () => unused,
99 },
100 run: () => unused,
101 helpers: { serveSimAxSettings: null, serveSimCli: null },
102 agentDevice: null,
103};
104const layerProjectsMock = Layer.mock(ProjectService.ProjectService)({
105 getById: () => Effect.succeedNone,
106});
107​
108const openSession = {
109 threadId,
110 hostId: "local",
111 deviceId: DeviceId.make("UDID-1"),
112 platform: "ios" as const,
113 openedAt: "2026-09-08T00:00:00.000Z",
114};
115const layerDeviceServiceMock = Layer.mock(DeviceService.DeviceService)({
116 state: Effect.succeed(state),
117 list: Effect.succeed(state),
118 agentReadinessIfSupported: () => Effect.succeed(readiness),
119 open: (input) =>
120 Effect.succeed({
121 threadId: input.threadId,
122 hostId: "local",
123 deviceId: input.deviceId,
124 platform: input.platform,
125 openedAt: "2026-09-08T00:00:00.000Z",
126 }),
127​
128 sessionsForThread: (id) => Effect.succeed(id === threadId ? [openSession] : []),
129 locateSession: (input) =>
130 Effect.succeed(
131 input.threadId === threadId && input.deviceId === openSession.deviceId
132 ? Option.some(openSession)
133 : Option.none(),
134 ),
135 screenshot: () => Effect.succeed({ device, png }),
136 close: () => Effect.void,
137 testHost: () => Effect.die("not used"),
138 // As for an Expo device, agent-device knows the device by a different id than T3.
139 agentTarget: () =>
140 Effect.succeed({
141 agentDeviceId: "SIM-UDID",
142 session: "thread-device",
143 args: ["--config", "/host.json", "--session", "thread-device"],
144 }),
145 agentLauncher: ({ targetArgs }) =>
146 Effect.succeedSome(`/state/device/targets/thread-device/${targetArgs.join("_")}/agent-device`),
147});
148​
149const layerTest = McpHttpServer.layerDeviceToolkit.pipe(
150 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
151 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
152 Layer.provideMerge(layerDeviceServiceMock),
153 Layer.provide(layerProjectsMock),
154 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-device-toolkit-test-" })),
155 Layer.provide(NodeServices.layer),
156);
157​
158it.effect("registers the device tools and returns the screenshot as image content", () =>
159 Effect.scoped(
160 Effect.gen(function* () {
161 const server = yield* McpServer.McpServer;
162 const names = server.tools.map(({ tool }) => tool.name).toSorted();
163 expect(names).toEqual(["device_close", "device_list", "device_open", "device_screenshot"]);
164​
165 const callWith = (capabilities: ReadonlyArray<McpInvocationContext.McpCapability>) =>
166 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(capabilities));
167​
168 const opened = yield* server
169 .callTool({ name: "device_open", arguments: { platform: "ios" } })
170 .pipe(callWith(["device"]), Effect.provideService(McpSchema.McpServerClient, client));
171 expect(opened.isError).toBe(false);
172 const openedContent = opened.structuredContent as {
173 agentDevice: { command: string; targetArgs: ReadonlyArray<string>; session: string };
174 quickStart: string;
175 };
176 // Callers that pass the target flags, like test-t3-mobile's pair-client.sh, keep working.
177 expect(openedContent.agentDevice).toMatchObject({
178 targetArgs: [
179 "--platform",
180 "ios",
181 "--udid",
182 "SIM-UDID",
183 "--config",
184 "/host.json",
185 "--session",
186 "thread-device",
187 ],
188 session: "thread-device",
189 });
190 expect(openedContent.quickStart).toContain(
191 `${openedContent.agentDevice.command} snapshot -i`,
192 );
193 // The launcher selects the device by agent-device's id for it, not T3's.
194 expect(openedContent.agentDevice.command).toBe(
195 "/state/device/targets/thread-device/--platform_ios_--udid_SIM-UDID_--config_/host.json_--session_thread-device/agent-device",
196 );
197​
198 const shot = yield* server
199 .callTool({ name: "device_screenshot", arguments: { deviceId: "UDID-1" } })
200 .pipe(callWith(["device"]), Effect.provideService(McpSchema.McpServerClient, client));
201 expect(shot.isError).toBe(false);
202 expect(shot.content.map((entry) => entry.type)).toEqual(["text", "image"]);
203 expect(shot.structuredContent).toMatchObject({
204 screenshot: { mimeType: "image/png", width: 1206, height: 2622 },
205 });
206​
207 const foreign = yield* server
208 .callTool({ name: "device_screenshot", arguments: { deviceId: "UDID-2" } })
209 .pipe(callWith(["device"]), Effect.provideService(McpSchema.McpServerClient, client));
210 expect(foreign.isError).toBe(true);
211 expect(foreign.content.map((entry) => entry.type)).toEqual(["text"]);
212​
213 const listed = yield* server
214 .callTool({ name: "device_list", arguments: { hostId: "THIS MACHINE" } })
215 .pipe(callWith(["device"]), Effect.provideService(McpSchema.McpServerClient, client));
216 expect(listed.structuredContent).toMatchObject({
217 hosts: [{ id: "local" }],
218 devices: [device],
219 });
220​
221 const unknownHost = yield* server
222 .callTool({ name: "device_screenshot", arguments: { hostId: "oliverMac" } })
223 .pipe(callWith(["device"]), Effect.provideService(McpSchema.McpServerClient, client));
224 expect(unknownHost.isError).toBe(true);
225 expect(unknownHost.content).toEqual([
226 { type: "text", text: "No device host oliverMac. Known hosts: This machine (local)." },
227 ]);
228​
229 const denied = yield* server
230 .callTool({ name: "device_list", arguments: {} })
231 .pipe(callWith(["preview"]), Effect.provideService(McpSchema.McpServerClient, client));
232 expect(denied.isError).toBe(true);
233 // The agent can't see Settings, and a running session keeps the capabilities it started with,
234 // so the error says where the user turns access on and when it applies.
235 expect(denied.content).toEqual([
236 {
237 type: "text",
238 text: "Agent device access is turned off for this environment. Ask the user to turn on the Device hub and Agent device access in Settings > Integrations > Devices; it applies when the agent session next starts, such as in a new thread.",
239 },
240 ]);
241 }),
242 ).pipe(Effect.provide(layerTest)),
243);
244​
245it.effect("rejects unavailable agent access before booting or opening a device", () => {
246 const layerUnavailable = Layer.mock(DeviceService.DeviceService)({
247 list: Effect.succeed(state),
248 agentReadinessIfSupported: () =>
249 Effect.fail(
250 new DeviceHostUnavailableError({ hostId: "local", reason: "Agent access is disabled." }),
251 ),
252 open: () => Effect.die("Must not boot or register a device when agent access fails"),
253 });
254 return Effect.gen(function* () {
255 const server = yield* McpServer.McpServer;
256 const result = yield* server
257 .callTool({ name: "device_open", arguments: { platform: "ios" } })
258 .pipe(
259 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(["device"])),
260 Effect.provideService(McpSchema.McpServerClient, client),
261 );
262 expect(result.isError).toBe(true);
263 expect(result.content).toEqual(
264 expect.arrayContaining([
265 expect.objectContaining({
266 type: "text",
267 text: expect.stringContaining("Agent access is disabled."),
268 }),
269 ]),
270 );
271 }).pipe(
272 Effect.scoped,
273 Effect.provide(
274 McpHttpServer.layerDeviceToolkit.pipe(
275 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
276 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
277 Layer.provide(layerUnavailable),
278 Layer.provide(layerProjectsMock),
279 Layer.provide(
280 ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-device-toolkit-test-" }),
281 ),
282 Layer.provide(NodeServices.layer),
283 ),
284 ),
285 );
286});
287​
288it.effect("device_open reports a failed host's setup error instead of no devices", () => {
289 const failure = "Device support failed: npm was not found. Install Node.js, which includes npm.";
290 const failedState = {
291 ...state,
292 hostStatus: "failed" as const,
293 hostStatusDetail: failure,
294 hostStatuses: { local: { status: "failed" as const, detail: failure } },
295 devices: [],
296 };
297 const layerFailed = Layer.mock(DeviceService.DeviceService)({
298 state: Effect.succeed(failedState),
299 list: Effect.succeed(failedState),
300 locateDevice: () => Effect.succeedNone,
301 open: () => Effect.die("Must not open a device on a host whose setup failed"),
302 });
303 return Effect.gen(function* () {
304 const server = yield* McpServer.McpServer;
305 for (const args of [
306 { platform: "android" },
307 { deviceId: "Pixel_API_35", hostId: "local" },
308 { deviceId: "Pixel_API_35" },
309 ]) {
310 const result = yield* server
311 .callTool({ name: "device_open", arguments: args })
312 .pipe(
313 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(["device"])),
314 Effect.provideService(McpSchema.McpServerClient, client),
315 );
316 const text = result.content
317 .flatMap((entry) => (entry.type === "text" ? [entry.text] : []))
318 .join("\n");
319 expect(result.isError).toBe(true);
320 expect(text).not.toContain("No android devices were found");
321 expect(text).toContain(failure);
322 }
323 }).pipe(
324 Effect.scoped,
325 Effect.provide(
326 McpHttpServer.layerDeviceToolkit.pipe(
327 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
328 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
329 Layer.provide(layerFailed),
330 Layer.provide(layerProjectsMock),
331 Layer.provide(
332 ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-device-toolkit-test-" }),
333 ),
334 Layer.provide(NodeServices.layer),
335 ),
336 ),
337 );
338});
339​
340describe("device targeting across hosts", () => {
341 const macHost = {
342 id: "mac-mini",
343 kind: "ssh" as const,
344 label: "Mac Mini",
345 platforms: [
346 { platform: "ios" as const, available: true },
347 { platform: "android" as const, available: true },
348 ],
349 hubInstalled: true,
350 agentDeviceInstalled: true,
351 };
352 const macIphone = { ...device, hostId: "mac-mini", id: "MAC-UDID" };
353 const localPixel = {
354 hostId: "local",
355 id: "Pixel_10",
356 platform: "android" as const,
357 name: "Pixel 10",
358 version: "Android 16",
359 booted: false,
360 physical: false,
361 };
362 const macPixel = { ...localPixel, hostId: "mac-mini" };
363 const multiHostState = {
364 ...state,
365 hosts: [...state.hosts, macHost],
366 hostStatuses: {
367 local: { status: "ready" as const },
368 "mac-mini": { status: "ready" as const },
369 },
370 devices: [device, macIphone, localPixel, macPixel],
371 };
372 const session = (hostId: string, deviceId: string, platform: "ios" | "android") => ({
373 threadId,
374 hostId,
375 deviceId: DeviceId.make(deviceId),
376 platform,
377 openedAt: "2026-09-08T00:00:00.000Z",
378 });
379 const thisMachine = { id: "local", label: "This machine" };
380 const macMini = { id: macHost.id, label: macHost.label };
381 // DeviceService's lookup errors; DeviceService.test.ts covers when each arises.
382 const onTwoHosts = new DeviceService.DeviceHostAmbiguousError({
383 deviceId: DeviceId.make("Pixel_10"),
384 hosts: [thisMachine, macMini],
385 });
386 const onTheMac = new DeviceService.DeviceOnOtherHostError({
387 deviceId: DeviceId.make("MAC-UDID"),
388 host: thisMachine,
389 hosts: [macMini],
390 });
391​
392 const run = <A, E>(
393 sessions: ReadonlyArray<ReturnType<typeof session>>,
394 program: (calls: {
395 readonly opened: Array<{ hostId: string; deviceId: string }>;
396 readonly closed: Array<{ hostId?: string | undefined; deviceId?: string | undefined }>;
397 readonly call: (
398 name: string,
399 args: Record<string, unknown>,
400 ) => Effect.Effect<McpSchema.CallToolResult, McpSchema.McpErrorBase, McpServer.McpServer>;
401 }) => Effect.Effect<A, E, McpServer.McpServer>,
402 overrides: Partial<DeviceService.DeviceService["Service"]> = {},
403 ) => {
404 const opened: Array<{ hostId: string; deviceId: string }> = [];
405 const closed: Array<{ hostId?: string | undefined; deviceId?: string | undefined }> = [];
406 const layerDevices = Layer.mock(DeviceService.DeviceService)({
407 state: Effect.succeed(multiHostState),
408 list: Effect.succeed({ ...multiHostState, sessions }),
409 agentReadinessIfSupported: () => Effect.succeed(readiness),
410 open: (input) =>
411 Effect.sync(() => {
412 opened.push({ hostId: input.hostId ?? "local", deviceId: input.deviceId });
413 return session(input.hostId ?? "local", input.deviceId, input.platform);
414 }),
415 sessionsForThread: () => Effect.succeed(sessions),
416 locateDevice: (input) =>
417 Effect.succeed(
418 Option.fromUndefinedOr(
419 multiHostState.devices.find(
420 (candidate) =>
421 candidate.id === input.deviceId &&
422 (input.hostId === undefined || candidate.hostId === input.hostId),
423 ),
424 ),
425 ),
426 locateSession: (input) =>
427 Effect.succeed(
428 Option.fromUndefinedOr(
429 sessions.find(
430 (candidate) =>
431 candidate.deviceId === input.deviceId &&
432 (input.hostId === undefined || candidate.hostId === input.hostId),
433 ),
434 ),
435 ),
436 screenshot: (target) =>
437 Effect.succeed({
438 device:
439 multiHostState.devices.find(
440 (candidate) => candidate.hostId === target.hostId && candidate.id === target.deviceId,
441 ) ?? device,
442 png,
443 }),
444 close: (input) =>
445 Effect.sync(() => {
446 closed.push({ hostId: input.hostId, deviceId: input.deviceId });
447 }),
448 agentTarget: () =>
449 Effect.succeed({
450 agentDeviceId: "MAC-UDID",
451 session: "thread-device",
452 args: ["--config", "/mac.json", "--session", "thread-device"],
453 }),
454 agentLauncher: () => Effect.succeedSome("/state/device/targets/thread-device/agent-device"),
455 ...overrides,
456 });
457 const call = (name: string, args: Record<string, unknown>) =>
458 McpServer.McpServer.pipe(
459 Effect.flatMap((server) => server.callTool({ name, arguments: args })),
460 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(["device"])),
461 Effect.provideService(McpSchema.McpServerClient, client),
462 );
463 return program({ opened, closed, call }).pipe(
464 Effect.scoped,
465 Effect.provide(
466 McpHttpServer.layerDeviceToolkit.pipe(
467 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
468 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
469 Layer.provide(layerDevices),
470 Layer.provide(layerProjectsMock),
471 Layer.provide(
472 ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-device-toolkit-test-" }),
473 ),
474 Layer.provide(NodeServices.layer),
475 ),
476 ),
477 );
478 };
479 const text = (result: McpSchema.CallToolResult) =>
480 result.content.flatMap((entry) => (entry.type === "text" ? [entry.text] : [])).join("\n");
481​
482 const localOpen = { hostId: device.hostId, deviceId: device.id };
483 const macOpen = { hostId: macIphone.hostId, deviceId: macIphone.id };
484​
485 it.effect.each([
486 { selection: "without a host filter", args: {}, open: [localOpen, macOpen] },
487 { selection: "by host label", args: { hostId: "MAC MINI" }, open: [macOpen] },
488 { selection: "by host id", args: { hostId: "local" }, open: [localOpen] },
489 ])("lists open devices for the current thread $selection", ({ args, open }) =>
490 run(
491 [
492 openSession,
493 session(macIphone.hostId, macIphone.id, macIphone.platform),
494 {
495 ...session(macPixel.hostId, macPixel.id, macPixel.platform),
496 threadId: ThreadId.make("other-thread"),
497 },
498 ],
499 ({ call }) =>
500 Effect.gen(function* () {
501 const result = yield* call("device_list", args);
502 expect(result.structuredContent).toHaveProperty("open", open);
503 }),
504 ),
505 );
506​
507 it.effect("opens a device id that exists only on another host", () =>
508 run([], ({ opened, call }) =>
509 Effect.gen(function* () {
510 const result = yield* call("device_open", { deviceId: "MAC-UDID" });
511 const byLabel = yield* call("device_open", { platform: "ios", hostId: "MAC MINI" });
512 expect(byLabel.isError).toBe(false);
513 expect(text(result)).not.toContain("No device");
514 expect(result.isError).toBe(false);
515 expect(opened).toEqual([
516 { hostId: "mac-mini", deviceId: "MAC-UDID" },
517 { hostId: "mac-mini", deviceId: "MAC-UDID" },
518 ]);
519 }),
520 ),
521 );
522​
523 it.effect("binds the launcher to the id the device booted with", () => {
524 const targets: Array<string> = [];
525 return run(
526 [],
527 ({ call }) =>
528 Effect.gen(function* () {
529 const result = yield* call("device_open", { deviceId: "Pixel_10", hostId: "mac-mini" });
530 expect(result.isError).toBe(false);
531 expect(targets).toEqual(["emulator-5554", "emulator-5554"]);
532 }),
533 {
534 open: (input) =>
535 Effect.succeed(session(input.hostId ?? "local", "emulator-5554", "android")),
536 agentTarget: (target) =>
537 Effect.sync(() => {
538 targets.push(target.deviceId);
539 return { agentDeviceId: target.deviceId, session: "thread-device", args: [] };
540 }),
541 agentLauncher: (target) =>
542 Effect.sync(() => {
543 targets.push(target.deviceId);
544 return Option.some("/state/device/targets/thread-device/agent-device");
545 }),
546 },
547 );
548 });
549​
550 it.effect("says a device closed during device_open was closed, not that its host is down", () =>
551 run(
552 [],
553 ({ call }) =>
554 Effect.gen(function* () {
555 const result = yield* call("device_open", { deviceId: "MAC-UDID" });
556 expect(result.isError).toBe(true);
557 expect(text(result)).toBe(
558 "The device was closed while device_open was preparing it. Call device_open again only if you still need it.",
559 );
560 }),
561 { agentLauncher: () => Effect.succeedNone },
562 ),
563 );
564​
565 it.effect("refuses a device id that exists on two hosts and names both", () =>
566 run(
567 [],
568 ({ opened, call }) =>
569 Effect.gen(function* () {
570 const result = yield* call("device_open", { deviceId: "Pixel_10" });
571 expect(result.isError).toBe(true);
572 expect(text(result)).toContain("hostId local");
573 expect(text(result)).toContain("hostId mac-mini");
574 expect(text(result)).toBe(
575 "Device Pixel_10 is on more than one host: 'This machine' (hostId local), 'Mac Mini' (hostId mac-mini). Pass hostId.",
576 );
577 expect(opened).toEqual([]);
578 }),
579 { locateDevice: () => Effect.fail(onTwoHosts) },
580 ),
581 );
582​
583 it.effect("keeps an explicit hostId and says which host has the device", () =>
584 run(
585 [],
586 ({ opened, call }) =>
587 Effect.gen(function* () {
588 const result = yield* call("device_open", { deviceId: "MAC-UDID", hostId: "local" });
589 expect(result.isError).toBe(true);
590 expect(text(result)).toContain("hostId mac-mini");
591 expect(text(result)).toBe(
592 "Device MAC-UDID is not on 'This machine' (hostId local). It is on 'Mac Mini' (hostId mac-mini); pass that hostId.",
593 );
594 expect(opened).toEqual([]);
595 }),
596 { locateDevice: () => Effect.fail(onTheMac) },
597 ),
598 );
599​
600 it.effect("says no host has a device id, naming the host it was asked on", () =>
601 run([], ({ opened, call }) =>
602 Effect.gen(function* () {
603 const missing = (args: Record<string, unknown>) =>
604 call("device_open", { deviceId: "Pixel_9", ...args }).pipe(Effect.map(text));
605 expect(yield* missing({})).toBe(
606 "No device Pixel_9 on any host. Call device_list for current ids.",
607 );
608 expect(yield* missing({ hostId: "mac-mini" })).toBe(
609 "No device Pixel_9 on 'Mac Mini' (hostId mac-mini). Call device_list for current ids.",
610 );
611 expect(yield* missing({ hostId: "unknown-host" })).toBe(
612 "No device host unknown-host. Known hosts: This machine (local), Mac Mini (mac-mini).",
613 );
614 expect(opened).toEqual([]);
615 }),
616 ),
617 );
618​
619 it.effect("screenshots an open device by id on whichever host it is on", () =>
620 run([session("mac-mini", "MAC-UDID", "ios")], ({ call }) =>
621 Effect.gen(function* () {
622 const result = yield* call("device_screenshot", { deviceId: "MAC-UDID" });
623 expect(result.isError).toBe(false);
624 expect(result.structuredContent).toMatchObject({ device: { hostId: "mac-mini" } });
625 const byLabel = yield* call("device_screenshot", { hostId: "MAC MINI" });
626 expect(byLabel.isError).toBe(false);
627 expect(byLabel.structuredContent).toMatchObject({ device: { hostId: "mac-mini" } });
628 }),
629 ),
630 );
631​
632 it.effect("says why device_screenshot failed instead of a generic error", () =>
633 run(
634 [session("mac-mini", "MAC-UDID", "ios")],
635 ({ call }) =>
636 Effect.gen(function* () {
637 const wrongHost = yield* call("device_screenshot", {
638 deviceId: "MAC-UDID",
639 hostId: "local",
640 });
641 expect(wrongHost.isError).toBe(true);
642 expect(text(wrongHost)).toContain("It is on 'Mac Mini' (hostId mac-mini)");
643 expect(text(wrongHost)).toBe(
644 "Device MAC-UDID is not on 'This machine' (hostId local). It is on 'Mac Mini' (hostId mac-mini); pass that hostId.",
645 );
646 }),
647 { locateSession: () => Effect.fail(onTheMac) },
648 ),
649 );
650​
651 it.effect("names a device_screenshot argument the tool does not declare", () =>
652 run([session("mac-mini", "MAC-UDID", "ios")], ({ call }) =>
653 Effect.gen(function* () {
654 const result = yield* call("device_screenshot", {
655 deviceId: "MAC-UDID",
656 includeImage: false,
657 });
658 expect(result.isError).toBe(true);
659 expect(text(result)).toContain('Unknown argument "includeImage"');
660 }),
661 ),
662 );
663​
664 it.effect("tells an agent to open a device id before screenshotting it", () =>
665 run([], ({ call }) =>
666 Effect.gen(function* () {
667 const result = yield* call("device_screenshot", { deviceId: "MAC-UDID" });
668 expect(result.isError).toBe(true);
669 expect(text(result)).toBe(
670 "Device MAC-UDID is not open in this thread. Call device_open first.",
671 );
672 }),
673 ),
674 );
675​
676 it.effect("tells an agent with no open device to call device_open before a screenshot", () =>
677 run([], ({ call }) =>
678 Effect.gen(function* () {
679 const result = yield* call("device_screenshot", {});
680 expect(result.isError).toBe(true);
681 expect(text(result)).toBe("No device is open in this thread. Call device_open first.");
682 expect(result.structuredContent).toMatchObject({
683 error: { _tag: "DeviceToolUnavailableError" },
684 });
685 }),
686 ),
687 );
688​
689 it.effect("refuses to close an id open on two hosts instead of closing both", () =>
690 run(
691 [session("local", "Pixel_10", "android"), session("mac-mini", "Pixel_10", "android")],
692 ({ closed, call }) =>
693 Effect.gen(function* () {
694 const result = yield* call("device_close", { deviceId: "Pixel_10" });
695 expect(result.isError).toBe(true);
696 expect(text(result)).toContain("hostId mac-mini");
697 expect(text(result)).toBe(
698 "Device Pixel_10 is on more than one host: 'This machine' (hostId local), 'Mac Mini' (hostId mac-mini). Pass hostId.",
699 );
700 expect(closed).toEqual([]);
701 }),
702 { locateSession: () => Effect.fail(onTwoHosts) },
703 ),
704 );
705​
706 it.effect("closes an open device on its host and treats an unopened one as closed", () =>
707 run([session("mac-mini", "MAC-UDID", "ios")], ({ closed, call }) =>
708 Effect.gen(function* () {
709 expect((yield* call("device_close", { deviceId: "MAC-UDID" })).isError).toBe(false);
710 expect((yield* call("device_close", { deviceId: "Pixel_9" })).isError).toBe(false);
711 expect((yield* call("device_close", { hostId: "MAC MINI" })).isError).toBe(false);
712 const unknown = yield* call("device_close", { hostId: "unknown-host" });
713 expect(unknown.isError).toBe(true);
714 expect(text(unknown)).toContain("No device host unknown-host.");
715 expect(closed).toEqual([
716 { hostId: "mac-mini", deviceId: "MAC-UDID" },
717 { hostId: undefined, deviceId: "Pixel_9" },
718 { hostId: "mac-mini", deviceId: undefined },
719 ]);
720 }),
721 ),
722 );
723});