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

McpDeviceToolkit.test.ts

608 lines22.3 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 EAS 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(McpServer.McpServer.layer),
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 denied = yield* server
214 .callTool({ name: "device_list", arguments: {} })
215 .pipe(callWith(["preview"]), Effect.provideService(McpSchema.McpServerClient, client));
216 expect(denied.isError).toBe(true);
217 // The agent can't see Settings, and a running session keeps the capabilities it started with,
218 // so the error says where the user turns access on and when it applies.
219 expect(denied.content).toEqual([
220 {
221 type: "text",
222 text: "Agent device access is turned off for this environment. Ask the user to turn on Agent device access in Settings > Integrations > Devices; it applies when the agent session next starts, such as in a new thread.",
223 },
224 ]);
225 }),
226 ).pipe(Effect.provide(layerTest)),
227);
228​
229it.effect("rejects unavailable agent access before booting or opening a device", () => {
230 const layerUnavailable = Layer.mock(DeviceService.DeviceService)({
231 list: Effect.succeed(state),
232 agentReadinessIfSupported: () =>
233 Effect.fail(
234 new DeviceHostUnavailableError({ hostId: "local", reason: "Agent access is disabled." }),
235 ),
236 open: () => Effect.die("Must not boot or register a device when agent access fails"),
237 });
238 return Effect.gen(function* () {
239 const server = yield* McpServer.McpServer;
240 const result = yield* server
241 .callTool({ name: "device_open", arguments: { platform: "ios" } })
242 .pipe(
243 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(["device"])),
244 Effect.provideService(McpSchema.McpServerClient, client),
245 );
246 expect(result.isError).toBe(true);
247 expect(result.content).toEqual(
248 expect.arrayContaining([
249 expect.objectContaining({
250 type: "text",
251 text: expect.stringContaining("Agent access is disabled."),
252 }),
253 ]),
254 );
255 }).pipe(
256 Effect.scoped,
257 Effect.provide(
258 McpHttpServer.layerDeviceToolkit.pipe(
259 Layer.provideMerge(McpServer.McpServer.layer),
260 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
261 Layer.provide(layerUnavailable),
262 Layer.provide(layerProjectsMock),
263 Layer.provide(
264 ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-device-toolkit-test-" }),
265 ),
266 Layer.provide(NodeServices.layer),
267 ),
268 ),
269 );
270});
271​
272describe("device targeting across hosts", () => {
273 const macHost = {
274 id: "mac-mini",
275 kind: "ssh" as const,
276 label: "Mac Mini",
277 platforms: [
278 { platform: "ios" as const, available: true },
279 { platform: "android" as const, available: true },
280 ],
281 hubInstalled: true,
282 agentDeviceInstalled: true,
283 };
284 const macIphone = { ...device, hostId: "mac-mini", id: "MAC-UDID" };
285 const localPixel = {
286 hostId: "local",
287 id: "Pixel_10",
288 platform: "android" as const,
289 name: "Pixel 10",
290 version: "Android 16",
291 booted: false,
292 physical: false,
293 };
294 const macPixel = { ...localPixel, hostId: "mac-mini" };
295 const multiHostState = {
296 ...state,
297 hosts: [...state.hosts, macHost],
298 hostStatuses: {
299 local: { status: "ready" as const },
300 "mac-mini": { status: "ready" as const },
301 },
302 devices: [device, macIphone, localPixel, macPixel],
303 };
304 const session = (hostId: string, deviceId: string, platform: "ios" | "android") => ({
305 threadId,
306 hostId,
307 deviceId: DeviceId.make(deviceId),
308 platform,
309 openedAt: "2026-09-08T00:00:00.000Z",
310 });
311 const thisMachine = { id: "local", label: "This machine" };
312 const macMini = { id: macHost.id, label: macHost.label };
313 // DeviceService's lookup errors; DeviceService.test.ts covers when each arises.
314 const onTwoHosts = new DeviceService.DeviceHostAmbiguousError({
315 deviceId: DeviceId.make("Pixel_10"),
316 hosts: [thisMachine, macMini],
317 });
318 const onTheMac = new DeviceService.DeviceOnOtherHostError({
319 deviceId: DeviceId.make("MAC-UDID"),
320 host: thisMachine,
321 hosts: [macMini],
322 });
323​
324 const run = <A, E>(
325 sessions: ReadonlyArray<ReturnType<typeof session>>,
326 program: (calls: {
327 readonly opened: Array<{ hostId: string; deviceId: string }>;
328 readonly closed: Array<{ hostId?: string | undefined; deviceId?: string | undefined }>;
329 readonly call: (
330 name: string,
331 args: Record<string, unknown>,
332 ) => Effect.Effect<
333 McpSchema.CallToolResult,
334 McpSchema.InternalError | McpSchema.InvalidParams,
335 McpServer.McpServer
336 >;
337 }) => Effect.Effect<A, E, McpServer.McpServer>,
338 overrides: Partial<DeviceService.DeviceService["Service"]> = {},
339 ) => {
340 const opened: Array<{ hostId: string; deviceId: string }> = [];
341 const closed: Array<{ hostId?: string | undefined; deviceId?: string | undefined }> = [];
342 const layerDevices = Layer.mock(DeviceService.DeviceService)({
343 state: Effect.succeed(multiHostState),
344 list: Effect.succeed(multiHostState),
345 agentReadinessIfSupported: () => Effect.succeed(readiness),
346 open: (input) =>
347 Effect.sync(() => {
348 opened.push({ hostId: input.hostId ?? "local", deviceId: input.deviceId });
349 return session(input.hostId ?? "local", input.deviceId, input.platform);
350 }),
351 sessionsForThread: () => Effect.succeed(sessions),
352 locateDevice: (input) =>
353 Effect.succeed(
354 Option.fromUndefinedOr(
355 multiHostState.devices.find(
356 (candidate) =>
357 candidate.id === input.deviceId &&
358 (input.hostId === undefined || candidate.hostId === input.hostId),
359 ),
360 ),
361 ),
362 locateSession: (input) =>
363 Effect.succeed(
364 Option.fromUndefinedOr(
365 sessions.find(
366 (candidate) =>
367 candidate.deviceId === input.deviceId &&
368 (input.hostId === undefined || candidate.hostId === input.hostId),
369 ),
370 ),
371 ),
372 screenshot: (target) =>
373 Effect.succeed({
374 device:
375 multiHostState.devices.find(
376 (candidate) => candidate.hostId === target.hostId && candidate.id === target.deviceId,
377 ) ?? device,
378 png,
379 }),
380 close: (input) =>
381 Effect.sync(() => {
382 closed.push({ hostId: input.hostId, deviceId: input.deviceId });
383 }),
384 agentTarget: () =>
385 Effect.succeed({
386 agentDeviceId: "MAC-UDID",
387 session: "thread-device",
388 args: ["--config", "/mac.json", "--session", "thread-device"],
389 }),
390 agentLauncher: () => Effect.succeedSome("/state/device/targets/thread-device/agent-device"),
391 ...overrides,
392 });
393 const call = (name: string, args: Record<string, unknown>) =>
394 McpServer.McpServer.pipe(
395 Effect.flatMap((server) => server.callTool({ name, arguments: args })),
396 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(["device"])),
397 Effect.provideService(McpSchema.McpServerClient, client),
398 );
399 return program({ opened, closed, call }).pipe(
400 Effect.scoped,
401 Effect.provide(
402 McpHttpServer.layerDeviceToolkit.pipe(
403 Layer.provideMerge(McpServer.McpServer.layer),
404 Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
405 Layer.provide(layerDevices),
406 Layer.provide(layerProjectsMock),
407 Layer.provide(
408 ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-device-toolkit-test-" }),
409 ),
410 Layer.provide(NodeServices.layer),
411 ),
412 ),
413 );
414 };
415 const text = (result: McpSchema.CallToolResult) =>
416 result.content.flatMap((entry) => (entry.type === "text" ? [entry.text] : [])).join("\n");
417​
418 it.effect("opens a device id that exists only on another host", () =>
419 run([], ({ opened, call }) =>
420 Effect.gen(function* () {
421 const result = yield* call("device_open", { deviceId: "MAC-UDID" });
422 expect(text(result)).not.toContain("No device");
423 expect(result.isError).toBe(false);
424 expect(opened).toEqual([{ hostId: "mac-mini", deviceId: "MAC-UDID" }]);
425 }),
426 ),
427 );
428​
429 it.effect("binds the launcher to the id the device booted with", () => {
430 const targets: Array<string> = [];
431 return run(
432 [],
433 ({ call }) =>
434 Effect.gen(function* () {
435 const result = yield* call("device_open", { deviceId: "Pixel_10", hostId: "mac-mini" });
436 expect(result.isError).toBe(false);
437 expect(targets).toEqual(["emulator-5554", "emulator-5554"]);
438 }),
439 {
440 open: (input) =>
441 Effect.succeed(session(input.hostId ?? "local", "emulator-5554", "android")),
442 agentTarget: (target) =>
443 Effect.sync(() => {
444 targets.push(target.deviceId);
445 return { agentDeviceId: target.deviceId, session: "thread-device", args: [] };
446 }),
447 agentLauncher: (target) =>
448 Effect.sync(() => {
449 targets.push(target.deviceId);
450 return Option.some("/state/device/targets/thread-device/agent-device");
451 }),
452 },
453 );
454 });
455​
456 it.effect("says a device closed during device_open was closed, not that its host is down", () =>
457 run(
458 [],
459 ({ call }) =>
460 Effect.gen(function* () {
461 const result = yield* call("device_open", { deviceId: "MAC-UDID" });
462 expect(result.isError).toBe(true);
463 expect(text(result)).toBe(
464 "The device was closed while device_open was preparing it. Call device_open again only if you still need it.",
465 );
466 }),
467 { agentLauncher: () => Effect.succeedNone },
468 ),
469 );
470​
471 it.effect("refuses a device id that exists on two hosts and names both", () =>
472 run(
473 [],
474 ({ opened, call }) =>
475 Effect.gen(function* () {
476 const result = yield* call("device_open", { deviceId: "Pixel_10" });
477 expect(result.isError).toBe(true);
478 expect(text(result)).toContain("hostId local");
479 expect(text(result)).toContain("hostId mac-mini");
480 expect(text(result)).toBe(
481 "Device Pixel_10 is on more than one host: 'This machine' (hostId local), 'Mac Mini' (hostId mac-mini). Pass hostId.",
482 );
483 expect(opened).toEqual([]);
484 }),
485 { locateDevice: () => Effect.fail(onTwoHosts) },
486 ),
487 );
488​
489 it.effect("keeps an explicit hostId and says which host has the device", () =>
490 run(
491 [],
492 ({ opened, call }) =>
493 Effect.gen(function* () {
494 const result = yield* call("device_open", { deviceId: "MAC-UDID", hostId: "local" });
495 expect(result.isError).toBe(true);
496 expect(text(result)).toContain("hostId mac-mini");
497 expect(text(result)).toBe(
498 "Device MAC-UDID is not on 'This machine' (hostId local). It is on 'Mac Mini' (hostId mac-mini); pass that hostId.",
499 );
500 expect(opened).toEqual([]);
501 }),
502 { locateDevice: () => Effect.fail(onTheMac) },
503 ),
504 );
505​
506 it.effect("says no host has a device id, naming the host it was asked on", () =>
507 run([], ({ opened, call }) =>
508 Effect.gen(function* () {
509 const missing = (args: Record<string, unknown>) =>
510 call("device_open", { deviceId: "Pixel_9", ...args }).pipe(Effect.map(text));
511 expect(yield* missing({})).toBe(
512 "No device Pixel_9 on any host. Call device_list for current ids.",
513 );
514 expect(yield* missing({ hostId: "mac-mini" })).toBe(
515 "No device Pixel_9 on 'Mac Mini' (hostId mac-mini). Call device_list for current ids.",
516 );
517 expect(yield* missing({ hostId: "unknown-host" })).toBe(
518 "No device Pixel_9 on hostId unknown-host. Call device_list for current ids.",
519 );
520 expect(opened).toEqual([]);
521 }),
522 ),
523 );
524​
525 it.effect("screenshots an open device by id on whichever host it is on", () =>
526 run([session("mac-mini", "MAC-UDID", "ios")], ({ call }) =>
527 Effect.gen(function* () {
528 const result = yield* call("device_screenshot", { deviceId: "MAC-UDID" });
529 expect(result.isError).toBe(false);
530 expect(result.structuredContent).toMatchObject({ device: { hostId: "mac-mini" } });
531 }),
532 ),
533 );
534​
535 it.effect("says why device_screenshot failed instead of a generic error", () =>
536 run(
537 [session("mac-mini", "MAC-UDID", "ios")],
538 ({ call }) =>
539 Effect.gen(function* () {
540 const wrongHost = yield* call("device_screenshot", {
541 deviceId: "MAC-UDID",
542 hostId: "local",
543 });
544 expect(wrongHost.isError).toBe(true);
545 expect(text(wrongHost)).toContain("It is on 'Mac Mini' (hostId mac-mini)");
546 expect(text(wrongHost)).toBe(
547 "Device MAC-UDID is not on 'This machine' (hostId local). It is on 'Mac Mini' (hostId mac-mini); pass that hostId.",
548 );
549 }),
550 { locateSession: () => Effect.fail(onTheMac) },
551 ),
552 );
553​
554 it.effect("tells an agent to open a device id before screenshotting it", () =>
555 run([], ({ call }) =>
556 Effect.gen(function* () {
557 const result = yield* call("device_screenshot", { deviceId: "MAC-UDID" });
558 expect(result.isError).toBe(true);
559 expect(text(result)).toBe(
560 "Device MAC-UDID is not open in this thread. Call device_open first.",
561 );
562 }),
563 ),
564 );
565​
566 it.effect("tells an agent with no open device to call device_open before a screenshot", () =>
567 run([], ({ call }) =>
568 Effect.gen(function* () {
569 const result = yield* call("device_screenshot", {});
570 expect(result.isError).toBe(true);
571 expect(text(result)).toBe("No device is open in this thread. Call device_open first.");
572 expect(result.structuredContent).toMatchObject({
573 error: { _tag: "DeviceToolUnavailableError" },
574 });
575 }),
576 ),
577 );
578​
579 it.effect("refuses to close an id open on two hosts instead of closing both", () =>
580 run(
581 [session("local", "Pixel_10", "android"), session("mac-mini", "Pixel_10", "android")],
582 ({ closed, call }) =>
583 Effect.gen(function* () {
584 const result = yield* call("device_close", { deviceId: "Pixel_10" });
585 expect(result.isError).toBe(true);
586 expect(text(result)).toContain("hostId mac-mini");
587 expect(text(result)).toBe(
588 "Device Pixel_10 is on more than one host: 'This machine' (hostId local), 'Mac Mini' (hostId mac-mini). Pass hostId.",
589 );
590 expect(closed).toEqual([]);
591 }),
592 { locateSession: () => Effect.fail(onTwoHosts) },
593 ),
594 );
595​
596 it.effect("closes an open device on its host and treats an unopened one as closed", () =>
597 run([session("mac-mini", "MAC-UDID", "ios")], ({ closed, call }) =>
598 Effect.gen(function* () {
599 expect((yield* call("device_close", { deviceId: "MAC-UDID" })).isError).toBe(false);
600 expect((yield* call("device_close", { deviceId: "Pixel_9" })).isError).toBe(false);
601 expect(closed).toEqual([
602 { hostId: "mac-mini", deviceId: "MAC-UDID" },
603 { hostId: undefined, deviceId: "Pixel_9" },
604 ]);
605 }),
606 ),
607 );
608});