Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeZlib from "node:zlib";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { assert, it } from "@effect/vitest";
6import * as Effect from "effect/Effect";
7import * as Schema from "effect/Schema";
8
9import {
10 AGENT_DEVICE_SHELL,
11 agentDeviceSessionError,
12 agentDeviceSessions,
13 describeSessions,
14 deviceFailure,
15 type LauncherTarget,
16 launcherHelp,
17 makeDeviceTools,
18 type ShellCall,
19} from "./devices.ts";
20import {
21 buildBase,
22 buildMessages,
23 cannedOutput,
24 makeSample,
25 McpToolUseCase,
26 shellRequest,
27 t3SubagentContext,
28 t3SystemAppend,
29 withDevices,
30} from "./run.ts";
31import { DeviceOperationError, LOCAL_DEVICE_HOST_ID } from "@t3tools/contracts";
32
33const MAC = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
34const IPHONE = "BBBBBBBB-BBBB-4BBB-8BBB-BBBBBBBBBBBB";
35const world = {
36 devices: [
37 {
38 hostId: MAC,
39 id: IPHONE,
40 name: "Acme iPhone",
41 platform: "ios",
42 version: "iOS 26.0",
43 booted: true,
44 physical: false,
45 },
46 ],
47 deviceHosts: { [MAC]: "build-mac" },
48};
49const screenshotFailure = {
50 _tag: "DeviceOperationError",
51 operation: "screenshot",
52 reason: "request_failed",
53 cause: null,
54};
55const decodeCase = Schema.decodeUnknownSync(McpToolUseCase);
56const deviceCase = (setup: object) =>
57 decodeCase({
58 id: "device-case",
59 area: "device-manager",
60 kind: "guard",
61 pattern: "device",
62 experience: "A device case.",
63 setup: { role: "top", world, ...setup },
64 prompt: "Show a fresh screenshot of the iPhone on build-mac.",
65 expect: {},
66 });
67const capture = JSON.parse(
68 NodeZlib.gunzipSync(
69 NodeFS.readFileSync(new URL("./templates/claude.json.gz", import.meta.url)),
70 ).toString(),
71).request.provider_native;
72const model = "claude-opus-5-5";
73const base = buildBase(capture, { model, keepUserInstructions: false });
74const json = (text: string) => JSON.parse(text);
75
76it.effect("answers device calls with T3's handlers over the case's world", () =>
77 Effect.gen(function* () {
78 const { devices, deviceHosts } = deviceCase({}).setup.world ?? {};
79 const tools = yield* makeDeviceTools({ devices: devices ?? [], deviceHosts }, base.environment);
80 const listed = json((yield* tools.call("device_list", {})).text);
81 assert.deepEqual(listed.devices, world.devices);
82 assert.deepEqual(
83 listed.hosts.map((host: { label: string }) => host.label),
84 ["This machine", "build-mac"],
85 );
86 const opened = json((yield* tools.call("device_open", { hostId: MAC, deviceId: IPHONE })).text);
87 const { command } = opened.agentDevice;
88 assert.match(command, /^\/home\/user\/\.t3\/userdata\/device\/.+\/agent-device$/);
89 assert.include(opened.quickStart, command);
90 assert.deepEqual(tools.launchers, [command]);
91 // The image never reaches the model; T3's text result has the rest.
92 assert.deepEqual(json((yield* tools.call("device_screenshot", {})).text).screenshot, {
93 mimeType: "image/png",
94 width: 1206,
95 height: 2622,
96 });
97 const failed = yield* tools.call("device_screenshot", {}, deviceFailure(screenshotFailure));
98 assert.isTrue(failed.isError);
99 assert.include(failed.text, "screenshot failed");
100 const elsewhere = yield* tools.call("device_open", { hostId: "local", deviceId: IPHONE });
101 assert.isTrue(elsewhere.isError);
102 assert.include(elsewhere.text, IPHONE);
103 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
104);
105
106it.effect("lists the boot state T3 left a device in", () =>
107 Effect.gen(function* () {
108 const { devices, deviceHosts } = deviceCase({}).setup.world ?? {};
109 const stopped = (devices ?? []).map((device) => ({ ...device, booted: false }));
110 const tools = yield* makeDeviceTools({ devices: stopped, deviceHosts }, base.environment);
111 const before = json((yield* tools.call("device_list", {})).text);
112 assert.isFalse(before.devices.find((d: { id: string }) => d.id === IPHONE).booted);
113 yield* tools.call("device_open", { hostId: MAC, deviceId: IPHONE });
114 const after = json((yield* tools.call("device_list", {})).text);
115 assert.isTrue(after.devices.find((d: { id: string }) => d.id === IPHONE).booted);
116 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
117);
118
119it("decodes only T3 device errors as injected failures", () => {
120 assert.isDefined(deviceFailure(screenshotFailure));
121 assert.isUndefined(deviceFailure({ error: "Synthetic hub is unavailable", isError: true }));
122 assert.isUndefined(deviceFailure("default"));
123});
124
125it.effect("rebuilds prior device results with T3, whose sessions reach the measured turn", () =>
126 Effect.gen(function* () {
127 const testCase = deviceCase({
128 priorTurns: [
129 { role: "user", text: "Show me Settings on the iPhone on build-mac." },
130 {
131 role: "assistant",
132 toolCalls: [
133 { tool: "device_list", input: {}, result: "default" },
134 { tool: "device_open", input: { hostId: MAC, deviceId: IPHONE }, result: "default" },
135 ],
136 },
137 ],
138 mocks: { device_screenshot: screenshotFailure },
139 });
140 const sample = makeSample(testCase, base);
141 assert.throws(() => buildMessages(sample), /run withDevices/);
142 yield* withDevices(sample);
143 const shown = JSON.stringify(buildMessages(sample));
144 const [launcher = ""] = sample.devices?.launchers ?? [];
145 assert.include(shown, launcher);
146 assert.notInclude(shown, `"content":"default"`);
147 const tools = sample.devices!;
148 assert.isFalse((yield* tools.call("device_screenshot", {})).isError);
149 const mock = deviceFailure(testCase.setup.mocks?.device_screenshot);
150 assert.isTrue((yield* tools.call("device_screenshot", {}, mock)).isError);
151 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
152);
153
154it.effect("gives a native subagent T3's SubagentStart context instead of T3's append", () =>
155 Effect.gen(function* () {
156 const subagentContext = yield* Effect.promise(() => t3SubagentContext(model));
157 const native = {
158 ...buildBase(capture, { model, keepUserInstructions: false, nativeSubagent: true }),
159 subagentContext,
160 };
161 const system = (blocks: typeof base.system) =>
162 blocks.map((block) => String(block.text)).join("");
163 assert.include(system(base.system), t3SystemAppend(model));
164 assert.notInclude(system(native.system), t3SystemAppend(model));
165 const testCase = deviceCase({ role: "native-subagent" });
166 const shown = (sample: typeof native) =>
167 buildMessages(makeSample(testCase, sample))[0]?.content.map((block) => String(block.text));
168 const reminders = shown(native)?.join("\n") ?? "";
169 // A ref without T3's hook gives the subagent nothing.
170 assert.equal(
171 reminders.includes("SubagentStart hook additional context"),
172 subagentContext !== "",
173 );
174 assert.include(reminders, subagentContext);
175 // Claude Code 2.1.310 records the hook's context after the task, and sends it that way.
176 const blocks = shown({ ...native, subagentContext: "## T3 Code devices" }) ?? [];
177 assert.equal(blocks.at(-2), testCase.prompt);
178 assert.equal(
179 blocks.at(-1),
180 "<system-reminder>\nSubagentStart hook additional context: ## T3 Code devices\n</system-reminder>",
181 );
182 }),
183);
184
185it.effect("tells the shell simulator the launchers T3 returned and agent-device's real CLI", () =>
186 Effect.gen(function* () {
187 const sample = makeSample(deviceCase({}), base);
188 yield* withDevices(sample);
189 const call = { tool: "Bash", input: { command: "ls /tmp" } };
190 const told = (request: ReturnType<typeof shellRequest>) => JSON.stringify(request.messages);
191 assert.notInclude(told(shellRequest(sample, call, "claude-haiku-5-5")), "launchers T3's");
192 const opened = yield* sample.devices!.call("device_open", { hostId: MAC, deviceId: IPHONE });
193 const { command } = json(opened.text).agentDevice;
194 const request = shellRequest(sample, call, "claude-haiku-5-5");
195 assert.include(told(request), `agent-device launchers T3's device_open returned: ${command}`);
196 // agent-device's own syntax: a positional recording path, and `record stop` with no flag.
197 assert.include(request.system, AGENT_DEVICE_SHELL);
198 assert.include(
199 request.system,
200 "agent-device record start [path] [--scope <app|device|system>]",
201 );
202 assert.include(request.system, "| record stop |");
203 assert.include(request.system, "Unknown flag: --stop. Did you mean --scope?");
204 // A case without devices keeps the shell prompt every other case has.
205 const plain = makeSample(deviceCase({ world: {} }), base);
206 assert.notInclude(shellRequest(plain, call, "claude-haiku-5-5").system, "agent-device");
207 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
208);
209
210it("prints agent-device's own help for a lone help command on a returned launcher", () => {
211 const help = (topic: string) =>
212 AGENT_DEVICE_SHELL.split(`$ agent-device help${topic ? ` ${topic}` : ""}\n`)[1]
213 ?.split("\n$ agent-device help")[0]
214 ?.trimEnd();
215 // Commands from the paired runs. The simulator once answered the first with a placeholder.
216 const launcher = "/home/user/.t3/userdata/device/bin/agent-device";
217 const target = `--platform ios --udid ${IPHONE} --config /home/user/.t3/userdata/device/hosts/303617b9730210ef3c86c52d.json --session t3-4c43aa31e607633b85e9ff2f`;
218 const asked = (command: string) => launcherHelp([launcher], command);
219 assert.match(help("") ?? "", /^agent-device <command> \[args\] \[--json\]\n/);
220 assert.equal(asked(`${launcher} help ${target}`), help(""));
221 assert.equal(asked(`${launcher} record --help ${target}`), help("record"));
222 assert.equal(asked(`${launcher} help open ${target}`), help("open"));
223 assert.equal(asked(`${launcher} --help 2>&1`), help(""));
224 assert.equal(asked(`${launcher} help settings --session=t3-1`), help("settings"));
225 // Anything else stays with the simulator: other topics, pipes, aliases, other commands.
226 assert.isUndefined(asked(`${launcher} metro --help ${target}`));
227 assert.isUndefined(asked(`${launcher} help record 2>&1 | head -40`));
228 assert.isUndefined(asked(`AD=${launcher}; $AD help record`));
229 assert.isUndefined(asked(`${launcher} snapshot -i ${target}`));
230 assert.isUndefined(asked(`/usr/local/bin/agent-device help`));
231});
232
233it("pins agent-device's help to the version T3 installs", () => {
234 const versions = JSON.parse(
235 NodeFS.readFileSync(
236 new URL("../../apps/server/src/device/deviceToolVersions.json", import.meta.url),
237 "utf8",
238 ),
239 );
240 assert.include(AGENT_DEVICE_SHELL, `agent-device ${versions["agent-device"]} prints this help`);
241});
242
243// agent-device 0.21.31's errors as a real Mac printed them (stderr, exit status 1).
244const NO_SESSION =
245 "Error (SESSION_NOT_FOUND): No active session. Run open first.\nHint: Run open first or pass an explicit device selector.";
246const APP_RECORDING_BEFORE_OPEN =
247 "Error (INVALID_ARGS): record start with app scope and an explicit session requires an active app session; run open <app> first, or use --scope device to record the full screen\nHint: Check command arguments and run --help for usage examples.";
248/** agent-device 0.21.31's snapshot-runtime-binding refusal, with the CLI's default hint. */
249const iosSnapshotRefused = (session: string) =>
250 `Error (SESSION_NOT_FOUND): iOS snapshot requires an active app session on the target device. Run open first (for example: open --session ${session} --platform ios --device "<name>" <app>).\nHint: Run open first or pass an explicit device selector.`;
251const APP_RECORDING_WITHOUT_APP =
252 "Error (UNKNOWN): App-scoped recording requires an active app session; open the app under test before recording.\nHint: Unexpected internal error. Retry with --debug and report the diagnostics log if it persists.";
253
254it.effect("answers the returned launcher as agent-device does before and after open", () =>
255 Effect.gen(function* () {
256 const { devices = [], deviceHosts } = deviceCase({}).setup.world ?? {};
257 const tools = yield* makeDeviceTools({ devices, deviceHosts }, base.environment);
258 const opened = json((yield* tools.call("device_open", { hostId: MAC, deviceId: IPHONE })).text);
259 const { command, targetArgs, session: bound } = opened.agentDevice;
260 // This ref's launcher: a bound one names its session; the shared one takes device_open's flags.
261 const session: string = bound ?? targetArgs[targetArgs.indexOf("--session") + 1];
262 const line = (args: string) =>
263 bound === undefined ? `${command} ${args} ${targetArgs.join(" ")}` : `${command} ${args}`;
264 const history: Array<ShellCall> = [];
265 const answer = (args: string) => tools.sessionError(history, line(args));
266 const ran = (args: string, output: string) =>
267 history.push({ tool: "Bash", input: { command: line(args) }, output });
268
269 const shot = answer("screenshot /tmp/shot.png") ?? "";
270 assert.isTrue(shot.startsWith(`Exit code 1\n${NO_SESSION}\nDiagnostic ID: `));
271 assert.match(
272 shot,
273 new RegExp(
274 `\\nDiagnostics Log: /home/user/\\.agent-device/remote-diagnostics/${session}/requests/[\\da-f]{16}\\.ndjson$`,
275 ),
276 );
277 for (const args of ["press @e3 --settle", 'fill @e5 "hello world"', "scroll down", "home"]) {
278 assert.include(answer(args), NO_SESSION, args);
279 }
280 assert.include(answer("record start /tmp/run.mp4"), APP_RECORDING_BEFORE_OPEN);
281 // An iOS snapshot needs an app open in the session.
282 assert.include(answer("snapshot -i"), iosSnapshotRefused("sim"));
283 // With the device selector both refs pass, these run without a session.
284 for (const args of [
285 "open",
286 "devices",
287 "apps",
288 "settings appearance dark",
289 "alert accept",
290 "install com.acme.app /tmp/Acme.app",
291 "record start --scope device /tmp/run.mp4",
292 ]) {
293 assert.isUndefined(answer(args), args);
294 }
295 // Unknown flags, JSON output and compound commands stay with the simulator.
296 assert.isUndefined(answer("screenshot --bogus /tmp/shot.png"));
297 assert.isUndefined(answer("screenshot --json /tmp/shot.png"));
298 assert.isUndefined(tools.sessionError(history, `${line("screenshot /tmp/a.png")} && echo ok`));
299 assert.deepEqual([...tools.sessions(history)], [[session, undefined]]);
300
301 ran("open com.acme.missing", "Exit code 1\nError (APP_NOT_INSTALLED): App not installed");
302 assert.include(answer("screenshot /tmp/shot.png"), NO_SESSION);
303 ran("open", `Opened: ${session}`);
304 assert.isUndefined(answer("screenshot /tmp/shot.png"));
305 assert.isUndefined(answer("press @e3"));
306 assert.include(answer("record start /tmp/run.mp4"), APP_RECORDING_WITHOUT_APP);
307 assert.isUndefined(answer("record start --scope device /tmp/run.mp4"));
308 assert.include(answer("snapshot -i"), iosSnapshotRefused(session));
309 ran("open com.acme.app", "Opened: com.acme.app");
310 assert.isUndefined(answer("record start /tmp/run.mp4"));
311 assert.isUndefined(answer("snapshot -i"));
312 assert.deepEqual([...tools.sessions(history)], [[session, { app: true }]]);
313 ran("close", "Closed");
314 assert.include(
315 tools.sessionError(history, `${line("screenshot /tmp/a.png")} 2>&1`),
316 NO_SESSION,
317 );
318 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
319);
320
321const shared = (session: string): LauncherTarget => ({
322 command: "/home/user/.t3/userdata/device/bin/agent-device",
323 session,
324 bound: false,
325 deviceId: IPHONE,
326 ios: true,
327 iosSimulator: true,
328});
329const boundTarget: LauncherTarget = {
330 command: "/home/user/.t3/userdata/device/targets/t3-bound/agent-device",
331 session: "t3-bound",
332 bound: true,
333 deviceId: IPHONE,
334 ios: true,
335 iosSimulator: true,
336};
337const bash = (command: string, output = "OK"): ShellCall => ({
338 tool: "Bash",
339 input: { command },
340 output,
341});
342const errorCode = (
343 targets: ReadonlyArray<LauncherTarget>,
344 history: ReadonlyArray<ShellCall>,
345 command: string,
346) => agentDeviceSessionError(targets, agentDeviceSessions(targets, {}, history), command)?.code;
347
348it("names the session on either ref: the bound launcher's own, or the shared one's --session", () => {
349 const flags = `--platform ios --udid ${IPHONE} --config /home/user/.t3/userdata/device/hosts/x.json`;
350 const sharedTargets = [shared("t3-a"), shared("t3-b")];
351 // The shared launcher answers each session its flags name; without one, its own check (not
352 // modelled) refuses before agent-device runs.
353 const opened = [bash(`${sharedTargets[0]!.command} open com.acme.app ${flags} --session t3-a`)];
354 assert.isUndefined(
355 errorCode(
356 sharedTargets,
357 opened,
358 `${sharedTargets[0]!.command} screenshot ${flags} --session t3-a`,
359 ),
360 );
361 assert.equal(
362 errorCode(
363 sharedTargets,
364 opened,
365 `${sharedTargets[0]!.command} screenshot ${flags} --session=t3-b`,
366 ),
367 "SESSION_NOT_FOUND",
368 );
369 assert.isUndefined(errorCode(sharedTargets, [], `${sharedTargets[0]!.command} screenshot`));
370 // The bound launcher needs no flags, and an explicit --session still wins.
371 assert.equal(
372 errorCode([boundTarget], [], `${boundTarget.command} screenshot`),
373 "SESSION_NOT_FOUND",
374 );
375 assert.equal(errorCode([boundTarget], [], `${boundTarget.command} record start`), "INVALID_ARGS");
376 const boundOpen = [bash(`${boundTarget.command} open`)];
377 assert.isUndefined(errorCode([boundTarget], boundOpen, `${boundTarget.command} screenshot`));
378 assert.equal(
379 errorCode([boundTarget], boundOpen, `${boundTarget.command} record start /tmp/r.mp4`),
380 "UNKNOWN",
381 );
382 assert.equal(
383 errorCode([boundTarget], boundOpen, `${boundTarget.command} screenshot --session other`),
384 "SESSION_NOT_FOUND",
385 );
386 // Without a selector, agent-device's record and close refuse a missing named session with
387 // other text; that stays with the simulator.
388 assert.isUndefined(
389 errorCode(sharedTargets, [], `${sharedTargets[0]!.command} record start --session t3-a`),
390 );
391});
392
393it("follows the session through aliases, compound calls, snapshots and whole-screen recordings", () => {
394 const launcher = boundTarget.command;
395 const after = (...history: ReadonlyArray<ShellCall>) =>
396 agentDeviceSessions([boundTarget], {}, history).get("t3-bound");
397 assert.deepEqual(after(bash(`AD=${launcher}; "$AD" open com.acme.app`)), { app: true });
398 // A failed lone open starts nothing; an open in a failed compound call still counts.
399 assert.isUndefined(after(bash(`${launcher} open com.acme.app`, "Exit code 1\nError (X): no")));
400 assert.deepEqual(
401 after(bash(`${launcher} open com.acme.app && ${launcher} press @e9`, "Exit code 1\nboom")),
402 { app: true },
403 );
404 // Dead tails, remote agent-device and help start nothing.
405 assert.isUndefined(after(bash(`false && ${launcher} open`, "Exit code 1")));
406 assert.isUndefined(after(bash("ssh build-mac agent-device open com.acme.app")));
407 assert.isUndefined(after(bash(`${launcher} help open`)));
408 // agent-device publishes a session for a sessionless Android snapshot, without an app. An iOS
409 // snapshot without an app fails and starts nothing.
410 assert.isUndefined(after(bash(`${launcher} snapshot -i`)));
411 const android = { ...boundTarget, ios: false, iosSimulator: false };
412 assert.deepEqual(
413 agentDeviceSessions([android], {}, [bash(`${launcher} snapshot -i`)]).get("t3-bound"),
414 { app: false },
415 );
416 // A whole-screen recording holds a session only until it stops.
417 const recording = bash(`${launcher} record start --scope device /tmp/r.mp4`);
418 assert.deepEqual(after(recording), { app: false, recordingOnly: true });
419 assert.isUndefined(errorCode([boundTarget], [recording], `${launcher} screenshot`));
420 assert.isUndefined(after(recording, bash(`${launcher} record stop`)));
421 assert.equal(
422 errorCode(
423 [boundTarget],
424 [recording, bash(`${launcher} record stop`)],
425 `${launcher} screenshot`,
426 ),
427 "SESSION_NOT_FOUND",
428 );
429 assert.deepEqual(after(bash(`${launcher} open`), bash(`${launcher} close`)), undefined);
430});
431
432it("follows the shared launcher's session through flags held in a variable or an array", () => {
433 // Forms Sonnet used with the shared launcher in a live sample.
434 const target = shared("t3-a");
435 const flags = `--platform ios --udid ${IPHONE} --config /home/user/.t3/userdata/device/hosts/x.json --session t3-a`;
436 const after = (history: ShellCall, targets = [target]) =>
437 agentDeviceSessions(targets, {}, [history]).get("t3-a");
438 const opened = bash(
439 `AD=${target.command}; A="${flags}"; $AD open com.acme.app $A 2>&1 | tail -5; sleep 5; $AD snapshot -i $A 2>&1 | head -60`,
440 "Opened: com.acme.app",
441 );
442 assert.deepEqual(after(opened), { app: true });
443 const array = bash(`A=(${flags}); ${target.command} open "\${A[@]}" 2>&1 | head -60`);
444 assert.deepEqual(after(array), { app: false });
445 // With two sessions behind the shared launcher, unread flags name neither.
446 assert.isUndefined(after(array, [target, shared("t3-b")]));
447 // agent-device still sees no session for a plain command after a failed open in a variable.
448 const failed = bash(
449 `AD=${target.command}; A="${flags}"; $AD open $A`,
450 "Exit code 1\nError (X): no",
451 );
452 assert.equal(
453 errorCode([target], [failed], `${target.command} screenshot ${flags}`),
454 "SESSION_NOT_FOUND",
455 );
456});
457
458it.effect("starts sessions the world says prior turns opened, and rejects unknown devices", () =>
459 Effect.gen(function* () {
460 const testCase = deviceCase({
461 world: { ...world, agentDeviceSessions: { [IPHONE]: { app: "com.acme.app" } } },
462 priorTurns: [
463 { role: "user", text: "Show me Settings on the iPhone on build-mac." },
464 {
465 role: "assistant",
466 toolCalls: [
467 { tool: "device_open", input: { hostId: MAC, deviceId: IPHONE }, result: "default" },
468 ],
469 },
470 ],
471 });
472 const sample = makeSample(testCase, base);
473 yield* withDevices(sample);
474 const tools = sample.devices!;
475 const [launcher = ""] = tools.launchers;
476 assert.deepEqual([...tools.sessions(sample.shell).values()], [{ app: true }]);
477 const call = { tool: "Bash", input: { command: "ls" } };
478 assert.include(
479 JSON.stringify(shellRequest(sample, call, "claude-haiku-5-5").messages),
480 "is open with an app",
481 );
482 assert.isUndefined(tools.sessionError(sample.shell, `${launcher} record start /tmp/r.mp4`));
483 const { devices = [], deviceHosts } = testCase.setup.world ?? {};
484 const unknown = { devices, deviceHosts, agentDeviceSessions: { "not-a-device": {} } };
485 const exit = yield* Effect.exit(makeDeviceTools(unknown, base.environment));
486 assert.isTrue(exit._tag === "Failure");
487 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
488);
489
490it.effect(
491 "answers a shell mock first, then help, then the session error, before the simulator",
492 () =>
493 Effect.gen(function* () {
494 const sample = makeSample(deviceCase({}), base);
495 yield* withDevices(sample);
496 const opened = yield* sample.devices!.call("device_open", { hostId: MAC, deviceId: IPHONE });
497 const { command, targetArgs, session } = json(opened.text).agentDevice;
498 const flags = session === undefined ? ` ${targetArgs.join(" ")}` : "";
499 const told = () =>
500 JSON.stringify(
501 shellRequest(sample, { tool: "Bash", input: {} }, "claude-haiku-5-5").messages,
502 );
503 assert.include(told(), "has not started");
504 assert.include(cannedOutput(sample, `${command} screenshot /tmp/a.png${flags}`), NO_SESSION);
505 assert.match(cannedOutput(sample, `${command} help record`) ?? "", /^Usage:/);
506 assert.isUndefined(cannedOutput(sample, `${command} open com.acme.app${flags}`));
507 const outage = makeSample(
508 deviceCase({
509 shellMocks: [
510 { match: "\\bagent-device\\b", output: "Exit code 1\nError (COMMAND_FAILED): down" },
511 ],
512 }),
513 base,
514 );
515 yield* withDevices(outage);
516 yield* outage.devices!.call("device_open", { hostId: MAC, deviceId: IPHONE });
517 assert.include(cannedOutput(outage, `${command} screenshot /tmp/a.png${flags}`), "down");
518 sample.shell.push({
519 tool: "Bash",
520 input: { command: `${command} open com.acme.app${flags}` },
521 output: "Opened: com.acme.app",
522 });
523 assert.isUndefined(cannedOutput(sample, `${command} screenshot /tmp/a.png${flags}`));
524 assert.include(told(), "is open with an app");
525 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
526);
527
528it("keeps a redirection's descriptor out of the app an open names, on either launcher", () => {
529 // Sol R10 B1: `open 2>&1` once read as `open 2`, an app the real shell never passes.
530 const flags = `--platform ios --udid ${IPHONE} --config /home/user/.t3/userdata/device/hosts/x.json --session t3-a`;
531 for (const [target, args] of [
532 [shared("t3-a"), ` ${flags}`],
533 [boundTarget, ""],
534 ] as const) {
535 for (const redirect of ["2>&1", "2>&1 | tail -5", "2>/dev/null"]) {
536 const opened = [
537 bash(`${target.command} open${args} ${redirect}`, `Opened: ${target.session}`),
538 ];
539 assert.deepEqual(
540 agentDeviceSessions([target], {}, opened).get(target.session),
541 { app: false },
542 redirect,
543 );
544 assert.equal(
545 errorCode([target], opened, `${target.command} record start /tmp/run.mp4${args}`),
546 "UNKNOWN",
547 redirect,
548 );
549 }
550 }
551});
552
553it("follows opens the parser cannot prove ran, in calls that did not fail", () => {
554 // Opus R10 B1(b): shapes from run 5, where `&&` before `;` leaves an open uncertain.
555 const launcher = boundTarget.command;
556 const after = (command: string, output = "Opened: com.acme.app") =>
557 agentDeviceSessions([boundTarget], {}, [bash(command, output)]).get("t3-bound");
558 assert.deepEqual(
559 after(`mkdir -p /tmp/p && ${launcher} open com.acme.app 2>&1 | tail -3; echo done`),
560 { app: true },
561 );
562 assert.deepEqual(after(`cd /tmp && ${launcher} open com.acme.app; ${launcher} snapshot -i`), {
563 app: true,
564 });
565 // The launcher alias such a call sets, too, here and in later calls.
566 assert.deepEqual(after(`mkdir -p /tmp/p && AD=${launcher}; $AD open com.acme.app`), {
567 app: true,
568 });
569 assert.deepEqual(after(`mkdir -p /tmp/p && AD="${launcher}"; "\${AD}" open com.acme.app`), {
570 app: true,
571 });
572 assert.deepEqual(
573 agentDeviceSessions([boundTarget], {}, [
574 bash(`cd /tmp && AD=${launcher}; echo ready`),
575 bash("$AD open com.acme.app"),
576 ]).get("t3-bound"),
577 { app: true },
578 );
579 // A failed call credits only what certainly ran.
580 assert.isUndefined(
581 after(`mkdir -p /tmp/p && ${launcher} open com.acme.app; echo done`, "Exit code 1\nno"),
582 );
583 assert.isUndefined(
584 after(`mkdir -p /tmp/p && AD=${launcher}; $AD open com.acme.app`, "Exit code 1\nno"),
585 );
586});
587
588const SPARE_MAC = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
589const SPARE_PHONE = "DDDDDDDD-DDDD-4DDD-8DDD-DDDDDDDDDDDD";
590const twoMacs = {
591 devices: [
592 ...world.devices,
593 { ...world.devices[0]!, hostId: SPARE_MAC, id: SPARE_PHONE, name: "Acme Spare iPhone" },
594 ],
595 deviceHosts: { ...world.deviceHosts, [SPARE_MAC]: "spare-mac" },
596};
597const deviceTools = (extra: object) =>
598 makeDeviceTools(
599 { ...twoMacs, ...extra } as Parameters<typeof makeDeviceTools>[0],
600 base.environment,
601 );
602
603it.effect("lists a host whose discovery fails as T3 does: failed, with none of its devices", () =>
604 Effect.gen(function* () {
605 // F1's saved device_list: the hub answered, but its device list timed out.
606 const failure = new DeviceOperationError({
607 operation: "list",
608 reason: "request_failed",
609 cause: null,
610 });
611 const tools = yield* deviceTools({ deviceDiscoveryFailures: { [MAC]: failure } });
612 const listed = json((yield* tools.call("device_list", {})).text);
613 assert.deepEqual(listed.hostStatuses[MAC], {
614 status: "failed",
615 detail:
616 "Device list failed: Could not communicate with device support. Try refreshing devices.",
617 });
618 assert.equal(listed.hostStatuses[SPARE_MAC].status, "ready");
619 assert.deepEqual(
620 listed.devices.map((device: { id: string }) => device.id),
621 [SPARE_PHONE],
622 );
623 const opened = yield* tools.call("device_open", { hostId: MAC, deviceId: IPHONE });
624 assert.isTrue(opened.isError);
625 assert.include(opened.text, IPHONE);
626 assert.isFalse(
627 (yield* tools.call("device_open", { hostId: SPARE_MAC, deviceId: SPARE_PHONE })).isError,
628 );
629 // A failed host with no devices of its own still needs its label.
630 const unlabeled = yield* Effect.exit(
631 deviceTools({ deviceDiscoveryFailures: { "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee": failure } }),
632 );
633 assert.isTrue(unlabeled._tag === "Failure");
634 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
635);
636
637it.effect("denies every device tool with T3's own error when agent device access is off", () =>
638 Effect.gen(function* () {
639 const tools = yield* deviceTools({ deviceAgentAccess: false });
640 for (const [name, input] of [
641 ["device_list", {}],
642 ["device_open", { hostId: MAC, deviceId: IPHONE }],
643 ["device_screenshot", {}],
644 ["device_close", {}],
645 ] as const) {
646 const result = yield* tools.call(name, input);
647 assert.isTrue(result.isError, name);
648 // Refs before typed screenshot errors print their generic screenshot failure instead, and
649 // later refs may add how to turn access on.
650 const denied = result.text.startsWith(
651 "Agent device access is turned off for this environment.",
652 );
653 assert.isTrue(
654 denied || (name === "device_screenshot" && result.text === "Device screenshot failed."),
655 `${name}: ${result.text}`,
656 );
657 }
658 // T3 drops its device text for a thread without the capability, on refs that have it.
659 assert.notInclude(t3SystemAppend(model, false), "## T3 Code devices");
660 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
661);
662
663it.effect("reports an unreadable capture as T3 does: a successful 0×0 screenshot", () =>
664 Effect.gen(function* () {
665 const tools = yield* deviceTools({ deviceInvalidCapture: true });
666 yield* tools.call("device_open", { hostId: MAC, deviceId: IPHONE });
667 const shot = yield* tools.call("device_screenshot", {});
668 assert.isFalse(shot.isError);
669 assert.deepEqual(json(shot.text).screenshot, { mimeType: "image/png", width: 0, height: 0 });
670 const sample = makeSample(
671 deviceCase({ world: { ...world, deviceInvalidCapture: true } }),
672 base,
673 );
674 yield* withDevices(sample);
675 const told = JSON.stringify(shellRequest(sample, { tool: "Bash", input: {} }, model).messages);
676 assert.include(told, "agent-device's own screenshot finds the PNG and is unaffected");
677 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
678);
679
680it.effect("refuses an open on a device another thread's agent-device session holds", () =>
681 Effect.gen(function* () {
682 const tools = yield* deviceTools({ deviceOwners: { [IPHONE]: "acme-design-review" } });
683 // T3 names the owner's session as it names every thread's.
684 const owner = "t3-a062c547ef0b6bf8ee839b67";
685 assert.deepEqual(tools.owners, [
686 { deviceId: IPHONE, threadId: "acme-design-review", session: owner },
687 ]);
688 // T3 has no cross-thread gate: device_open succeeds, and device_list shows only this thread.
689 const opened = json((yield* tools.call("device_open", { hostId: MAC, deviceId: IPHONE })).text);
690 assert.deepEqual(json((yield* tools.call("device_list", {})).text).open, [
691 { hostId: MAC, deviceId: IPHONE },
692 ]);
693 const { command, targetArgs, session: bound } = opened.agentDevice;
694 const own: string = bound ?? targetArgs[targetArgs.indexOf("--session") + 1];
695 const target = (session = own) =>
696 bound === undefined
697 ? targetArgs.map((arg: string) => (arg === own ? session : arg)).join(" ")
698 : session === own
699 ? ""
700 : `--session ${session}`;
701 const line = (args: string, session?: string) => `${command} ${args} ${target(session)}`.trim();
702 const history: Array<ShellCall> = [];
703 const answer = (args: string, session?: string) =>
704 tools.sessionError(history, line(args, session)) ?? "";
705 const inUse = `Error (DEVICE_IN_USE): Device is already in use by session "${owner}".\nHint: Run agent-device session list to inspect active sessions. To reuse this device, rerun the command with --session ${owner}. To open a new session on this device, first run agent-device close --session ${owner}.`;
706 assert.include(
707 answer("open com.acme.app"),
708 `${inUse} To wait for the device to free up, run the same open with --wait <ms>.\nDiagnostic ID: `,
709 );
710 assert.include(
711 answer("open --wait 5000"),
712 `Error (DEVICE_IN_USE): Device is already in use by session "${owner}".\nHint: Waited 5000ms for this device and it stayed busy. Run agent-device session list`,
713 );
714 assert.notInclude(answer("open --wait 5000"), "--wait <ms>");
715 // The hint's reuse works, in the other thread's session.
716 assert.equal(answer("screenshot /tmp/a.png", owner), "");
717 assert.equal(answer("open com.acme.app", owner), "");
718 // A failed open starts nothing, in a compound call too.
719 history.push({
720 tool: "Bash",
721 input: { command: `${line("open com.acme.app")} && ${line("screenshot /tmp/a.png")}` },
722 output: "Exit code 1\nError (DEVICE_IN_USE): Device is already in use",
723 });
724 assert.deepEqual(
725 [...tools.sessions(history)],
726 [
727 [own, undefined],
728 [owner, { app: true }],
729 ],
730 );
731 const sample = makeSample(
732 deviceCase({ world: { ...twoMacs, deviceOwners: { [IPHONE]: "acme-design-review" } } }),
733 base,
734 );
735 yield* withDevices(sample);
736 const told = JSON.stringify(shellRequest(sample, { tool: "Bash", input: {} }, model).messages);
737 assert.include(
738 told,
739 `${owner} (Acme iPhone, ${IPHONE}, on build-mac) belongs to another T3 thread (acme-design-review)`,
740 );
741 // Closing the owner's session frees the device.
742 history.push({ tool: "Bash", input: { command: line("close", owner) }, output: "Closed" });
743 assert.equal(answer("open com.acme.app"), "");
744 assert.include(describeSessions(tools.sessions(history), tools.owners), "was closed");
745 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
746);
747
748it.effect("leaves a free device free when another thread holds a different one", () =>
749 Effect.gen(function* () {
750 const tools = yield* deviceTools({ deviceOwners: { [IPHONE]: "acme-design-review" } });
751 const opened = json(
752 (yield* tools.call("device_open", { hostId: SPARE_MAC, deviceId: SPARE_PHONE })).text,
753 );
754 const { command, targetArgs, session } = opened.agentDevice;
755 const flags = session === undefined ? ` ${targetArgs.join(" ")}` : "";
756 assert.isUndefined(tools.sessionError([], `${command} open com.acme.app${flags}`));
757 assert.include(
758 tools.sessionError([], `${command} screenshot /tmp/a.png${flags}`) ?? "",
759 "SESSION_NOT_FOUND",
760 );
761 // The local host always exists and holds none of the world's devices.
762 assert.isFalse(
763 (yield* tools.call("device_list", {})).text.includes(`"hostId":"${LOCAL_DEVICE_HOST_ID}"`),
764 );
765 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
766);
767
768type Opened = { command: string; targetArgs: Array<string>; session?: string };
769/** This ref's command line for a launcher: a bound one needs no flags; the shared one takes them. */
770const commandLine = (opened: Opened, args: string, session?: string) => {
771 const own = opened.session ?? opened.targetArgs[opened.targetArgs.indexOf("--session") + 1];
772 if (opened.session !== undefined)
773 return `${opened.command} ${args}${session === undefined ? "" : ` --session ${session}`}`;
774 const flags = opened.targetArgs.map((arg) => (arg === own && session ? session : arg));
775 return `${opened.command} ${args} ${flags.join(" ")}`;
776};
777
778it.effect(
779 "tells the simulator each launcher's device, and routes DEVICE_IN_USE to the held one",
780 () =>
781 Effect.gen(function* () {
782 // Opus R11-B3(a): in run 6 the simulator gave the free spare's plain open the owner's
783 // DEVICE_IN_USE twice. It could not tell which device a flagless bound launcher drives.
784 const owner = "t3-a062c547ef0b6bf8ee839b67";
785 const sample = makeSample(
786 deviceCase({ world: { ...twoMacs, deviceOwners: { [IPHONE]: "acme-design-review" } } }),
787 base,
788 );
789 yield* withDevices(sample);
790 const tools = sample.devices!;
791 const open = (hostId: string, deviceId: string) =>
792 Effect.map(
793 tools.call("device_open", { hostId, deviceId }),
794 (result): Opened => json(result.text).agentDevice,
795 );
796 const held = yield* open(MAC, IPHONE);
797 const spare = yield* open(SPARE_MAC, SPARE_PHONE);
798 const session = (opened: Opened) =>
799 opened.session ?? opened.targetArgs[opened.targetArgs.indexOf("--session") + 1];
800 const told = (command: string) =>
801 String(
802 shellRequest(sample, { tool: "Bash", input: { command } }, model).messages[0]?.content[0]
803 ?.text,
804 );
805 // Run 6's history: the held device's plain open, refused without the simulator.
806 const heldOpen = commandLine(held, "open com.acme.app --metro-port 8095");
807 const refused = cannedOutput(sample, heldOpen) ?? "";
808 assert.include(
809 refused,
810 `Error (DEVICE_IN_USE): Device is already in use by session "${owner}".`,
811 );
812 sample.shell.push({ tool: "Bash", input: { command: heldOpen }, output: refused });
813
814 // The spare's plain open goes to the simulator, which now knows it drives the free spare.
815 const spareOpen = commandLine(spare, "open com.acme.app --metro-port 8095");
816 assert.isUndefined(cannedOutput(sample, spareOpen));
817 const free = told(spareOpen);
818 assert.include(
819 free,
820 `agent-device launchers T3's device_open returned: ${
821 held.session === undefined
822 ? `${held.command} (shared: each command's --udid or --serial and --session name its device and session)`
823 : `${held.command} (drives Acme iPhone, ${IPHONE}, on build-mac, in session ${held.session}); ${spare.command} (drives Acme Spare iPhone, ${SPARE_PHONE}, on spare-mac, in session ${spare.session})`
824 }`,
825 );
826 assert.include(
827 free,
828 `${session(held)} (Acme iPhone, ${IPHONE}, on build-mac) has not started; ${session(spare)} (Acme Spare iPhone, ${SPARE_PHONE}, on spare-mac) has not started; ${owner} (Acme iPhone, ${IPHONE}, on build-mac) belongs to another T3 thread (acme-design-review) and holds its device with an app open.`,
829 );
830 assert.include(
831 free,
832 `In the new call, \`${spareOpen}\` drives Acme Spare iPhone, ${SPARE_PHONE}, on spare-mac, which no other session holds: it prints no DEVICE_IN_USE.`,
833 );
834 assert.notInclude(free, "Error (DEVICE_IN_USE)");
835
836 // A compound open of the held device gets agent-device's exact refusal, for that open only.
837 const piped = commandLine(held, "open com.acme.app");
838 const refusal = told(`${piped} 2>&1 | tail -5`);
839 assert.include(
840 refusal,
841 `In the new call, \`${piped}\` drives Acme iPhone, ${IPHONE}, on build-mac, which session ${owner} holds: it fails with exit code 1, printing "Error (DEVICE_IN_USE): Device is already in use by session "${owner}"." and "Hint: Run agent-device session list to inspect active sessions. To reuse this device,`,
842 );
843 assert.notInclude(refusal, "no other session holds");
844 // One call may try the held device, then fall back to the spare through an alias.
845 const alias =
846 spare.session === undefined
847 ? `A=${spare.command}; "$A" open com.acme.app ${spare.targetArgs.join(" ")}`
848 : `A=${spare.command}; "$A" open com.acme.app`;
849 const both = told(`${piped} || echo busy; ${alias}`);
850 assert.include(both, `which session ${owner} holds: it fails with exit code 1`);
851 assert.include(
852 both,
853 `on spare-mac, which no other session holds: it prints no DEVICE_IN_USE`,
854 );
855 // An open in the other thread's own session is not refused, and gets no route.
856 assert.notInclude(told(commandLine(held, "open com.acme.app", owner)), "In the new call");
857 // An open after the same call closes the other thread's session finds the device free.
858 const reopen = told(`${commandLine(held, "close", owner)}; ${piped}`);
859 assert.include(
860 reopen,
861 `\`${piped}\` drives Acme iPhone, ${IPHONE}, on build-mac, which no other session holds: it prints no DEVICE_IN_USE`,
862 );
863 assert.notInclude(reopen, `which session ${owner} holds`);
864 // Neither do commands other than open.
865 assert.notInclude(
866 told(`${commandLine(spare, "screenshot /tmp/a.png")} && echo ok`),
867 "In the new call",
868 );
869
870 // A world where no other thread holds a device gets no route either.
871 const alone = makeSample(deviceCase({}), base);
872 yield* withDevices(alone);
873 const own: Opened = json(
874 (yield* alone.devices!.call("device_open", { hostId: MAC, deviceId: IPHONE })).text,
875 ).agentDevice;
876 const request = shellRequest(
877 alone,
878 { tool: "Bash", input: { command: `${commandLine(own, "open com.acme.app")} | tail -3` } },
879 model,
880 );
881 assert.notInclude(JSON.stringify(request.messages), "In the new call");
882 assert.include(
883 JSON.stringify(request.messages),
884 `${session(own)} (Acme iPhone, ${IPHONE}, on build-mac) has not started`,
885 );
886 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
887);
888
889it("tells the simulator 0.21.31's --foreground and session list behaviour", () => {
890 // Opus R11-B3(b): 0.21.31 (session2.js ys) refuses only an open --foreground with no app or URL.
891 // Run 6's simulator refused `open <app> --foreground` in 9 base samples.
892 assert.include(
893 AGENT_DEVICE_SHELL,
894 "open --foreground with no app or URL fails with exit code 1 when the command passes --udid or --device",
895 );
896 assert.include(AGENT_DEVICE_SHELL, "open <app> --foreground works.");
897 // Run 6's simulator answered the DEVICE_IN_USE hint's `session list` with "Unknown command".
898 assert.include(
899 AGENT_DEVICE_SHELL,
900 "session list prints, as JSON, the started sessions on the launcher's host, other threads' too",
901 );
902 // Neither is refused without the simulator.
903 for (const args of ["open com.acme.app --foreground", "session list"]) {
904 assert.isUndefined(
905 agentDeviceSessionError(
906 [boundTarget],
907 new Map([["t3-bound", undefined]]),
908 `${boundTarget.command} ${args}`,
909 ),
910 args,
911 );
912 }
913});