Repository navigation
fix(server): bound agent-device launcher acts as one session from any directory #38625
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
9631ce5
e6244c6
431f190
3759582
afb9426
83de6fa
013714d
1acad2f
45253ca
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -36,6 +36,7 @@ const VALUE_FLAGS: ReadonlyArray<string> = [ | |
| "--crop-on", | ||
| "--custom-network", | ||
| "-d", | ||
| "-e", | ||
| "--daemon-auth-token", | ||
| "--daemon-base-url", | ||
| "--daemon-server-mode", | ||
|
|
@@ -46,6 +47,7 @@ const VALUE_FLAGS: ReadonlyArray<string> = [ | |
| "--device-orientation", | ||
| "--dsym", | ||
| "--duration-ms", | ||
| "--env", | ||
| "--fps", | ||
| "--from", | ||
| "--geo-location", | ||
|
|
@@ -85,6 +87,7 @@ const VALUE_FLAGS: ReadonlyArray<string> = [ | |
| "--out", | ||
| "--pattern", | ||
| "--pause-ms", | ||
| "--pick", | ||
| "--pixel-density", | ||
| "--pixels", | ||
| "--plan-digest", | ||
|
|
@@ -151,21 +154,65 @@ const VALUE_FLAGS: ReadonlyArray<string> = [ | |
| "--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<string> = [ | ||
| "--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<string>) => | ||
| const launcherSource = ( | ||
| node: string, | ||
| entryPath: string, | ||
| boundArgs: ReadonlyArray<string>, | ||
| 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; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Preserve agent-device's
|
||
| // 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]); | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| } | ||
| 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), | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Keep the caller directory literal when rebasing test globs. If the caller runs
|
||
| 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(".")); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Preserve a Metro project root supplied through If Apply the caller-directory fallback only when the effective project root is unset. Preserve the fallback for calls without a configured root.
|
||
| } | ||
| 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 } : {}) }); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Report a missing bound workspace before spawning the agent-device child. When the workspace recorded for a bound launcher no longer exists, Check that the bound workspace exists before spawning. If it does not, print a message that names the missing path and tells the caller to close and reopen the device session. Do not fall back to the caller's working directory. That fallback can bind the command to a different workspace than the one that holds the device claim.
|
||
| child.on("error", error => { console.error(error.message); process.exitCode = 1; }); | ||
| child.on("exit", code => { process.exitCode = code ?? 1; }); | ||
| `; | ||
|
|
@@ -228,14 +313,19 @@ const writeLauncher = Effect.fn("AgentDeviceShim.writeLauncher")(function* (inpu | |
| readonly dir: string; | ||
| readonly entryPath: string; | ||
| readonly boundArgs: ReadonlyArray<string>; | ||
| readonly cwd?: string; | ||
| readonly targetsDir?: string; | ||
| }) { | ||
| const fs = yield* FileSystem.FileSystem; | ||
| const path = yield* Path.Path; | ||
| const platform = yield* HostProcess.Platform; | ||
| 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<string>; | ||
| /** 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, | ||
| }); | ||
| }); | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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"]), | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Test The echo fixture accepts As per path instructions, “Test behavior that can break, including the logic changed by a bug fix.”
|
||
| ), | ||
| ).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<string>, | ||
| 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); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Resolve the expected workspace path before the CWD assertion. On macOS, the temporary directory can sit under a symlink, such as
|
||
| }).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: "", | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Select the last
--sessionvalue before delegation.With
--session=t3-a --session=t3-b, this line selectst3-a. Agent-device 0.21.36 uses the last value for this non-repeatable flag, so it executes sessiont3-b. The command therefore receives session A's workspace and missing target defaults instead of session B's. (raw.githubusercontent.com)Scan both
--session valueand--session=valuein argument order. Retain the last occurrence. Extend the existing shared-launcher case to cover this override while preserving single-session delegation.