diff --git a/apps/server/src/device/AgentDeviceShim.ts b/apps/server/src/device/AgentDeviceShim.ts index e5b42557a1e10..580c186f8c146 100644 --- a/apps/server/src/device/AgentDeviceShim.ts +++ b/apps/server/src/device/AgentDeviceShim.ts @@ -36,6 +36,7 @@ const VALUE_FLAGS: ReadonlyArray = [ "--crop-on", "--custom-network", "-d", + "-e", "--daemon-auth-token", "--daemon-base-url", "--daemon-server-mode", @@ -46,6 +47,7 @@ const VALUE_FLAGS: ReadonlyArray = [ "--device-orientation", "--dsym", "--duration-ms", + "--env", "--fps", "--from", "--geo-location", @@ -85,6 +87,7 @@ const VALUE_FLAGS: ReadonlyArray = [ "--out", "--pattern", "--pause-ms", + "--pick", "--pixel-density", "--pixels", "--plan-digest", @@ -151,21 +154,65 @@ const VALUE_FLAGS: ReadonlyArray = [ "--wait", ]; +/** + * agent-device 0.21.36's flags whose value is a path. It ties a session's device claim to its cwd's + * workspace and refuses install, push and the like from another, so a bound launcher runs it in the + * directory that opened the session and resolves these, and path operands, against the caller's. + */ +const PATH_FLAGS: ReadonlyArray = [ + "--artifact", + "--artifacts-dir", + "-b", + "--baseline", + "--config", + "--dsym", + "--ios-simulator-device-set", + "--ios-xctest-derived-data-path", + "--ios-xctest-env-dir", + "--ios-xctestrun-file", + "--out", + "--project-root", + "--remote-config", + "--report-junit", + "--runtime-file", + "--search-path", + "--state-dir", + "--steps-file", +]; + // Help gets no bound flags (agent-device reads --config even for help); only args before `--` are flags. // agent-device 0.21.31 refuses some bound flags per command; connect/disconnect/auth/daemon would // replace T3's connection; device status reads this machine's claims. It reports a sandboxed shell and a // dropped tunnel alike, so check first, at --daemon-base-url if given, as agent-device prefers it. -const launcherSource = (node: string, entryPath: string, boundArgs: ReadonlyArray) => +const launcherSource = ( + node: string, + entryPath: string, + boundArgs: ReadonlyArray, + cwd: string | undefined, + targetsDir: string | undefined, +) => `import { spawn } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; import { connect } from "node:net"; +import { isAbsolute, join, resolve } from "node:path"; +import { pathToFileURL } from "node:url"; const entry = ${JSON.stringify(entryPath)}; +const workspace = ${JSON.stringify(cwd ?? null)}; const bound = ${JSON.stringify(boundArgs)}; const refused = new Map([["cdp", ["--platform", "--udid", "--config", "--session"]], ["connection", ["--platform", "--udid"]]]); const managed = ["connect", "disconnect", "auth", "daemon"]; const args = process.argv.slice(2); const end = args.indexOf("--"); const options = end < 0 ? args : args.slice(0, end); +// The unbound launcher hands a bound session to its own launcher, so both run in one workspace. +const targets = ${JSON.stringify(targetsDir ?? null)}; +const sessionAt = options.indexOf("--session"); +const session = options.find(arg => arg.startsWith("--session="))?.slice(10) ?? (sessionAt >= 0 ? options[sessionAt + 1] : undefined); +const delegate = targets && session && /^[\\w.-]+$/.test(session) && !/^\\.+$/.test(session) ? join(targets, session, "agent-device-launcher.mjs") : undefined; +if (delegate && existsSync(delegate)) { + const child = spawn(process.execPath, [delegate, ...args], { stdio: "inherit" }); + process.exit(await new Promise(done => { child.on("error", error => { console.error(error.message); done(1); }); child.on("exit", code => done(code ?? 1)); })); +} const valued = new Set(${JSON.stringify(VALUE_FLAGS)}); let name = ""; for (let index = 0; index < args.length; index++) { @@ -214,11 +261,49 @@ if (local) { process.exit(1); } } +if (workspace) { +const pathFlags = new Set(${JSON.stringify(PATH_FLAGS)}); +const absolute = value => value && value !== "-" && !isAbsolute(value) ? resolve(value) : value; +// A reporter starting with "." is a module path; a file URL keeps it one on Windows too. +const reporter = spec => spec.trim().startsWith(".") ? pathToFileURL(resolve(spec.trim())).href : spec.trim().startsWith("junit:") ? "junit:" + absolute(spec.trim().slice(6)) : spec; +const flagValue = (flag, value) => flag === "--reporter" ? reporter(value) : pathFlags.has(flag) ? absolute(value) : value; +const positionals = []; +// After the first \`--\` every argument is an operand, and agent-device still reads paths there. +let literal = false; +for (let index = 0; index < command.length; index++) { + const arg = command[index]; + if (literal) { positionals.push(index); continue; } + if (arg === "--") { literal = true; continue; } + const equals = arg.indexOf("="); + if (!arg.startsWith("-") || arg === "-") positionals.push(index); + else if (equals > 0) command[index] = arg.slice(0, equals + 1) + flagValue(arg.slice(0, equals), arg.slice(equals + 1)); + else if (valued.has(arg) && ++index < command.length) command[index] = flagValue(arg, command[index]); +} +const [, ...operands] = positionals; +const operand = position => operands[position] === undefined ? undefined : command[operands[position]]; +const pathOperands = { + install: [operands.length - 1], + reinstall: [1], + screenshot: [0], + replay: [operand(0) === "export" ? 1 : 0], + test: operands.map((_, position) => position), + record: ["start", "contact-sheet"].includes(operand(0)) ? [1] : [], + trace: [1], + diff: operand(0) === "screenshot" ? [1] : [], + session: operand(0) === "save-script" ? [1] : [], +}[name] ?? []; +for (const position of pathOperands) if (operands[position] !== undefined) command[operands[position]] = absolute(command[operands[position]]); +// A push payload is a file or inline JSON. +if (name === "push" && operands[1] !== undefined && existsSync(absolute(command[operands[1]]))) command[operands[1]] = absolute(command[operands[1]]); +// metro prepare defaults --project-root to its cwd, which is no longer the caller's. +const given = flag => options.some(arg => arg === flag || arg.startsWith(flag + "=")); +if (name === "metro" && operand(0) === "prepare" && !given("--project-root") && !given("--remote-config")) command.splice(end < 0 ? command.length : command.indexOf("--"), 0, "--project-root", resolve(".")); +} const env = { ...process.env, ELECTRON_RUN_AS_NODE: "1" }; delete env.AGENT_DEVICE_DAEMON_BASE_URL; delete env.AGENT_DEVICE_DAEMON_AUTH_TOKEN; delete env.AGENT_DEVICE_CONFIG; -const child = spawn(${JSON.stringify(node)}, [entry, ...command], { stdio: "inherit", env }); +const child = spawn(${JSON.stringify(node)}, [entry, ...command], { stdio: "inherit", env, ...(workspace ? { cwd: workspace } : {}) }); child.on("error", error => { console.error(error.message); process.exitCode = 1; }); child.on("exit", code => { process.exitCode = code ?? 1; }); `; @@ -228,6 +313,8 @@ const writeLauncher = Effect.fn("AgentDeviceShim.writeLauncher")(function* (inpu readonly dir: string; readonly entryPath: string; readonly boundArgs: ReadonlyArray; + readonly cwd?: string; + readonly targetsDir?: string; }) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -235,7 +322,10 @@ const writeLauncher = Effect.fn("AgentDeviceShim.writeLauncher")(function* (inpu const node = yield* resolveNodeExecutable("Device automation"); yield* fs.makeDirectory(input.dir, { recursive: true }); const launcherPath = path.join(input.dir, "agent-device-launcher.mjs"); - yield* fs.writeFileString(launcherPath, launcherSource(node, input.entryPath, input.boundArgs)); + yield* fs.writeFileString( + launcherPath, + launcherSource(node, input.entryPath, input.boundArgs, input.cwd, input.targetsDir), + ); if (platform === "win32") { const script = `@echo off\r\nsetlocal EnableExtensions DisableDelayedExpansion\r\nif not exist "${node}" (echo ${STALE_RUNTIME} 1>&2 & exit /b 1)\r\nset "ELECTRON_RUN_AS_NODE=1"\r\n"${node}" "${launcherPath}" %*\r\n`; const scriptPath = path.join(input.dir, "agent-device.cmd"); @@ -256,7 +346,12 @@ export const ensureAgentDeviceShim = Effect.fn("AgentDeviceShim.ensure")(functio }) { const path = yield* Path.Path; const shimDir = path.join(input.stateDir, SHIM_DIR); - yield* writeLauncher({ dir: shimDir, entryPath: input.entryPath, boundArgs: [] }); + yield* writeLauncher({ + dir: shimDir, + entryPath: input.entryPath, + boundArgs: [], + targetsDir: path.join(input.stateDir, TARGETS_DIR), + }); return shimDir; }); @@ -269,12 +364,16 @@ export const bindAgentDeviceLauncher = Effect.fn("AgentDeviceShim.bind")(functio readonly stateDir: string; readonly session: string; readonly targetArgs: ReadonlyArray; + /** The directory that opened the session, whose workspace agent-device ties the device claim to. */ + readonly cwd?: string | undefined; }) { const path = yield* Path.Path; + const dir = path.join(input.stateDir, TARGETS_DIR, input.session); return yield* writeLauncher({ - dir: path.join(input.stateDir, TARGETS_DIR, input.session), + dir, entryPath: input.entryPath, boundArgs: input.targetArgs, + cwd: input.cwd ?? dir, }); }); diff --git a/apps/server/src/device/AgentDeviceTarget.test.ts b/apps/server/src/device/AgentDeviceTarget.test.ts index bf180c9004dfd..4ade6ebe93075 100644 --- a/apps/server/src/device/AgentDeviceTarget.test.ts +++ b/apps/server/src/device/AgentDeviceTarget.test.ts @@ -3,6 +3,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { describe, expect, it } from "@effect/vitest"; import * as NodeChildProcess from "node:child_process"; import * as NodeNet from "node:net"; +import * as NodeURL from "node:url"; import * as NodeUtil from "node:util"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -144,6 +145,69 @@ exec '${process.execPath.replaceAll("'", "'\"'\"'")}' "$@" "--config", "/h.json", ]); + // agent-device runs in the launcher's directory, so relative paths resolve against the caller's. + expect( + yield* Effect.promise(() => + launch(bound, ["install", "com.example.app", "b/App.app", "--out=o.png"]), + ), + ).toEqual([ + "install", + "com.example.app", + path.resolve("b/App.app"), + `--out=${path.resolve("o.png")}`, + ...target, + ]); + expect( + yield* Effect.promise(() => + launch(bound, [ + "test", + "sample.ad", + "--env", + "APP_ID=a", + "-e", + "B=b", + "--reporter", + "./reporter.mjs", + "--reporter=junit:out/j.xml", + "--reporter", + "default", + ]), + ), + ).toEqual([ + "test", + path.resolve("sample.ad"), + "--env", + "APP_ID=a", + "-e", + "B=b", + "--reporter", + NodeURL.pathToFileURL(path.resolve("reporter.mjs")).href, + `--reporter=junit:${path.resolve("out/j.xml")}`, + "--reporter", + "default", + ...target, + ]); + expect( + yield* Effect.promise(() => launch(bound, ["push", "com.example.app", '{"a":1}'])), + ).toEqual(["push", "com.example.app", '{"a":1}', ...target]); + expect( + yield* Effect.promise(() => + launch(bound, ["replay", "export", "--out", "/o.yaml", "--", "flow.ad"]), + ), + ).toEqual(["replay", "export", "--out", "/o.yaml", ...target, "--", path.resolve("flow.ad")]); + expect( + yield* Effect.promise(() => + launch(bound, ["metro", "prepare", "--public-base-url", "https://h:8081"]), + ), + ).toEqual([ + "metro", + "prepare", + "--public-base-url", + "https://h:8081", + ...target, + "--project-root", + path.resolve("."), + ]); // After `--` everything is text: no help, no overrides, and bound flags go before it. for (const text of [["--help"], ["literal text", "--session", "mine"]]) { expect(yield* Effect.promise(() => launch(bound, ["fill", "@e5", "--", ...text]))).toEqual([ @@ -156,9 +220,9 @@ exec '${process.execPath.replaceAll("'", "'\"'\"'")}' "$@" } expect( yield* Effect.promise(() => - launch(shared, ["snapshot", "--config=/h.json", "--session=t3-a"]), + launch(shared, ["snapshot", "--config=/h.json", "--session=t3-unbound"]), ), - ).toEqual(["snapshot", "--config=/h.json", "--session=t3-a"]); + ).toEqual(["snapshot", "--config=/h.json", "--session=t3-unbound"]); yield* Effect.promise(() => expect( launch(shared, ["fill", "@e5", "--", "--config", "/h.json", "--session", "t3-a"]), @@ -255,6 +319,94 @@ exec '${process.execPath.replaceAll("'", "'\"'\"'")}' "$@" ), ); + // agent-device records a device claim's workspace from its own cwd (the nearest `.git` above it) + // and refuses install/uninstall/push from a different workspace, even for the same session. + it.effect( + "gives agent-device one workspace for its session whatever shell directory runs it", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-cwd-" }); + const entryPath = path.join(dir, "cli.mjs"); + yield* fs.writeFileString(entryPath, "console.log(process.cwd());"); + const command = yield* bindAgentDeviceLauncher({ + entryPath, + stateDir: dir, + session: "t3-a", + targetArgs: [ + "--platform", + "ios", + "--udid", + "UDID-1", + "--config", + "/h.json", + "--session", + "t3-a", + ], + }); + const launchFrom = Effect.fn(function* ( + repo: string, + args: ReadonlyArray, + launcher = command, + ) { + const cwd = path.join(dir, repo); + yield* fs.makeDirectory(path.join(cwd, ".git"), { recursive: true }); + const { stdout } = yield* Effect.promise(() => + exec( + process.execPath, + [path.join(path.dirname(launcher), "agent-device-launcher.mjs"), ...args], + { + cwd, + }, + ), + ); + return stdout.trim(); + }); + const opened = yield* launchFrom("mobile-app", ["open", "com.example.app"]); + const installed = yield* launchFrom("coordinator", [ + "install", + "com.example.app", + "/b/App.app", + ]); + expect(installed).toBe(opened); + const shared = yield* ensureAgentDeviceShim({ entryPath, stateDir: dir }); + expect( + yield* launchFrom( + "other", + [ + "install", + "com.example.app", + "/b/App.app", + "--config", + "/h.json", + "--session", + "t3-a", + ], + path.join(shared, "agent-device"), + ), + ).toBe(opened); + // A Simlock lease opened its claim from the thread's workspace, so its launcher runs there. + const workspace = path.join(dir, "workspace"); + yield* fs.makeDirectory(workspace); + const leased = yield* bindAgentDeviceLauncher({ + entryPath, + stateDir: dir, + session: "t3-lease", + targetArgs: ["--config", "/h.json", "--session", "t3-lease"], + cwd: workspace, + }); + expect( + yield* launchFrom("coordinator", ["install", "com.example.app", "/b/App.app"], leased), + ).toBe(workspace); + }).pipe( + Effect.scoped, + Effect.provideService(HostProcess.IsExecutable, false), + Effect.provideService(HostProcess.ExecutablePath, process.execPath), + Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ); + it("tells a released session from a close that failed or timed out", () => { const result = (code: number | null, stderr = "", timedOut = false) => ({ stdout: "", diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.ts index cf8aece6745e0..fdb6c4ee4361a 100644 --- a/apps/server/src/device/DeviceService.ts +++ b/apps/server/src/device/DeviceService.ts @@ -198,6 +198,7 @@ export class DeviceService extends Context.Service< readonly hostId: DeviceHostId; readonly deviceId: DeviceId; readonly targetArgs: ReadonlyArray; + readonly installDirectory?: string | undefined; }) => Effect.Effect, DeviceError>; readonly state: Effect.Effect; readonly subscribe: Effect.Effect, never, Scope.Scope>; @@ -261,6 +262,7 @@ export interface AgentDeviceLaunchers { readonly bind: (input: { readonly session: string; readonly targetArgs: ReadonlyArray; + readonly cwd?: string | undefined; }) => Effect.Effect; /** Removes every launcher whose session is not in `live`. */ readonly prune: (live: ReadonlySet) => Effect.Effect; @@ -1197,6 +1199,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* }), agentLauncher: Effect.fn("DeviceService.agentLauncher")(function* ({ targetArgs, + installDirectory, ...target }) { if (!launchers) @@ -1221,7 +1224,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* ) ) return Option.none(); - const launcher = yield* launchers.bind({ session, targetArgs }); + const launcher = yield* launchers.bind({ session, targetArgs, cwd: installDirectory }); boundLaunchers.set(session, launcher); return Option.some(launcher); }), diff --git a/apps/server/src/mcp/toolkits/device/handlers.ts b/apps/server/src/mcp/toolkits/device/handlers.ts index 099a9bae9e2d3..5b650f5f76be4 100644 --- a/apps/server/src/mcp/toolkits/device/handlers.ts +++ b/apps/server/src/mcp/toolkits/device/handlers.ts @@ -290,7 +290,11 @@ const handlers = { : agentDeviceTargetArgs({ ...device, id: agent.agentDeviceId })), ...agent.args, ]; - const launcher = yield* devices.agentLauncher({ ...opened, targetArgs }); + const launcher = yield* devices.agentLauncher({ + ...opened, + targetArgs, + installDirectory: agent.installDirectory, + }); if (Option.isNone(launcher)) { return yield* new DeviceToolUnavailableError({ reason: