Skip to content

Commit 4abcb20

Browse files
committed
fix(server): flows and environment selectors no longer reach a claimed device
batch, replay and test hand their selectors to every step, and agent-device runs a non-open step with selectors on that device without a claim check. The launcher now lists the daemon's sessions first and refuses a flow with DEVICE_IN_USE when another session holds the bound device. agent-device also reads selectors from AGENT_DEVICE_PLATFORM, _SERIAL and the like, so the launcher drops those for commands that get no selector flags. The command is now found past `--save-script <path>`, which takes a value only when it looks like a path, so `--save-script ./run.ad open` still selects.
1 parent 033bcf9 commit 4abcb20

2 files changed

Lines changed: 125 additions & 2 deletions

File tree

‎apps/server/src/device/AgentDeviceShim.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,12 +179,18 @@ const SELECTING_COMMANDS: ReadonlyArray<string> = [
179179
"push",
180180
];
181181

182+
/**
183+
* agent-device 0.21.36 hands a flow's selectors to every step, so a step other than open runs on
184+
* the device without a claim check, as any command given a selector does.
185+
*/
186+
const FLOW_COMMANDS: ReadonlyArray<string> = ["batch", "replay", "test"];
187+
182188
// Help gets no bound flags (agent-device reads --config even for help); only args before `--` are flags.
183189
// agent-device 0.21.31 refuses some bound flags per command; connect/disconnect/auth/daemon would
184190
// replace T3's connection; device status reads this machine's claims. It reports a sandboxed shell and a
185191
// dropped tunnel alike, so check first, at --daemon-base-url if given, as agent-device prefers it.
186192
const launcherSource = (node: string, entryPath: string, boundArgs: ReadonlyArray<string>) =>
187-
`import { spawn } from "node:child_process";
193+
`import { spawn, spawnSync } from "node:child_process";
188194
import { existsSync, readFileSync } from "node:fs";
189195
import { connect } from "node:net";
190196
const entry = ${JSON.stringify(entryPath)};
@@ -193,6 +199,8 @@ const refused = new Map([["cdp", ["--platform", "--udid", "--config", "--session
193199
const managed = ["connect", "disconnect", "auth", "daemon"];
194200
const selectors = ["--platform", "--target", "--device", "--udid", "--serial"];
195201
const selecting = ${JSON.stringify(SELECTING_COMMANDS)};
202+
const flows = ${JSON.stringify(FLOW_COMMANDS)};
203+
const selectorEnv = ["AGENT_DEVICE_PLATFORM", "AGENT_DEVICE_TARGET", "AGENT_DEVICE_DEVICE", "AGENT_DEVICE_UDID", "AGENT_DEVICE_SERIAL"];
196204
const args = process.argv.slice(2);
197205
const end = args.indexOf("--");
198206
const given = end < 0 ? args : args.slice(0, end);
@@ -203,6 +211,9 @@ for (let index = 0; index < args.length; index++) {
203211
if (arg === "--") { name = args[index + 1] ?? ""; break; }
204212
if (!arg.startsWith("-")) { name = arg; break; }
205213
if (!arg.includes("=") && valued.has(arg)) index++;
214+
// --save-script takes a value only when it looks like a path, as agent-device decides.
215+
const next = args[index + 1];
216+
if (arg === "--save-script" && next !== undefined && !next.startsWith("-") && /[\\/\\\\]/.test(next) && !/^[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\//.test(next)) index++;
206217
}
207218
const informational = args.length === 0 || ["help", "--help", "-h", "--version", "version"].includes(args[0]) || given.includes("--help") || given.includes("-h");
208219
const selects = informational || selecting.includes(name.toLowerCase());
@@ -251,6 +262,23 @@ const env = { ...process.env, ELECTRON_RUN_AS_NODE: "1" };
251262
delete env.AGENT_DEVICE_DAEMON_BASE_URL;
252263
delete env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
253264
delete env.AGENT_DEVICE_CONFIG;
265+
// agent-device reads selectors from the environment too.
266+
if (!selects) for (const key of selectorEnv) delete env[key];
267+
const held = valueOf("--udid") ?? valueOf("--serial");
268+
if (!informational && flows.includes(name.toLowerCase()) && held) {
269+
const listed = spawnSync(${JSON.stringify(node)}, [entry, "session", "list", "--json", "--config", valueOf("--config")], { env, encoding: "utf8", timeout: 30000 });
270+
let sessions;
271+
try { sessions = JSON.parse(listed.stdout).data.sessions; } catch {}
272+
if (!Array.isArray(sessions)) {
273+
console.error("\`" + name + "\` did not run: T3 Code could not check whether another session holds this device. " + (listed.stderr || listed.stdout || listed.error?.message || "").trim());
274+
process.exit(1);
275+
}
276+
const own = valueOf("--session");
277+
if (sessions.some(session => session?.id === held && session?.name !== own)) {
278+
console.error("Error (DEVICE_IN_USE): this device is in use by another session. \`" + name + "\` would run its steps there without a claim check, so it is not available until that session closes.");
279+
process.exit(1);
280+
}
281+
}
254282
const child = spawn(${JSON.stringify(node)}, [entry, ...command], { stdio: "inherit", env });
255283
child.on("error", error => { console.error(error.message); process.exitCode = 1; });
256284
child.on("exit", code => { process.exitCode = code ?? 1; });

‎apps/server/src/device/AgentDeviceTarget.test.ts‎

Lines changed: 96 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,11 @@ exec '${process.execPath.replaceAll("'", "'\"'\"'")}' "$@"
183183
const path = yield* Path.Path;
184184
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-commands-" });
185185
const entryPath = path.join(dir, "cli.mjs");
186-
yield* fs.writeFileString(entryPath, "console.log(JSON.stringify(process.argv.slice(2)));");
186+
// Answers the launcher's session list with no sessions; otherwise prints what it was given.
187+
yield* fs.writeFileString(
188+
entryPath,
189+
'const args = process.argv.slice(2); console.log(JSON.stringify(args[0] === "session" ? { data: { sessions: [] } } : args));',
190+
);
187191
const command = yield* bindAgentDeviceLauncher({
188192
entryPath,
189193
stateDir: dir,
@@ -237,6 +241,15 @@ exec '${process.execPath.replaceAll("'", "'\"'\"'")}' "$@"
237241
]) {
238242
expect(yield* Effect.promise(() => launch(args))).toEqual([...args, ...selected]);
239243
}
244+
// --save-script takes the next argument only when it is a path, so open still selects.
245+
for (const flags of [["--save-script", "./capture.ad"], ["--save-script"]]) {
246+
expect(yield* Effect.promise(() => launch([...flags, "open", "com.example"]))).toEqual([
247+
...flags,
248+
"open",
249+
"com.example",
250+
...selected,
251+
]);
252+
}
240253
// agent-device 0.21.31 rejects these flags with "unknown option" or "not supported for command".
241254
const cdp = ["cdp", "target", "list", "--url", "http://127.0.0.1:8081"];
242255
expect(yield* Effect.promise(() => launch(cdp))).toEqual(cdp);
@@ -285,6 +298,88 @@ exec '${process.execPath.replaceAll("'", "'\"'\"'")}' "$@"
285298
),
286299
);
287300

301+
it.effect("keeps another session's device out of reach of flows and environment selectors", () =>
302+
Effect.gen(function* () {
303+
const fs = yield* FileSystem.FileSystem;
304+
const path = yield* Path.Path;
305+
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-claim-" });
306+
const entryPath = path.join(dir, "cli.mjs");
307+
// Lists the sessions in T3_TEST_SESSIONS; otherwise prints its arguments and any selector
308+
// agent-device would read from the environment.
309+
yield* fs.writeFileString(
310+
entryPath,
311+
[
312+
"const args = process.argv.slice(2);",
313+
'if (args[0] === "session") console.log(JSON.stringify({ data: { sessions: JSON.parse(process.env.T3_TEST_SESSIONS ?? "[]") } }));',
314+
"else console.log(JSON.stringify([...args, ...Object.keys(process.env).filter((key) => /^AGENT_DEVICE_(PLATFORM|SERIAL)$/.test(key))]));",
315+
].join("\n"),
316+
);
317+
const command = yield* bindAgentDeviceLauncher({
318+
entryPath,
319+
stateDir: dir,
320+
session: "t3-b",
321+
targetArgs: [
322+
"--platform",
323+
"android",
324+
"--serial",
325+
"emulator-5554",
326+
"--config",
327+
"/h.json",
328+
"--session",
329+
"t3-b",
330+
],
331+
});
332+
const launch = (args: ReadonlyArray<string>, env: Record<string, string> = {}) =>
333+
exec(
334+
process.execPath,
335+
[path.join(path.dirname(command), "agent-device-launcher.mjs"), ...args],
336+
{ env: { ...process.env, ...env } },
337+
).then((result) => JSON.parse(result.stdout));
338+
const owned = ["--config", "/h.json", "--session", "t3-b"];
339+
const selected = ["--platform", "android", "--serial", "emulator-5554", ...owned];
340+
const selectorEnv = {
341+
AGENT_DEVICE_PLATFORM: "android",
342+
AGENT_DEVICE_SERIAL: "emulator-5554",
343+
};
344+
// Selectors in the environment would reach the device as flags would.
345+
expect(yield* Effect.promise(() => launch(["snapshot", "-i"], selectorEnv))).toEqual([
346+
"snapshot",
347+
"-i",
348+
...owned,
349+
]);
350+
// A command that selects its device gets the bound flags, which win over the environment.
351+
expect(yield* Effect.promise(() => launch(["open", "com.example"], selectorEnv))).toEqual([
352+
"open",
353+
"com.example",
354+
...selected,
355+
"AGENT_DEVICE_PLATFORM",
356+
"AGENT_DEVICE_SERIAL",
357+
]);
358+
// A flow's steps inherit its selectors, so it does not run while another session holds the device.
359+
const held = (name: string) =>
360+
JSON.stringify([{ name, address: name, platform: "android", id: "emulator-5554" }]);
361+
for (const flow of [
362+
["batch", "--steps-file", "/s.json"],
363+
["replay", "flow.ad"],
364+
["test", "flows"],
365+
]) {
366+
yield* Effect.promise(() =>
367+
expect(launch(flow, { T3_TEST_SESSIONS: held("t3-a") })).rejects.toThrow(
368+
`Error (DEVICE_IN_USE): this device is in use by another session. \`${flow[0]}\``,
369+
),
370+
);
371+
expect(
372+
yield* Effect.promise(() => launch(flow, { T3_TEST_SESSIONS: held("t3-b") })),
373+
).toEqual([...flow, ...selected]);
374+
}
375+
}).pipe(
376+
Effect.scoped,
377+
Effect.provideService(HostProcess.IsExecutable, false),
378+
Effect.provideService(HostProcess.ExecutablePath, process.execPath),
379+
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
380+
),
381+
);
382+
288383
it("tells a released session from a close that failed or timed out", () => {
289384
const result = (code: number | null, stderr = "", timedOut = false) => ({
290385
stdout: "",

0 commit comments

Comments
 (0)