Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/agent-device/host/agent-device-supervisor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ async function arrange(options: Options = {}) {
filesystem,
healthProbe: health,
home: simlockHome,
hostPlatform: "linux",
...supervisorRole(options),
leaseMaxTtlMs: options.leaseMaxTtlMs ?? 4 * 60 * 60_000,
logger,
Expand Down
6 changes: 4 additions & 2 deletions src/agent-device/host/agent-device-supervisor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
NO_ANDROID_DEVICE_SERIAL,
} from "../shared/daemon-environment.js";
import type { AgentDeviceHealthProbe } from "./health.js";
import { findAgentDevice } from "./install.js";
import { findAgentDevice, pathVariableOf } from "./install.js";

export type AgentDevicePlatform = "ios" | "android";

Expand Down Expand Up @@ -90,6 +90,7 @@ export interface AgentDeviceSupervisorOptions {
readonly filesystem: Filesystem;
readonly healthProbe: AgentDeviceHealthProbe;
readonly home: string;
readonly hostPlatform: NodeJS.Platform;
readonly ios?: AgentDeviceIosSigning;
readonly leaseMaxTtlMs: number;
readonly logger: Logger;
Expand Down Expand Up @@ -324,7 +325,8 @@ export class AgentDeviceSupervisor {
const install = await findAgentDevice(
o.filesystem,
o.config.command,
o.baseEnvironment["PATH"],
pathVariableOf(o.baseEnvironment),
o.hostPlatform,
);
if (!install.ok) {
this.#fail(install.reason, install.message);
Expand Down
180 changes: 180 additions & 0 deletions src/agent-device/host/install.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { describe, expect, it } from "vitest";

import { MemoryFilesystem, NodeFilesystem } from "../../ports/index.js";
import { findAgentDevice, pathVariableOf } from "./install.js";

const npm = "/Users/me/AppData/Roaming/npm";
const packageRoot = `${npm}/node_modules/agent-device`;

/** why: npm on Windows lays out a global install as a `.cmd` shim beside `node_modules`, every file 0o666. */
async function windowsNpmInstall(
options: { readonly bin?: unknown; readonly shim?: boolean } = {},
): Promise<MemoryFilesystem> {
const filesystem = new MemoryFilesystem();
await filesystem.mkdirp(`${packageRoot}/bin`);
await filesystem.mkdirp(`${packageRoot}/dist/src/internal`);
if (options.shim !== false)
await filesystem.writeFileAtomic(`${npm}/agent-device.cmd`, "@node ...");
await filesystem.writeFileAtomic(
`${packageRoot}/package.json`,
JSON.stringify({
bin: options.bin ?? { "agent-device": "bin/agent-device.mjs" },
name: "agent-device",
}),
);
await filesystem.writeFileAtomic(`${packageRoot}/bin/agent-device.mjs`, "#!/usr/bin/env node\n");
await filesystem.writeFileAtomic(`${packageRoot}/dist/src/internal/daemon.js`, "");
for (const path of [`${npm}/agent-device.cmd`, `${packageRoot}/bin/agent-device.mjs`]) {
if (await filesystem.exists(path)) filesystem.defineAttributes(path, { mode: 0o666 });
}
return filesystem;
}

// why: pure lookup rules, per platform, with many cases the supervisor's own tests reach only one at a time.
describe("findAgentDevice", () => {
it.each([
["an object", { "agent-device": "bin/agent-device.mjs" }],
["a string", "./bin/agent-device.mjs"],
])(
"finds an npm .cmd shim on a Windows PATH and stands in its package's bin, named as %s",
async (_form, bin) => {
const filesystem = await windowsNpmInstall({ bin });

await expect(
findAgentDevice(filesystem, "agent-device", `/Windows/System32;${npm};/other`, "win32"),
).resolves.toEqual({
entry: `${packageRoot}/dist/src/internal/daemon.js`,
ok: true,
realPath: `${packageRoot}/bin/agent-device.mjs`,
});
},
);

it("finds a local install's shim in node_modules/.bin, its package beside .bin", async () => {
const project = "/work/app/node_modules";
const filesystem = new MemoryFilesystem();
await filesystem.mkdirp(`${project}/.bin`);
await filesystem.mkdirp(`${project}/agent-device/bin`);
await filesystem.mkdirp(`${project}/agent-device/dist/src`);
await filesystem.writeFileAtomic(`${project}/.bin/agent-device.cmd`, "@node ...");
await filesystem.writeFileAtomic(
`${project}/agent-device/package.json`,
JSON.stringify({ bin: { "agent-device": "bin/agent-device.mjs" }, name: "agent-device" }),
);
await filesystem.writeFileAtomic(`${project}/agent-device/bin/agent-device.mjs`, "");
await filesystem.writeFileAtomic(`${project}/agent-device/dist/src/daemon.js`, "");

await expect(
findAgentDevice(filesystem, "agent-device", `/Windows;${project}/.bin/`, "win32"),
).resolves.toEqual({
entry: `${project}/agent-device/dist/src/daemon.js`,
ok: true,
realPath: `${project}/agent-device/bin/agent-device.mjs`,
});
});

it.each([
["a command name ending in .cmd, looked up on PATH", "agent-device.CMD", npm],
["a configured path to the shim", `${npm}/agent-device.cmd`, undefined],
])("stands in the package's bin for %s on Windows", async (_case, command, pathVariable) => {
const filesystem = await windowsNpmInstall();

await expect(findAgentDevice(filesystem, command, pathVariable, "win32")).resolves.toEqual({
entry: `${packageRoot}/dist/src/internal/daemon.js`,
ok: true,
realPath: `${packageRoot}/bin/agent-device.mjs`,
});
});

it("does not take a package with no .cmd shim beside it as the command on Windows", async () => {
const filesystem = await windowsNpmInstall({ shim: false });

await expect(findAgentDevice(filesystem, "agent-device", npm, "win32")).resolves.toMatchObject({
ok: false,
reason: "not-found",
});
});

it("accepts a configured path to the bin file on Windows, where no file has an execute bit", async () => {
const filesystem = await windowsNpmInstall();
const bin = `${packageRoot}/bin/agent-device.mjs`;

await expect(findAgentDevice(filesystem, bin, undefined, "win32")).resolves.toMatchObject({
ok: true,
realPath: bin,
});
await expect(findAgentDevice(filesystem, bin, undefined, "linux")).resolves.toMatchObject({
ok: false,
reason: "not-found",
});
});

it("still splits PATH on ':' and ignores .cmd shims off Windows", async () => {
const filesystem = await windowsNpmInstall();
await filesystem.mkdirp("/opt/bin");
await filesystem.writeFileAtomic("/opt/bin/agent-device", "#!/bin/sh\n");
filesystem.defineAttributes("/opt/bin/agent-device", { mode: 0o755 });

await expect(
findAgentDevice(filesystem, "agent-device", `/usr/bin:${npm}`, "linux"),
).resolves.toMatchObject({ ok: false, reason: "not-found" });
await expect(
findAgentDevice(filesystem, "agent-device", "/usr/bin:/opt/bin", "linux"),
).resolves.toMatchObject({ ok: false, reason: "not-agent-device" });
});

it("takes a command with a backslash as a path on Windows only", async () => {
const filesystem = new MemoryFilesystem();
const command = "C:\\Users\\me\\agent-device.mjs";

await expect(findAgentDevice(filesystem, command, undefined, "win32")).resolves.toMatchObject({
message: `agent-device not found: ${command} is not an executable file`,
});
await expect(findAgentDevice(filesystem, command, undefined, "linux")).resolves.toMatchObject({
message: `agent-device not found: "${command}" is not on PATH`,
});
});
});

describe.runIf(process.platform === "win32")("findAgentDevice on Windows", () => {
it("finds a local install from a PATH entry that is a project's node_modules .bin, written with backslashes", async () => {
const directory = await mkdtemp(join(tmpdir(), "simlock agent-device "));
const modules = join(directory, "node_modules");
const packageRoot = join(modules, "agent-device");
try {
await mkdir(join(modules, ".bin"), { recursive: true });
await mkdir(join(packageRoot, "bin"), { recursive: true });
await mkdir(join(packageRoot, "dist", "src"), { recursive: true });
await writeFile(join(modules, ".bin", "agent-device.cmd"), "@node ...");
await writeFile(
join(packageRoot, "package.json"),
JSON.stringify({ bin: { "agent-device": "bin/agent-device.mjs" }, name: "agent-device" }),
);
await writeFile(join(packageRoot, "bin", "agent-device.mjs"), "");
await writeFile(join(packageRoot, "dist", "src", "daemon.js"), "");

await expect(
findAgentDevice(new NodeFilesystem(), "agent-device", join(modules, ".bin"), "win32"),
).resolves.toMatchObject({
ok: true,
realPath: join(packageRoot, "bin", "agent-device.mjs"),
});
} finally {
await rm(directory, { force: true, recursive: true });
}
});
});

describe("pathVariableOf", () => {
it.each([
["PATH", { PATH: "/usr/bin" }, "/usr/bin"],
["Windows' Path", { Path: "C:\\npm;C:\\bin" }, "C:\\npm;C:\\bin"],
["none", { HOME: "/home/me" }, undefined],
])("reads %s", (_name, environment, expected) => {
expect(pathVariableOf(environment)).toBe(expected);
});
});
106 changes: 95 additions & 11 deletions src/agent-device/host/install.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { dirname } from "node:path";
import { dirname, win32 } from "node:path";

import { type Filesystem } from "../../ports/index.js";

Expand All @@ -10,31 +10,114 @@ export type AgentDeviceInstall =
readonly message: string;
};

async function isExecutableFile(filesystem: Filesystem, path: string): Promise<boolean> {
// why: Windows has no execute bit; Node reports a file there as 0o666 (0o444 when read-only), so any file counts.
async function isExecutableFile(
filesystem: Filesystem,
path: string,
windows: boolean,
): Promise<boolean> {
try {
const details = await filesystem.stat(path);
return details.kind === "file" && ((details.mode ?? 0) & 0o111) !== 0;
return details.kind === "file" && (windows || ((details.mode ?? 0) & 0o111) !== 0);
} catch {
return false;
}
}

const SHIM_SUFFIX = /\.cmd$/i;

/**
* why: npm on Windows installs a `<command>.cmd` shim, not a symlink. `node` cannot run the shim,
* and its real path is itself, so the package's own `bin` file stands in for it: `--version` runs
* it, and the package root is above it. A configured name or path may already end in `.cmd`.
*/
async function npmShimTarget(
filesystem: Filesystem,
directory: string,
command: string,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
): Promise<string | undefined> {
const name = command.replace(SHIM_SUFFIX, "");
const shimDirectory = directory.replace(/[\\/]+$/, "");
if (!(await isExecutableFile(filesystem, `${shimDirectory}/${name}.cmd`, true))) return undefined;
return packageBin(filesystem, packageRootBeside(shimDirectory, name), name);
}

// why: a global install puts its shims beside `node_modules`; a local one puts them in `node_modules/.bin`, beside the package.
function packageRootBeside(shimDirectory: string, name: string): string {
return /(^|[\\/])node_modules[\\/]\.bin$/i.test(shimDirectory)
? `${win32.dirname(shimDirectory)}/${name}`
: `${shimDirectory}/node_modules/${name}`;
}

async function packageBin(
filesystem: Filesystem,
packageRoot: string,
name: string,
): Promise<string | undefined> {
try {
const { bin } = JSON.parse(await filesystem.readFile(`${packageRoot}/package.json`)) as {
bin?: unknown;
};
const relative =
typeof bin === "string" ? bin : (bin as Record<string, unknown> | undefined)?.[name];
if (typeof relative !== "string") return undefined;
const target = `${packageRoot}/${relative.replace(/^\.\//, "")}`;
return (await isExecutableFile(filesystem, target, true)) ? target : undefined;
} catch {
return undefined;
}
}

function isPath(command: string, windows: boolean): boolean {
return command.includes("/") || (windows && command.includes("\\"));
}

async function locatePath(
filesystem: Filesystem,
command: string,
windows: boolean,
): Promise<string | undefined> {
if (windows && SHIM_SUFFIX.test(command)) {
return npmShimTarget(filesystem, win32.dirname(command), win32.basename(command));
}
return (await isExecutableFile(filesystem, command, windows)) ? command : undefined;
}

async function executableIn(
filesystem: Filesystem,
directory: string,
command: string,
): Promise<string | undefined> {
const candidate = `${directory}/${command}`;
return (await isExecutableFile(filesystem, candidate, false)) ? candidate : undefined;
}

async function locate(
filesystem: Filesystem,
command: string,
pathVariable: string | undefined,
platform: NodeJS.Platform,
): Promise<string | undefined> {
if (command.includes("/")) {
return (await isExecutableFile(filesystem, command)) ? command : undefined;
}
for (const directory of (pathVariable ?? "").split(":")) {
const windows = platform === "win32";
if (isPath(command, windows)) return locatePath(filesystem, command, windows);
const lookIn = windows ? npmShimTarget : executableIn;
// why: Windows separates PATH entries with `;`, and its drive letters hold a `:`.
for (const directory of (pathVariable ?? "").split(windows ? ";" : ":")) {
if (directory === "") continue;
const candidate = `${directory}/${command}`;
if (await isExecutableFile(filesystem, candidate)) return candidate;
const candidate = await lookIn(filesystem, directory, command);
if (candidate !== undefined) return candidate;
}
return undefined;
}

/** why: on Windows the variable is `Path`, and a copy of `process.env` loses its case-insensitive lookup. */
export function pathVariableOf(environment: NodeJS.ProcessEnv): string | undefined {
return (
environment["PATH"] ??
Object.entries(environment).find(([key]) => key.toUpperCase() === "PATH")?.[1]
);
}

// why: a pnpm global install puts a shell launcher in PNPM_HOME/bin, not a symlink into the
// package; the launcher records the real CLI in a `cmd-shim-target` comment.
async function pnpmShimTarget(filesystem: Filesystem, file: string): Promise<string | undefined> {
Expand All @@ -47,12 +130,13 @@ export async function findAgentDevice(
filesystem: Filesystem,
command: string,
pathVariable: string | undefined,
platform: NodeJS.Platform,
): Promise<AgentDeviceInstall> {
const found = await locate(filesystem, command, pathVariable);
const found = await locate(filesystem, command, pathVariable, platform);
const notFound = {
ok: false,
reason: "not-found",
message: command.includes("/")
message: isPath(command, platform === "win32")
? `agent-device not found: ${command} is not an executable file`
: `agent-device not found: "${command}" is not on PATH`,
} as const;
Expand Down
1 change: 1 addition & 0 deletions src/agent-device/host/upstream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ async function arrange(version: string) {
filesystem,
healthProbe: health,
home,
hostPlatform: "linux",
leaseMaxTtlMs,
logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }),
nodePath,
Expand Down
1 change: 1 addition & 0 deletions src/agent-device/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ export function createWorkerWith(
logger: ctx.logger,
nodePath: ctx.nodePath,
nodeVersion: ctx.nodeVersion,
hostPlatform: ctx.hostPlatform,
platforms: ctx.platforms,
processRunner: ctx.processRunner,
processSupervisor: ctx.processSupervisor,
Expand Down
1 change: 1 addition & 0 deletions src/daemon/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,7 @@ async function composeDaemon(
leaseEnvironment,
nodePath: process.execPath,
nodeVersion: process.versions.node,
hostPlatform: process.platform,
platforms: drivers.map((driver) => driver.platform),
processRunner,
processSupervisor,
Expand Down
1 change: 1 addition & 0 deletions src/modules/testing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ export async function fakeWorkerContext<C>(name: string, config: C): Promise<Fak
name,
nodePath: "/usr/bin/node",
nodeVersion: "22.0.0",
hostPlatform: "linux",
platforms: ["ios"],
processRunner,
processSupervisor,
Expand Down
Loading
Loading