diff --git a/apps/server/src/device/AgentDeviceShim.ts b/apps/server/src/device/AgentDeviceShim.ts index e5b42557a1e10..553c40529200c 100644 --- a/apps/server/src/device/AgentDeviceShim.ts +++ b/apps/server/src/device/AgentDeviceShim.ts @@ -7,6 +7,7 @@ import * as Path from "effect/Path"; const SHIM_DIR = "device/bin"; const TARGETS_DIR = "device/targets"; +const CLAIM_DIRECTORY_FILE = "claim-directory"; const STALE_RUNTIME = "This agent-device command is out of date because T3 Code moved or updated its runtime. Call device_open again for a fresh one."; @@ -151,14 +152,50 @@ const VALUE_FLAGS: ReadonlyArray = [ "--wait", ]; +/** + * agent-device 0.21.36's commands that take or check a session's claim on its device. It records the + * directory `open` ran in as the claim's workspace and refuses the rest from outside that repository, + * so a bound launcher runs these in one directory and resolves their paths against the caller's. + */ +const CLAIM_COMMANDS: ReadonlyArray = [ + "open", + "install", + "reinstall", + "uninstall", + "install-from-source", + "push", + "prepare", + "boot", + "shutdown", +]; + +/** The flags those commands accept whose value is a path. */ +const CLAIM_PATH_FLAGS: ReadonlyArray = [ + "--config", + "--ios-simulator-device-set", + "--ios-xctest-derived-data-path", + "--ios-xctest-env-dir", + "--ios-xctestrun-file", + "--launch-console", + "--remote-config", + "--save-script", + "--state-dir", +]; + // 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, + claim: { readonly directory: string } | { readonly targetsDir: string }, +) => `import { spawn } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; import { connect } from "node:net"; +import { isAbsolute, join, resolve } from "node:path"; const entry = ${JSON.stringify(entryPath)}; const bound = ${JSON.stringify(boundArgs)}; const refused = new Map([["cdp", ["--platform", "--udid", "--config", "--session"]], ["connection", ["--platform", "--udid"]]]); @@ -214,11 +251,37 @@ if (local) { process.exit(1); } } +// The shared launcher uses the directory of the session's bound launcher, so both hold one claim. +const targets = ${JSON.stringify("targetsDir" in claim ? claim.targetsDir : null)}; +const session = targets ? valueOf("--session") ?? "" : ""; +const recorded = () => { try { return readFileSync(join(targets, session, ${JSON.stringify(CLAIM_DIRECTORY_FILE)}), "utf8"); } catch { return null; } }; +const claimDirectory = targets ? (/^[\\w-][\\w.-]*$/.test(session) ? recorded() : null) : ${JSON.stringify("directory" in claim ? claim.directory : null)}; +const cwd = !informational && claimDirectory && ${JSON.stringify(CLAIM_COMMANDS)}.includes(name) && existsSync(claimDirectory) ? claimDirectory : undefined; +if (cwd) { + const pathFlags = new Set(${JSON.stringify(CLAIM_PATH_FLAGS)}); + const url = /^[a-zA-Z][a-zA-Z0-9+.-]*:/; + const absolute = value => !value || isAbsolute(value) || value.startsWith("~") || url.test(value) ? value : resolve(value); + const operands = []; + for (let index = 0; index < command.length; index++) { + const arg = command[index]; + if (arg === "--") { for (let rest = index + 1; rest < command.length; rest++) operands.push(rest); break; } + if (!arg.startsWith("-")) { operands.push(index); continue; } + const equals = arg.indexOf("="); + const flag = equals < 0 ? arg : arg.slice(0, equals); + if (equals >= 0) { if (pathFlags.has(flag)) command[index] = flag + "=" + absolute(arg.slice(equals + 1)); } + else if (valued.has(flag)) { if (++index < command.length && pathFlags.has(flag)) command[index] = absolute(command[index]); } + // agent-device reads the word after --save-script as its path only when it looks like one. + else if (flag === "--save-script" && /[\\/]/.test(command[index + 1] ?? "")) { index++; command[index] = absolute(command[index]); } + } + const file = name === "push" || name === "reinstall" ? operands[2] : name === "install" && operands.length > 1 ? operands.at(-1) : undefined; + // A push payload is a file or inline JSON. + if (file !== undefined && (name !== "push" || existsSync(resolve(command[file])))) command[file] = absolute(command[file]); +} 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, ...(cwd ? { cwd } : {}) }); child.on("error", error => { console.error(error.message); process.exitCode = 1; }); child.on("exit", code => { process.exitCode = code ?? 1; }); `; @@ -228,6 +291,7 @@ const writeLauncher = Effect.fn("AgentDeviceShim.writeLauncher")(function* (inpu readonly dir: string; readonly entryPath: string; readonly boundArgs: ReadonlyArray; + readonly claim: { readonly directory: string } | { readonly targetsDir: string }; }) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -235,7 +299,12 @@ 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.claim), + ); + if ("directory" in input.claim) + yield* fs.writeFileString(path.join(input.dir, CLAIM_DIRECTORY_FILE), input.claim.directory); 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 +325,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: [], + claim: { targetsDir: path.join(input.stateDir, TARGETS_DIR) }, + }); return shimDir; }); @@ -269,12 +343,16 @@ export const bindAgentDeviceLauncher = Effect.fn("AgentDeviceShim.bind")(functio readonly stateDir: string; readonly session: string; readonly targetArgs: ReadonlyArray; + /** Where the host already opened the session; without it the launcher's own directory. */ + readonly openedIn?: 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, + claim: { directory: input.openedIn ?? dir }, }); }); diff --git a/apps/server/src/device/AgentDeviceTarget.test.ts b/apps/server/src/device/AgentDeviceTarget.test.ts index bf180c9004dfd..e2d2c698fee9f 100644 --- a/apps/server/src/device/AgentDeviceTarget.test.ts +++ b/apps/server/src/device/AgentDeviceTarget.test.ts @@ -180,6 +180,100 @@ exec '${process.execPath.replaceAll("'", "'\"'\"'")}' "$@" ), ); + it.effect("runs a session's claim commands in one directory, with the caller's paths", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-cwd-" }), + ); + const entryPath = path.join(dir, "cli.mjs"); + yield* fs.writeFileString( + entryPath, + "console.log(JSON.stringify({ cwd: process.cwd(), args: process.argv.slice(2) }));", + ); + const caller = path.join(dir, "caller"); + const openedIn = path.join(dir, "workspace"); + yield* fs.makeDirectory(caller); + yield* fs.makeDirectory(openedIn); + yield* fs.writeFileString(path.join(caller, "payload.json"), "{}"); + const target = ["--config", "/h.json", "--session", "t3-a"]; + const bind = (session: string, opened?: string) => + bindAgentDeviceLauncher({ + entryPath, + stateDir: dir, + session, + targetArgs: target, + openedIn: opened, + }).pipe(Effect.map(path.dirname)); + const own = yield* bind("t3-a"); + const hostOpened = yield* bind("t3-b", openedIn); + const shared = yield* ensureAgentDeviceShim({ entryPath, stateDir: dir }); + const launch = (launcher: string, args: ReadonlyArray) => + exec(process.execPath, [path.join(launcher, "agent-device-launcher.mjs"), ...args], { + cwd: caller, + }).then((result) => JSON.parse(result.stdout)); + const here = (file: string) => path.join(caller, file); + const cases: ReadonlyArray< + readonly [launcher: string, args: ReadonlyArray, cwd: string, ReadonlyArray] + > = [ + [ + own, + ["open", "com.app", "--launch-console", "logs/c.log", "--save-script", "./s.ad"], + own, + [ + "open", + "com.app", + "--launch-console", + here("logs/c.log"), + "--save-script", + here("s.ad"), + ], + ], + [own, ["open", "--save-script", "com.app"], own, ["open", "--save-script", "com.app"]], + [ + own, + ["install", "com.app", "build/App.app"], + own, + ["install", "com.app", here("build/App.app")], + ], + [hostOpened, ["install", "App.apk"], openedIn, ["install", here("App.apk")]], + [own, ["install", "remote:/tmp/App.apk"], own, ["install", "remote:/tmp/App.apk"]], + [own, ["reinstall", "com.app"], own, ["reinstall", "com.app"]], + [own, ["push", "com.app", "payload.json"], own, ["push", "com.app", here("payload.json")]], + [own, ["push", "com.app", '{"aps":{}}'], own, ["push", "com.app", '{"aps":{}}']], + [own, ["screenshot", "out.png"], caller, ["screenshot", "out.png"]], + [ + own, + ["metro", "prepare", "--public-base-url", "https://example.com:8081"], + caller, + ["metro", "prepare", "--public-base-url", "https://example.com:8081"], + ], + ]; + for (const [launcher, args, cwd, expected] of cases) { + expect(yield* Effect.promise(() => launch(launcher, args))).toEqual({ + cwd, + args: [...expected, ...target], + }); + } + // The shared launcher claims in the session's bound launcher directory, or the caller's without one. + for (const [session, cwd] of [ + ["t3-a", own], + ["t3-b", openedIn], + ["t3-none", caller], + ["../t3-a", caller], + ] as const) { + const args = ["open", "App.app", "--config", "/h.json", "--session", session]; + expect(yield* Effect.promise(() => launch(shared, args))).toEqual({ cwd, args }); + } + }).pipe( + Effect.scoped, + Effect.provideService(HostProcess.IsExecutable, false), + Effect.provideService(HostProcess.ExecutablePath, process.execPath), + Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ); + it.effect("passes each command only the bound flags agent-device accepts for it", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.ts index cf8aece6745e0..ff00f987dba81 100644 --- a/apps/server/src/device/DeviceService.ts +++ b/apps/server/src/device/DeviceService.ts @@ -198,6 +198,8 @@ export class DeviceService extends Context.Service< readonly hostId: DeviceHostId; readonly deviceId: DeviceId; readonly targetArgs: ReadonlyArray; + /** The directory the host opened the agent-device session in, when it opened one. */ + readonly openedIn?: string | undefined; }) => Effect.Effect, DeviceError>; readonly state: Effect.Effect; readonly subscribe: Effect.Effect, never, Scope.Scope>; @@ -261,6 +263,7 @@ export interface AgentDeviceLaunchers { readonly bind: (input: { readonly session: string; readonly targetArgs: ReadonlyArray; + readonly openedIn?: string | undefined; }) => Effect.Effect; /** Removes every launcher whose session is not in `live`. */ readonly prune: (live: ReadonlySet) => Effect.Effect; @@ -1197,6 +1200,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* }), agentLauncher: Effect.fn("DeviceService.agentLauncher")(function* ({ targetArgs, + openedIn, ...target }) { if (!launchers) @@ -1221,7 +1225,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, openedIn }); 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..3b8a9f0ecdb6f 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, + openedIn: agent.installDirectory, + }); if (Option.isNone(launcher)) { return yield* new DeviceToolUnavailableError({ reason: