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