From 41edfd80185130eb0a8752b507d88a60e3a38eb3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 23:37:47 +0000 Subject: [PATCH 1/3] fix(server): bound agent-device launcher keeps one device claim from any directory agent-device records the directory `open` ran in as the workspace of a session's device claim, and refuses install, reinstall, uninstall, push, prepare, boot and shutdown from a directory outside that repository. The bound launcher inherited the shell's directory, so a thread that opened from one directory and installed from another was refused by its own session with DEVICE_IN_USE. The launcher now runs only those claim commands in one directory: the one the host opened the session in (a Simlock lease), else the launcher's own. Their relative path arguments are resolved against the caller's directory first. Every other command, metro included, still runs in the caller's directory with its arguments untouched. Fixes pingdotgg/t3code#38603 Co-Authored-By: Claude Fable 5.2 --- apps/server/src/device/AgentDeviceShim.ts | 74 ++++++++++++++++- .../src/device/AgentDeviceTarget.test.ts | 83 +++++++++++++++++++ apps/server/src/device/DeviceService.ts | 6 +- .../src/mcp/toolkits/device/handlers.ts | 6 +- 4 files changed, 163 insertions(+), 6 deletions(-) diff --git a/apps/server/src/device/AgentDeviceShim.ts b/apps/server/src/device/AgentDeviceShim.ts index e5b42557a1e10..ba954eddd202f 100644 --- a/apps/server/src/device/AgentDeviceShim.ts +++ b/apps/server/src/device/AgentDeviceShim.ts @@ -151,14 +151,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, + claimDirectory: string | undefined, +) => `import { spawn } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; import { connect } from "node:net"; +import { isAbsolute, 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 +250,33 @@ if (local) { process.exit(1); } } +const claimDirectory = ${JSON.stringify(claimDirectory ?? 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 +286,7 @@ const writeLauncher = Effect.fn("AgentDeviceShim.writeLauncher")(function* (inpu readonly dir: string; readonly entryPath: string; readonly boundArgs: ReadonlyArray; + readonly claimDirectory?: string; }) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -235,7 +294,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.claimDirectory), + ); 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"); @@ -269,12 +331,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, + claimDirectory: input.openedIn ?? dir, }); }); diff --git a/apps/server/src/device/AgentDeviceTarget.test.ts b/apps/server/src/device/AgentDeviceTarget.test.ts index bf180c9004dfd..1ad4b0f861bd9 100644 --- a/apps/server/src/device/AgentDeviceTarget.test.ts +++ b/apps/server/src/device/AgentDeviceTarget.test.ts @@ -180,6 +180,89 @@ 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 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], + }); + } + }).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: From 65c94ec79d18537f2e348e6912dd1d9cb5dd32f5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 23:46:50 +0000 Subject: [PATCH 2/3] fix(server): shared agent-device launcher claims in its session's bound directory A session opened through the shared launcher claimed its device under the caller's directory, while the bound launcher of the same session ran its claim commands in the session directory, so the two refused each other. The shared launcher now runs claim commands in the directory of the bound launcher for the session it is given, and in the caller's when there is none. Co-Authored-By: Claude Fable 5.2 --- apps/server/src/device/AgentDeviceShim.ts | 22 +++++++++++++------ .../src/device/AgentDeviceTarget.test.ts | 10 +++++++++ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/apps/server/src/device/AgentDeviceShim.ts b/apps/server/src/device/AgentDeviceShim.ts index ba954eddd202f..2329d2f9afff9 100644 --- a/apps/server/src/device/AgentDeviceShim.ts +++ b/apps/server/src/device/AgentDeviceShim.ts @@ -189,12 +189,12 @@ const launcherSource = ( node: string, entryPath: string, boundArgs: ReadonlyArray, - claimDirectory: string | undefined, + 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, resolve } from "node:path"; +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"]]]); @@ -250,7 +250,10 @@ if (local) { process.exit(1); } } -const claimDirectory = ${JSON.stringify(claimDirectory ?? null)}; +// 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 claimDirectory = targets ? (/^[\\w-][\\w.-]*$/.test(session) ? join(targets, session) : 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)}); @@ -286,7 +289,7 @@ const writeLauncher = Effect.fn("AgentDeviceShim.writeLauncher")(function* (inpu readonly dir: string; readonly entryPath: string; readonly boundArgs: ReadonlyArray; - readonly claimDirectory?: string; + readonly claim: { readonly directory: string } | { readonly targetsDir: string }; }) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -296,7 +299,7 @@ const writeLauncher = Effect.fn("AgentDeviceShim.writeLauncher")(function* (inpu const launcherPath = path.join(input.dir, "agent-device-launcher.mjs"); yield* fs.writeFileString( launcherPath, - launcherSource(node, input.entryPath, input.boundArgs, input.claimDirectory), + launcherSource(node, input.entryPath, input.boundArgs, input.claim), ); 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`; @@ -318,7 +321,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; }); @@ -340,7 +348,7 @@ export const bindAgentDeviceLauncher = Effect.fn("AgentDeviceShim.bind")(functio dir, entryPath: input.entryPath, boundArgs: input.targetArgs, - claimDirectory: input.openedIn ?? dir, + claim: { directory: input.openedIn ?? dir }, }); }); diff --git a/apps/server/src/device/AgentDeviceTarget.test.ts b/apps/server/src/device/AgentDeviceTarget.test.ts index 1ad4b0f861bd9..3f78b6a5ca29f 100644 --- a/apps/server/src/device/AgentDeviceTarget.test.ts +++ b/apps/server/src/device/AgentDeviceTarget.test.ts @@ -208,6 +208,7 @@ exec '${process.execPath.replaceAll("'", "'\"'\"'")}' "$@" }).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, @@ -255,6 +256,15 @@ exec '${process.execPath.replaceAll("'", "'\"'\"'")}' "$@" 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-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), From 8c77695fd88ac8b8b07b1427f7a74aa22c76af86 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 00:05:41 +0000 Subject: [PATCH 3/3] fix(server): shared agent-device launcher reads its session's recorded claim directory A bound launcher whose host opened the session elsewhere runs claim commands in that directory, not in its own. It now records the directory beside itself, and the shared launcher reads it, so both always claim in the same place. Co-Authored-By: Claude Fable 5.2 --- apps/server/src/device/AgentDeviceShim.ts | 6 +++++- apps/server/src/device/AgentDeviceTarget.test.ts | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/server/src/device/AgentDeviceShim.ts b/apps/server/src/device/AgentDeviceShim.ts index 2329d2f9afff9..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."; @@ -253,7 +254,8 @@ if (local) { // 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 claimDirectory = targets ? (/^[\\w-][\\w.-]*$/.test(session) ? join(targets, session) : null) : ${JSON.stringify("directory" in claim ? claim.directory : null)}; +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)}); @@ -301,6 +303,8 @@ const writeLauncher = Effect.fn("AgentDeviceShim.writeLauncher")(function* (inpu 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"); diff --git a/apps/server/src/device/AgentDeviceTarget.test.ts b/apps/server/src/device/AgentDeviceTarget.test.ts index 3f78b6a5ca29f..e2d2c698fee9f 100644 --- a/apps/server/src/device/AgentDeviceTarget.test.ts +++ b/apps/server/src/device/AgentDeviceTarget.test.ts @@ -259,6 +259,7 @@ exec '${process.execPath.replaceAll("'", "'\"'\"'")}' "$@" // 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) {