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
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ whether or not the command is found), the module host writes `<data dir>/agent-d

```json
{
"clientId": "a51a51a51a51a51a",
"daemonAuthToken": "slk_…",
"daemonBaseUrl": "http://127.0.0.1:4701/v1/agent-device",
"daemonTransport": "http",
Expand Down
9 changes: 9 additions & 0 deletions e2e/console/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,15 @@ export async function startDaemon(
...(mode === "worker" ? FAKE_CAPACITY : {}),
http: httpConfig,
...extraConfig,
// why: a standalone worker has agent-device on by default (ADR 0046); the console specs do not ask for it, and a test's own `capabilities` (a stream, say) must not replace this pin, so it merges one level deep.
...(mode === "worker"
? {
capabilities: {
"agent-device": { enabled: false },
...(extraConfig.capabilities as object | undefined),
},
}
: {}),
}),
);
if (options.driverScript !== undefined) {
Expand Down
65 changes: 63 additions & 2 deletions e2e/helpers/agent-device.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ interface MadeAgent {
readonly env: SharedTestEnv;
readonly agent: Agent;
readonly background: Set<CliBackgroundHandle>;
// why: the profile token belongs to the worker, not to the agent, so cleanup leaves it.
readonly keepToken?: boolean;
}

const made: MadeAgent[] = [];
Expand Down Expand Up @@ -159,16 +161,75 @@ export async function makeAgent(env: SharedTestEnv, name: string): Promise<Agent
return agent;
}

const PROFILE_TOKEN_LABEL = "agent-device on this Mac";

// why: the agent a local user is, per ADR 0046: no token in its environment, the worker's profile file named once at connect, and its own --session on every command.
export async function makeProfileAgent(env: SharedTestEnv, name: string): Promise<Agent> {
const profilePath = join(env.dataDirectory, "agent-device-profile.json");
const secret = (JSON.parse(await readFile(profilePath, "utf8")) as { daemonAuthToken: string })
.daemonAuthToken;
const listed = await env.cli(["token", "list"], { timeout: 60_000 });
const labelled = (
listed.json as { tokens: readonly { id: string; label?: string }[] }
).tokens.filter((token) => token.label === PROFILE_TOKEN_LABEL);
const tokenId = labelled[0]?.id;
if (labelled.length !== 1 || tokenId === undefined) {
throw new Error(
`expected one "${PROFILE_TOKEN_LABEL}" token, found ${String(labelled.length)}`,
);
}
const home = await mkdtemp(join(tmpdir(), `simlock-ad-${name}-`));
const entry = agentDeviceEntry();
const inherited = Object.fromEntries(
Object.entries(process.env).filter(([key]) => !key.startsWith("AGENT_DEVICE_")),
);
const childEnv: NodeJS.ProcessEnv = {
...inherited,
HOME: home,
AGENT_DEVICE_STATE_DIR: home,
AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1",
};
const background = new Set<CliBackgroundHandle>();
const agent: Agent = {
name,
home,
token: secret,
tokenId,
async run(args, options = {}) {
const result = await cli(["--json", ...args, "--session", name], childEnv, {
entry,
timeout: options.timeout ?? 60_000,
});
return parseResult(result.code, result.stdout, result.stderr);
},
start(args) {
const handle = cliBackground(["--json", ...args, "--session", name], childEnv, { entry });
background.add(handle);
return handle;
},
};
made.push({ env, agent, background, keepToken: true });
const connected = await agent.run(["connect", "--remote-config", profilePath]);
if (connected.code !== 0) {
throw new Error(`agent-device connect failed: ${connected.stdout}\n${connected.stderr}`);
}
return agent;
}

export async function cleanupAgents(): Promise<void> {
const agents = made.splice(0);
await Promise.allSettled(
agents.map(async ({ env, agent, background }) => {
agents.map(async ({ env, agent, background, keepToken }) => {
for (const handle of background) handle.kill("SIGKILL");
await Promise.all(
[...background].map((handle) => handle.waitForExit(10_000).catch(() => undefined)),
);
await agent.run(["disconnect"], { timeout: 60_000 }).catch(() => undefined);
await env.cli(["token", "revoke", agent.tokenId], { timeout: 30_000 }).catch(() => undefined);
if (keepToken !== true) {
await env
.cli(["token", "revoke", agent.tokenId], { timeout: 30_000 })
.catch(() => undefined);
}
await rm(agent.home, { force: true, recursive: true });
}),
);
Expand Down
18 changes: 15 additions & 3 deletions e2e/helpers/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,17 +214,29 @@ function processEnv(
};
}

// why: a standalone worker serves HTTP and agent-device by default (ADR 0046); a test gets neither unless it asks, and two daemons would clash on port 4701. A gateway keeps its HTTP, which it cannot do without.
const STANDALONE_OFF: Record<string, unknown> = {
capabilities: { "agent-device": { enabled: false } },
http: { enabled: false },
};

function seedConfig(
options: WithDaemonOptions,
adbServerPort: number | undefined,
): Record<string, unknown> | undefined {
const pinned = options.role === "gateway" ? {} : STANDALONE_OFF;
if (options.driver === undefined || options.driver === "fake") {
return mergeDeep(FAKE_LANE_BASE_CONFIG, options.configOverrides ?? {});
return mergeDeep(mergeDeep(pinned, FAKE_LANE_BASE_CONFIG), options.configOverrides ?? {});
}
if (options.driver === "real") {
return mergeDeep({ drivers: { android: { adbServerPort } } }, options.configOverrides ?? {});
return mergeDeep(
mergeDeep(pinned, { drivers: { android: { adbServerPort } } }),
options.configOverrides ?? {},
);
}
return options.configOverrides;
return options.role === "gateway"
? options.configOverrides
: mergeDeep(pinned, options.configOverrides ?? {});
}

async function buildEnv(
Expand Down
1 change: 1 addition & 0 deletions e2e/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export {
assertPinnedAgentDevice,
cleanupAgents,
makeAgent,
makeProfileAgent,
newAgentToken,
waitForAgentDevice,
} from "./agent-device.js";
Expand Down
15 changes: 15 additions & 0 deletions e2e/slow-agent-device.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
cleanupAgents,
freeLoopbackPort,
makeAgent,
makeProfileAgent,
newAgentToken,
waitForAgentDevice,
waitFor,
Expand Down Expand Up @@ -194,6 +195,20 @@ function defineSuite(target: Target): void {
},
);

it(
"an agent with no token in its environment connects with the worker's profile file, opens a device, installs the fixture app as an upload and closes; the lease's owner is the profile token",
{ timeout: 600_000 },
async () => {
const a = await makeProfileAgent(env, "profile");
ok(await open(a));
const leases = await listLeases(env);
expect(leases.map((lease) => lease.ownerId)).toEqual([a.tokenId]);
ok(await a.run(["install", "Appduct", target.app]));
ok(await a.run(["close"]));
await waitForFree(env);
},
);

it(
"with this working agent-device, simlock doctor reports no module-unavailable finding and no finding whose message names agent-device",
{ timeout: 600_000 },
Expand Down
2 changes: 1 addition & 1 deletion src/agent-device/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Does: runs two agent-device daemons per worker (the simulator daemon over Simloc
Entry: `index.ts` → `agentDeviceModule`. The front parts live in `front/edge-parts.ts` (`createGatewayAgentDeviceFrontParts`, `createAgentDeviceFront`, `disposeAgentDeviceEdge`, `cancelWaitingAllocates`). The gateway half is `gateway.ts` (`createGateway`, builds the `FleetPort` from the gateway context); the worker half is `worker.ts` (`createAgentDeviceEdgeParts`, builds one `AgentDeviceSupervisor` per role). The module host loads both.
Uses: ports, auth (`Identity`), http (session, errors), contract types, core and leasing types. Never imports: gateway, drivers, `fs`, `child_process`.
Imported by: the module registry (`index.ts` only); `daemon/main.ts` imports nothing from it (tests may use `testing.ts`). Pinned in `lint-rules.test.ts`.
Off unless `capabilities.agent-device.enabled` (false). Off: nothing mounted, no daemon.
On unless `capabilities.agent-device.enabled` is set false, on a standalone worker (`definition.ts` declares `enabledByDefault: "standalone-worker"`); off on a joined worker and a gateway unless set true. Off: nothing mounted, no daemon. When on only by default and the command is not found, the capability reads `off` and `agentDeviceFindings` says nothing (`isAbsentByDefault`); every other trouble, and a not-found with `enabled: true` set, stays `unavailable` with its finding.

## Files

Expand Down
30 changes: 23 additions & 7 deletions src/agent-device/definition.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,15 @@ async function loadWith(
return loadConfig({
configPath,
filesystem,
modules: [{ ...agentDeviceModule.config, name: agentDeviceModule.name }],
modules: [
{
...agentDeviceModule.config,
...(agentDeviceModule.enabledByDefault === undefined
? {}
: { enabledByDefault: agentDeviceModule.enabledByDefault }),
name: agentDeviceModule.name,
},
],
...(role === undefined ? {} : { role }),
systemStats: new FakeSystemStats({ cpuCount: 4, totalRamBytes: 16 * 1024 ** 3 }),
...(warn === undefined ? {} : { warn }),
Expand All @@ -32,10 +40,18 @@ function section(config: Config): Record<string, unknown> | undefined {
}

describe("agent-device's definition: capabilities.agent-device config", () => {
it("defaults capabilities.agent-device.enabled to false and command to agent-device, with leaseTtlCapMs unset", async () => {
const config = await loadWith({});

expect(section(config)).toEqual({ command: "agent-device", enabled: false });
it("defaults capabilities.agent-device.enabled to true on a standalone worker and false on a joined worker and a gateway, with command agent-device and leaseTtlCapMs unset", async () => {
const joined = { gateway: { token: "join-secret", url: "wss://fleet.example" } };

expect(section(await loadWith({}))).toEqual({ command: "agent-device", enabled: true });
expect(
section(await loadWith({ capabilities: { "agent-device": { enabled: false } } })),
).toEqual({ command: "agent-device", enabled: false });
expect(section(await loadWith(joined))).toEqual({ command: "agent-device", enabled: false });
expect(section(await loadWith({}, undefined, "gateway"))).toEqual({
command: "agent-device",
enabled: false,
});
});

it("keeps an explicit capabilities.agent-device section", async () => {
Expand Down Expand Up @@ -132,12 +148,12 @@ describe("agent-device's definition: capabilities.agent-device config", () => {
);
});

it("refuses the old top-level agentDevice key as unknown, and leaves agent-device off", async () => {
it("refuses the old top-level agentDevice key as unknown, and leaves agent-device at its default", async () => {
const warn = vi.fn();

const config = await loadWith({ agentDevice: { enabled: true } }, warn);

expect(warn).toHaveBeenCalledWith('Unknown config key: "agentDevice"');
expect(section(config)?.["enabled"]).toBe(false);
expect(section(config)?.["enabled"]).toBe(true);
});
});
3 changes: 3 additions & 0 deletions src/agent-device/definition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,14 @@ export const agentDeviceModule: OptionalModuleDefinition<AgentDeviceModuleConfig
leaseTtlCapMs: integerInRange(MIN_AGENT_DEVICE_LEASE_TTL_MS, Number.MAX_SAFE_INTEGER),
}),
},
enabledByDefault: "standalone-worker",
localProfile: {
fileName: "agent-device-profile.json",
render: (origin, secret) =>
`${JSON.stringify(
{
// why: agent-device refuses a proxy open without a clientId; it is a constant so the file's bytes stay stable.
clientId: "a51a51a51a51a51a",
daemonAuthToken: secret,
daemonBaseUrl: `${origin}/v1/agent-device`,
daemonTransport: "http",
Expand Down
4 changes: 2 additions & 2 deletions src/agent-device/edge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4268,13 +4268,13 @@ describe("a worker's capabilities in status.get, through the whole worker daemon
return (await rig.daemon.dispatch("status.get", {}, adminSession)).capabilities;
}

it("a worker with no capabilities.agent-device section answers status.get with capabilities [{name: agent-device, state: off}], and so does one with it false", async () => {
it("a standalone worker with no capabilities.agent-device section answers status.get with capabilities [{name: agent-device, state: available}], and one with it false answers state off", async () => {
const unset = await setUp({ enabled: "unset" });
const off = await setUp({ enabled: false });
const running = await setUp();

expect(await capabilities(running)).toEqual([{ name: "agent-device", state: "available" }]);
expect(await capabilities(unset)).toEqual([{ name: "agent-device", state: "off" }]);
expect(await capabilities(unset)).toEqual([{ name: "agent-device", state: "available" }]);
expect(await capabilities(off)).toEqual([{ name: "agent-device", state: "off" }]);
});

Expand Down
12 changes: 12 additions & 0 deletions src/agent-device/host/availability-findings.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
import type { OptionalModuleFinding } from "../../core/index.js";
import type { AgentDeviceAvailability, AgentDeviceRole } from "./agent-device-supervisor.js";

// why: ADR 0046 §1: a command never found while the module is on only by default is no fault of this Mac, so it is neither reported nor an unavailable capability.
export function isAbsentByDefault(
availability: AgentDeviceAvailability,
enabledByDefault: boolean,
): boolean {
return (
enabledByDefault && availability.state === "unavailable" && availability.reason === "not-found"
);
}

export function agentDeviceFindings(
availability: AgentDeviceAvailability,
role: AgentDeviceRole = "simulators",
enabledByDefault = false,
): readonly OptionalModuleFinding[] {
if (availability.state !== "unavailable") return [];
if (isAbsentByDefault(availability, enabledByDefault)) return [];
return [
{
kind: "module-unavailable",
Expand Down
46 changes: 42 additions & 4 deletions src/agent-device/local-profile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ interface Switches {
readonly http?: boolean;
readonly agentDevice?: boolean;
readonly role?: "gateway";
readonly defaults?: "standalone" | "joined";
}

interface LaunchOptions extends Switches {
Expand Down Expand Up @@ -82,10 +83,24 @@ async function launch(options: LaunchOptions = {}): Promise<Rig> {
}
const daemon = await startDaemon({
clock,
configOverrides: {
capabilities: { "agent-device": { enabled: options.agentDevice ?? true } },
http: { enabled: options.http ?? true, host, port },
},
configOverrides:
options.defaults === undefined
? {
capabilities: { "agent-device": { enabled: options.agentDevice ?? true } },
http: { enabled: options.http ?? true, host, port },
}
: {
capabilities: { "agent-device": { command: "fake-agent-device" } },
...(options.defaults === "joined"
? {
gateway: {
token: "slk_join",
url: `ws://127.0.0.1:${String(await freeLoopbackPort())}`,
},
}
: {}),
http: { port },
},
...(options.role === undefined ? {} : { role: options.role }),
dataDirectory: directory,
deviceDataTables: fakeDeviceDataTables,
Expand Down Expand Up @@ -229,6 +244,7 @@ describe("the local agent-device profile", () => {
const profile = JSON.parse(text) as Record<string, string>;
expect((await rig.filesystem.stat(rig.profilePath)).mode).toBe(0o600);
expect(Object.keys(profile)).toEqual([
"clientId",
"daemonAuthToken",
"daemonBaseUrl",
"daemonTransport",
Expand All @@ -239,6 +255,7 @@ describe("the local agent-device profile", () => {
]);
expect(text).toBe(`${JSON.stringify(profile, null, 2)}\n`);
expect(profile).toMatchObject({
clientId: "a51a51a51a51a51a",
daemonBaseUrl: `http://127.0.0.1:${rig.port}/v1/agent-device`,
daemonTransport: "http",
leaseProvider: "proxy",
Expand Down Expand Up @@ -380,4 +397,25 @@ describe("the local agent-device profile", () => {
const made = await rig.daemon.dispatch("token.create", { role: "agent" }, adminSession);
expect((await allocateWith(rig, made.secret, 1)).status).toBe(200);
});

it("is written and served by a standalone worker on its defaults, and not by a joined one", async () => {
const standalone = await launch({ defaults: "standalone" });
const config = await standalone.daemon.dispatch("config.get", {}, adminSession);
expect(config.http.enabled).toBe(true);
expect(config.capabilities["agent-device"]?.enabled).toBe(true);
const profile = JSON.parse(await standalone.filesystem.readFile(standalone.profilePath)) as {
daemonAuthToken: string;
};
const health = await fetch(`http://127.0.0.1:${standalone.port}/v1/agent-device/health`, {
headers: { authorization: `Bearer ${profile.daemonAuthToken}`, connection: "close" },
});
const joined = await launch({ defaults: "joined" });

expect(health.status).toBe(200);
expect(await listens(joined.port)).toBe(false);
expect(await joined.filesystem.exists(joined.profilePath)).toBe(false);
expect((await joined.daemon.dispatch("status.get", {}, adminSession)).capabilities).toEqual([
{ name: "agent-device", state: "off" },
]);
});
});
Loading
Loading