Files
plan2code/scripts/test-app-smoke-agent.mjs
T

110 lines
5.1 KiB
JavaScript

// Tests for plan2code-app/scripts/smoke-agent.mjs, the stand-in agent CI's
// macOS smoke run starts in place of a real agent CLI. Run with:
// node --test scripts/test-app-smoke-agent.mjs
//
// The stand-in has one job: open a real web console the way an agent would,
// so the app's dashboard frame has something to connect to. This runs it
// outside the app, under a throwaway console home, and checks a live session
// appears and the stand-in ends when its input closes.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const AGENT = path.join(HERE, "../plan2code-app/scripts/smoke-agent.mjs");
const CONSOLE_DIR = path.join(HERE, "../src/web-console");
// The desktop app's own variables would have the console announce itself to
// a live window. Deleted from the spawned environment, never inherited.
const APP_VARS = ["PLAN2CODE_IN_APP", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_APP_VERSION", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_CONSOLE_SID"];
function outsideAppEnv(extra) {
const env = { ...process.env, ...extra };
for (const name of APP_VARS) delete env[name];
return env;
}
// Every session handle under a console home: runtime/<project hash>/<sid>.json.
function handles(consoleHome) {
const runtime = path.join(consoleHome, "runtime");
if (!fs.existsSync(runtime)) return [];
return fs.readdirSync(runtime).flatMap((hash) =>
fs
.readdirSync(path.join(runtime, hash))
.filter((name) => name.endsWith(".json"))
.map((name) => JSON.parse(fs.readFileSync(path.join(runtime, hash, name), "utf8")))
);
}
async function waitFor(check, ms) {
const end = Date.now() + ms;
while (Date.now() < end) {
const value = check();
if (value) return value;
await new Promise((resolve) => setTimeout(resolve, 100));
}
return check();
}
function pidAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (err) {
return err.code === "EPERM";
}
}
test("smoke agent: is an executable Node script with no dependencies", { skip: process.platform === "win32" }, () => {
const source = fs.readFileSync(AGENT, "utf8");
assert.ok(source.startsWith("#!/usr/bin/env node\n"), "starts with a node shebang");
assert.ok((fs.statSync(AGENT).mode & 0o111) !== 0, "has its executable bits set");
for (const [, name] of source.matchAll(/from\s+["']([^"']+)["']/g)) {
assert.ok(name.startsWith("node:"), `imports only Node built-ins, not ${name}`);
}
});
test("smoke agent: opens a live dashboard session, then ends when its input closes", async (t) => {
const consoleHome = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-smoke-agent-home-"));
const project = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-smoke-agent-project-"));
const env = outsideAppEnv({ PLAN2CODE_CONSOLE_HOME: consoleHome, PLAN2CODE_NO_BROWSER: "1", PLAN2CODE_CONSOLE_DIR: CONSOLE_DIR });
let agent;
t.after(() => {
if (agent && agent.exitCode === null) agent.kill("SIGKILL");
// --all stops this folder's sessions, so it runs from the project, under the same home.
spawnSync(process.execPath, [path.join(CONSOLE_DIR, "console.mjs"), "stop", "--all"], { cwd: project, env, timeout: 15000 });
fs.rmSync(consoleHome, { recursive: true, force: true });
fs.rmSync(project, { recursive: true, force: true });
});
agent = spawn(process.execPath, [AGENT, "--some-agent-flag"], { cwd: project, env, stdio: ["pipe", "pipe", "pipe"] });
let output = "";
agent.stdout.on("data", (chunk) => (output += chunk));
agent.stderr.on("data", (chunk) => (output += chunk));
const exited = new Promise((resolve) => agent.on("exit", (code) => resolve(code)));
const handle = await waitFor(() => handles(consoleHome)[0], 20000);
assert.ok(handle, `a session appeared under the console home; agent said: ${output}`);
const health = await (await fetch(`http://127.0.0.1:${handle.port}/health`)).json();
assert.equal(health.ok, true);
assert.equal(health.sid, handle.sid, "the port answers for this session");
const state = JSON.parse(fs.readFileSync(path.join(consoleHome, "sessions", handle.sid, "state.json"), "utf8"));
assert.equal(state.workflow, "dashboard");
// Still running until its input closes, like an agent waiting for the person.
assert.equal(agent.exitCode, null, "the stand-in waits on its input");
agent.stdin.end();
const code = await Promise.race([exited, new Promise((resolve) => setTimeout(() => resolve("timeout"), 10000))]);
assert.equal(code, 0, `the stand-in exits cleanly once its input closes; agent said: ${output}`);
// The console outlives the agent (it is detached), so the stop below is what ends it.
const stop = spawnSync(process.execPath, [path.join(CONSOLE_DIR, "console.mjs"), "stop", "--all"], { cwd: project, env, encoding: "utf8", timeout: 15000 });
assert.equal(stop.status, 0, stop.stderr);
assert.equal(await waitFor(() => !pidAlive(handle.pid), 10000), true, "the console server is gone after stop --all");
});