708 lines
40 KiB
JavaScript
708 lines
40 KiB
JavaScript
"use strict";
|
|
|
|
const assert = require("node:assert/strict");
|
|
const { execFile, spawn, spawnSync } = require("node:child_process");
|
|
const { randomUUID, webcrypto } = require("node:crypto");
|
|
const { once } = require("node:events");
|
|
const fs = require("node:fs/promises");
|
|
const http = require("node:http");
|
|
const os = require("node:os");
|
|
const path = require("node:path");
|
|
const { setTimeout: delay } = require("node:timers/promises");
|
|
const { promisify } = require("node:util");
|
|
const vm = require("node:vm");
|
|
|
|
const source = path.join(__dirname, "..");
|
|
const files = ["index.js", "db.js", "nodes.js", "package.json", "mysql-schema.sql", "ecosystem.config.template.js"];
|
|
const directories = ["AgentWorker", "public", "views", "services", "utils", "routes", "scripts", "node_modules"];
|
|
const origin = "http://127.0.0.1:3000";
|
|
const serviceSocket = "/run/fixture-agent-service.sock";
|
|
const fixtureSecret = "synthetic-session-secret-for-the-isolated-agent-staging-run";
|
|
const fixturePassword = "Synthetic-fixture-password-123!";
|
|
const exec = promisify(execFile);
|
|
|
|
function runIsolated(args) {
|
|
const binds = [...files, ...directories].flatMap((name) => ["--ro-bind", path.join(source, name), `/source/${name}`]);
|
|
const child = spawnSync("bwrap", [
|
|
"--unshare-all", "--die-with-parent", "--uid", "0", "--gid", "0", "--clearenv",
|
|
"--setenv", "PATH", "/usr/bin:/usr/sbin", "--setenv", "HOME", "/tmp", "--setenv", "DOTENV_CONFIG_QUIET", "true",
|
|
"--ro-bind", "/usr", "/usr", "--symlink", "usr/bin", "/bin", "--symlink", "usr/sbin", "/sbin",
|
|
"--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev",
|
|
"--tmpfs", "/tmp", "--tmpfs", "/run", "--tmpfs", "/usr/local/lib", "--dir", "/etc",
|
|
"--dir", "/source", "--dir", "/fixture", ...binds, "--chdir", "/fixture",
|
|
"/usr/bin/node", "/source/scripts/verify-agent-worker-staging.js", "--isolated", ...args,
|
|
], { stdio: "inherit", timeout: args.includes("--load") ? 480_000 : 180_000 });
|
|
if (child.error) throw child.error;
|
|
process.exitCode = child.status ?? 1;
|
|
}
|
|
|
|
async function until(description, check, timeout = 20_000, interval = 80) {
|
|
const deadline = Date.now() + timeout;
|
|
do {
|
|
const result = await check();
|
|
if (result) return result;
|
|
await delay(interval);
|
|
} while (Date.now() < deadline);
|
|
throw new Error(`Timed out: ${description}`);
|
|
}
|
|
|
|
function requestService(args) {
|
|
const [operation, action] = args;
|
|
assert.ok(args.length === 2 && operation === "agent-service" && ["start", "stop", "restart"].includes(action));
|
|
return new Promise((resolve, reject) => {
|
|
const request = http.request({ socketPath: serviceSocket, path: `/${action}`, method: "POST", timeout: 15_000 }, (response) => {
|
|
response.on("error", reject);
|
|
response.on("aborted", () => reject(new Error("Fixture service response interrupted")));
|
|
response.resume();
|
|
response.on("end", () => response.statusCode === 204 ? resolve() : reject(new Error("Fixture service failed")));
|
|
});
|
|
request.on("error", reject);
|
|
request.on("timeout", () => request.destroy(new Error("Fixture service timed out")));
|
|
request.end();
|
|
});
|
|
}
|
|
|
|
function createBrowser() {
|
|
const cookies = new Map();
|
|
return async function request(route, options = {}) {
|
|
const headers = {
|
|
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
|
|
origin, referer: `${origin}/`, "sec-fetch-site": "same-origin", ...options.headers,
|
|
};
|
|
if (cookies.size) headers.cookie = [...cookies].map(([key, value]) => `${key}=${value}`).join("; ");
|
|
const response = await fetch(`${origin}${route}`, { redirect: "manual", signal: AbortSignal.timeout(8000), ...options, headers });
|
|
for (const cookie of response.headers.getSetCookie()) {
|
|
const pair = cookie.split(";", 1)[0];
|
|
const separator = pair.indexOf("=");
|
|
if (separator > 0) cookies.set(pair.slice(0, separator), pair.slice(separator + 1));
|
|
}
|
|
return response;
|
|
};
|
|
}
|
|
|
|
async function login(email, signInAddress) {
|
|
const request = createBrowser();
|
|
const proxyHeaders = signInAddress ? { "x-forwarded-for": signInAddress } : {};
|
|
const page = await request("/login", { headers: proxyHeaders });
|
|
assert.equal(page.status, 200, `fixture login page returned ${page.status}`);
|
|
const html = await page.text();
|
|
const botProof = html.match(/name="botProof"[^>]*value="([a-f0-9]+)"/)?.[1];
|
|
const csrf = html.match(/name="_csrf"[^>]*value="([a-f0-9]+)"/)?.[1];
|
|
assert.ok(botProof && csrf, `login did not render browser proof and CSRF fields (${JSON.stringify({
|
|
contentType: page.headers.get("content-type"), title: html.match(/<title>([^<]*)<\/title>/i)?.[1],
|
|
botProofField: html.includes('name="botProof"'), csrfField: html.includes('name="_csrf"'),
|
|
cookieIssued: page.headers.getSetCookie().length > 0,
|
|
})})`);
|
|
const response = await request("/login", {
|
|
method: "POST", headers: { ...proxyHeaders, "content-type": "application/json", accept: "application/json" },
|
|
body: JSON.stringify({ email, password: fixturePassword, botProof, _csrf: csrf }),
|
|
});
|
|
const result = await response.text();
|
|
assert.equal(response.status, 200, `fixture login failed (${response.status}): ${result.slice(0, 180)}`);
|
|
assert.equal(JSON.parse(result).ok, true);
|
|
return request;
|
|
}
|
|
|
|
async function assertServerAgentMarkup(browser, visible) {
|
|
const response = await browser("/server/fixture");
|
|
assert.equal(response.status, 200);
|
|
const markup = await response.text();
|
|
for (const marker of ['id="aiHelpModal"', 'id="dockAiHelp"', 'id="dockAiHelpBottom"', 'id="aiHelpBtn"',
|
|
'value="planner_next_to_agent"', 'value="agent_prompt"', '/js/agent-live.js?v=', '/js/server-agent-history.js?v=',
|
|
'id="aiReviewCard"', 'id="aiAgentAccessMode"', 'value="file_plan"', 'id="aiReviewPlan"', '/js/server-agent-review.js?v=']) {
|
|
assert.equal(markup.includes(marker), visible, marker);
|
|
}
|
|
assert.doesNotMatch(markup, /id="aiReview(?:Dialog|Action)"/);
|
|
return markup;
|
|
}
|
|
|
|
async function loadServedAgentClient(browser, markup) {
|
|
const scripts = Array.from(markup.matchAll(/<script\b[^>]*\bsrc="(\/js\/(server-agent-history|server-agent-review|agent-live|bot)\.js\?v=[^"]+)"[^>]*\bdefer\b/g));
|
|
assert.deepEqual(scripts.map(([, , name]) => name), ["server-agent-history", "server-agent-review", "agent-live", "bot"]);
|
|
const context = vm.createContext({ AbortController, AbortSignal, DOMException, crypto: webcrypto, setTimeout, clearTimeout });
|
|
for (const [, url, name] of scripts) {
|
|
const response = await browser(url);
|
|
assert.equal(response.status, 200, url);
|
|
const script = await response.text();
|
|
assert.equal(script, await fs.readFile(path.join(source, "public/js", `${name}.js`), "utf8"), url);
|
|
if (name === "agent-live") vm.runInContext(script, context, { filename: url });
|
|
}
|
|
console.log(`PASS: panel served current deferred Agent scripts; bot.js version ends in ${scripts.at(-1)[1].split("-").slice(-3).join("-")}.`);
|
|
return context.adpanelAgentLive;
|
|
}
|
|
|
|
async function assertScene(browser, enabled) {
|
|
await assertServerAgentMarkup(browser, enabled);
|
|
const tokens = await browser("/api/settings/action-tokens");
|
|
assert.equal(tokens.status, 200);
|
|
const { actionTokens } = await tokens.json();
|
|
assert.equal(Object.hasOwn(actionTokens, "setAgentAccess"), enabled);
|
|
assert.ok(actionTokens.grantPerms && actionTokens.changePassword);
|
|
return actionTokens.setAgentAccess;
|
|
}
|
|
|
|
async function assertProviderSetup(admin, reader) {
|
|
const { actionTokens } = await (await admin("/api/ai/keys")).json();
|
|
const connect = (input) => admin("/api/ai/keys", { method: "POST",
|
|
headers: { "content-type": "application/json", "x-action-token": actionTokens.setKey },
|
|
body: JSON.stringify({ provider: "openai-compatible", ...input }),
|
|
});
|
|
const modelsRoute = "/api/ai/models/openai-compatible";
|
|
const base = "http://127.0.0.1:3099";
|
|
const auto = await connect({ key: "auto-fixture-key", baseUrl: base, modelIds: [] });
|
|
const automatic = await auto.json();
|
|
assert.equal(auto.status, 200, JSON.stringify(automatic));
|
|
assert.deepEqual(automatic.models, ["synthetic"]);
|
|
assert.equal(automatic.providerState.baseUrl, `${base}/v1`);
|
|
assert.doesNotMatch(JSON.stringify(automatic), /auto-fixture-key/);
|
|
|
|
const rejected = await connect({ key: "rejected-fixture-key", baseUrl: `${base}/v1`, modelIds: [] });
|
|
const refusal = await rejected.json();
|
|
assert.equal(rejected.status, 422, JSON.stringify(refusal));
|
|
assert.equal(refusal.code, "agent_discovery_auth", JSON.stringify(refusal));
|
|
assert.match(refusal.error, /provider rejected the API key/);
|
|
assert.doesNotMatch(JSON.stringify(refusal), /upstream response|rejected-fixture-key/);
|
|
assert.deepEqual((await (await reader(modelsRoute)).json()).models, ["synthetic"]);
|
|
|
|
const manualId = "Fixture/Audio-Chat";
|
|
const manual = await connect({ key: "manual-fixture-key", baseUrl: `${base}/manual/v1/chat/completions`, modelIds: [manualId] });
|
|
const configured = await manual.json();
|
|
assert.equal(manual.status, 200, JSON.stringify(configured));
|
|
assert.deepEqual(configured.models, [manualId]);
|
|
assert.equal(configured.providerState.modelId, manualId);
|
|
assert.equal(configured.providerState.baseUrl, `${base}/manual/v1`);
|
|
assert.deepEqual((await (await reader(modelsRoute)).json()).models, [manualId]);
|
|
|
|
const modelIds = [manualId, 'Fixture/Chat,variant="2"'];
|
|
const added = await connect({ key: "", modelIds });
|
|
const updated = await added.json();
|
|
assert.equal(added.status, 200, JSON.stringify(updated));
|
|
assert.deepEqual(updated.models, modelIds);
|
|
assert.deepEqual(updated.providerState.modelIds, modelIds);
|
|
assert.doesNotMatch(JSON.stringify(updated), /manual-fixture-key/);
|
|
|
|
const missing = await connect({ key: "", modelIds: [...modelIds, "missing-model"] });
|
|
const modelError = await missing.json();
|
|
assert.equal(missing.status, 422, JSON.stringify(modelError));
|
|
assert.equal(modelError.code, "agent_discovery_model_unavailable");
|
|
assert.deepEqual((await (await admin("/api/ai/keys")).json()).providers["openai-compatible"].modelIds, modelIds);
|
|
assert.deepEqual((await (await reader(modelsRoute)).json()).models, modelIds);
|
|
|
|
const reset = await connect({ baseUrl: `${base}/v1`, modelIds: [] });
|
|
const automaticAgain = await reset.json();
|
|
assert.equal(reset.status, 200, JSON.stringify(automaticAgain));
|
|
assert.deepEqual(automaticAgain.models, ["synthetic"]);
|
|
assert.deepEqual(automaticAgain.providerState.modelIds, []);
|
|
console.log("PASS: provider setup listed the catalog or saved IDs, added a second model using the saved key, and preserved the list after a failed addition.");
|
|
}
|
|
|
|
async function staging(args) {
|
|
assert.ok(process.getuid() === 0 && process.cwd() === "/fixture" && source === "/source");
|
|
assert.ok(Object.values(os.networkInterfaces()).flat().every((entry) => entry.internal));
|
|
await assert.rejects(fs.stat("/run/systemd/private"), { code: "ENOENT" });
|
|
const mysql = require("mysql2/promise");
|
|
const bcrypt = require("bcrypt");
|
|
const { fixtureImage, measureLoad } = require("./agent-staging-workload");
|
|
const { createActionChecks } = require("./agent-staging-actions");
|
|
const actionChecks = createActionChecks();
|
|
const { pruneExpiredAgentAttachments } = require("../AgentWorker/attachments");
|
|
const { createAgentRpcClient, deriveRpcSecret, listPanelAgentSockets, RPC_VERSION, WORKER_SOCKET } = require("../AgentWorker/private-rpc");
|
|
const root = await fs.mkdtemp("/tmp/agent-staging-");
|
|
const panel = path.join(root, "panel");
|
|
const mysqlData = path.join(root, "mysql");
|
|
const binaries = path.join(root, "bin");
|
|
const processEnv = { ...process.env, HOME: root, PATH: `${binaries}:${process.env.PATH}`, PM2_HOME: path.join(root, "pm2"), ADPANEL_AGENT_ENABLED: "ON" };
|
|
const pm2 = path.join(panel, "node_modules/.bin/pm2");
|
|
const processes = [];
|
|
const servers = [];
|
|
let worker;
|
|
let pool;
|
|
let schedules;
|
|
let providerRequests = 0;
|
|
let titleRequests = 0;
|
|
const firstProviderCalls = [];
|
|
const titleRefusalPrompt = "Could you check why the fixture server restarted?";
|
|
let activeProviderRequests = 0;
|
|
let peakProviderRequests = 0;
|
|
let workerStarts = 0;
|
|
let serviceStops = 0;
|
|
|
|
function start(label, command, args, env = processEnv) {
|
|
const child = spawn(command, args, { cwd: panel, env, stdio: ["ignore", "pipe", "pipe"] });
|
|
const entry = { label, child, closed: once(child, "close"), output: "" };
|
|
for (const stream of [child.stdout, child.stderr]) {
|
|
stream.on("data", (data) => { entry.output = (entry.output + data).slice(-12_000); });
|
|
}
|
|
processes.push(entry);
|
|
return entry;
|
|
}
|
|
|
|
async function stop(entry) {
|
|
if (!entry || entry.child.exitCode !== null || entry.child.signalCode !== null) return;
|
|
if (!entry.stopping) {
|
|
entry.child.kill("SIGTERM");
|
|
const force = setTimeout(() => entry.child.kill("SIGKILL"), 10_000);
|
|
entry.stopping = entry.closed.finally(() => clearTimeout(force));
|
|
}
|
|
await entry.stopping;
|
|
}
|
|
|
|
async function listen(handler, target) {
|
|
const server = http.createServer(handler);
|
|
if (typeof target === "string") server.listen(target);
|
|
else server.listen(target, "127.0.0.1");
|
|
await once(server, "listening");
|
|
servers.push(server);
|
|
}
|
|
|
|
const pm2Command = (...args) => exec(pm2, args, { cwd: panel, env: processEnv, timeout: 20_000 });
|
|
const query = async (sql, params) => (await pool.execute(sql, params))[0];
|
|
const database = { host: "127.0.0.1", user: "root", connectTimeout: 1000 };
|
|
const waitPanel = () => until("panel HTTP readiness", async () => {
|
|
try { return (await createBrowser()("/healthz")).ok; } catch { return false; }
|
|
}, 35_000);
|
|
const waitWorker = (peers = 2, sessionSecret = fixtureSecret) => until("Agent diagnostic handshake", async () => {
|
|
const secret = deriveRpcSecret(sessionSecret);
|
|
const workerHealth = createAgentRpcClient({ socketPath: WORKER_SOCKET, receiver: "worker", secret, timeoutMs: 500 });
|
|
const health = await workerHealth("health").catch(() => null);
|
|
if (!health?.ready || health.version !== RPC_VERSION) return false;
|
|
const sockets = await listPanelAgentSockets();
|
|
if (sockets.length !== peers) return false;
|
|
const states = await Promise.all(sockets.map((socketPath) => createAgentRpcClient({ socketPath, receiver: "panel",
|
|
secret, timeoutMs: 500 })("health").catch(() => null)));
|
|
if (states.some((state) => state?.generation !== health.generation)) return false;
|
|
await delay(2100);
|
|
return true;
|
|
});
|
|
const setAgent = (value, sessionSecret = fixtureSecret) => fs.writeFile(path.join(panel, ".env"), [
|
|
`ADPANEL_AGENT_ENABLED=${value}`, `SESSION_SECRET=${sessionSecret}`, "HOST=127.0.0.1", "HTTP_PORT=3000",
|
|
`PANEL_PUBLIC_URL=${origin}`, "STEALTH_MODE=false", "MYSQL_USER=root", "MYSQL_DATABASE=agent_fixture", "MYSQL_POOL_SIZE=8",
|
|
"SESSION_STORE=redis", "REDIS_URL=redis://127.0.0.1:6379", "REDIS_ENSURE_PERSISTENCE=false", "BCRYPT_ROUNDS=10",
|
|
"OPENAI_COMPATIBLE_BASE_URL=http://127.0.0.1:3099/v1", "ADPANEL_ALLOW_PRIVATE_NODES=1",
|
|
].join("\n") + "\n", { mode: 0o600 });
|
|
|
|
try {
|
|
await fs.mkdir(panel);
|
|
await fs.mkdir(mysqlData);
|
|
await fs.mkdir(binaries);
|
|
await fs.writeFile(path.join(binaries, "systemctl"), `#!/bin/sh
|
|
case "$1:$2" in
|
|
list-unit-files:mariadb.service) printf '%s\\n' 'mariadb.service enabled' ;;
|
|
is-active:mariadb) printf '%s\\n' 'active' ;;
|
|
*) exit 1 ;;
|
|
esac
|
|
`, { mode: 0o700 });
|
|
for (const name of files) await fs.copyFile(path.join(source, name), path.join(panel, name));
|
|
for (const name of directories) {
|
|
if (name === "AgentWorker" || name === "utils" || name === "services" || name === "routes") {
|
|
await fs.cp(path.join(source, name), path.join(panel, name), { recursive: true });
|
|
}
|
|
else await fs.symlink(path.join(source, name), path.join(panel, name));
|
|
}
|
|
await fs.writeFile("/etc/passwd", "root:x:0:0:root:/tmp:/bin/sh\n");
|
|
await fs.writeFile("/etc/group", "root:x:0:\n");
|
|
await fs.writeFile("/etc/hosts", "127.0.0.1 localhost\n::1 localhost\n");
|
|
await fs.writeFile("/etc/nsswitch.conf", "passwd: files\ngroup: files\nhosts: files\n");
|
|
await fs.mkdir("/usr/local/lib/adpanel");
|
|
await fs.writeFile("/usr/local/lib/adpanel/adpanel-priv", `#!/usr/bin/node\nrequire(${JSON.stringify(__filename)}).requestService(process.argv.slice(2)).catch(() => { process.exitCode = 1; });\n`, { mode: 0o700 });
|
|
await fs.mkdir("/run/adpanel-agent", { mode: 0o700 });
|
|
await fs.mkdir("/run/adpanel-agent-panel", { mode: 0o700 });
|
|
await fs.writeFile(path.join(panel, "security.json"), JSON.stringify({ rate_limiting: false, limit: 300, window_seconds: 120 }));
|
|
await setAgent("NOT-ASKED");
|
|
await listen(async (request, response) => {
|
|
request.on("error", () => {});
|
|
response.on("error", () => {});
|
|
try {
|
|
assert.equal(request.method, "POST");
|
|
if (request.url === "/start" || request.url === "/restart") {
|
|
if (request.url === "/restart") await stop(worker);
|
|
if (!worker || worker.child.exitCode !== null || worker.child.signalCode !== null) {
|
|
worker = start("Agent worker", process.execPath, [path.join(panel, "AgentWorker/worker.js")]);
|
|
workerStarts += 1;
|
|
}
|
|
} else if (request.url === "/stop") {
|
|
serviceStops += 1;
|
|
await stop(worker);
|
|
} else assert.fail("Unknown fixture service action");
|
|
response.writeHead(204).end();
|
|
} catch { response.writeHead(500).end(); }
|
|
}, serviceSocket);
|
|
await listen((request, response) => {
|
|
request.on("error", () => {});
|
|
response.on("error", () => {});
|
|
let body = "";
|
|
request.on("data", (chunk) => { body += chunk; });
|
|
request.on("end", () => {
|
|
if (request.url === "/v1/models") {
|
|
if (request.headers.authorization === "Bearer rejected-fixture-key") {
|
|
return response.writeHead(401).end(JSON.stringify({ error: "Never expose this upstream response." }));
|
|
}
|
|
return response.end(JSON.stringify({ data: [{ id: "synthetic" }] }));
|
|
}
|
|
if (request.url === "/manual/v1/chat/completions") {
|
|
const payload = JSON.parse(body);
|
|
assert.ok(payload.max_tokens <= 128);
|
|
assert.equal(request.headers.authorization, "Bearer manual-fixture-key");
|
|
if (payload.model === "missing-model") return response.writeHead(404).end(JSON.stringify({ error: "Unknown model" }));
|
|
assert.ok(["Fixture/Audio-Chat", 'Fixture/Chat,variant="2"'].includes(payload.model));
|
|
return response.end(JSON.stringify({ choices: [{ message: { role: "assistant", content: "OK" } }] }));
|
|
}
|
|
if (request.url !== "/v1/chat/completions") return response.writeHead(404).end();
|
|
providerRequests += 1;
|
|
activeProviderRequests += 1;
|
|
peakProviderRequests = Math.max(peakProviderRequests, activeProviderRequests);
|
|
response.once("close", () => { activeProviderRequests -= 1; });
|
|
const payload = JSON.parse(body);
|
|
const titleOnly = payload.messages?.[0]?.content?.startsWith("Name this chat based on its first user message.");
|
|
if (firstProviderCalls.length < 2) firstProviderCalls.push(titleOnly ? "title" : "reply");
|
|
if (titleOnly) {
|
|
titleRequests += 1;
|
|
assert.equal(payload.tools, undefined);
|
|
assert.ok(payload.max_tokens <= 96);
|
|
assert.equal(payload.messages.length, 2);
|
|
assert.equal(typeof payload.messages[1].content, "string", "the title does not receive attachments or tool outputs");
|
|
const { message } = JSON.parse(payload.messages[1].content.split("\n").at(-1));
|
|
const content = message === titleRefusalPrompt ? "Sorry, but I can't help with that." : JSON.stringify({ title: "Synthetic Diagnostics" });
|
|
return response.end(JSON.stringify({ choices: [{ message: { content } }] }));
|
|
}
|
|
if (body.includes("Lifecycle fixture waits for cancellation")) return;
|
|
if (actionChecks.provider(payload, response)) return;
|
|
const reply = JSON.stringify({ choices: [{ message: { role: "assistant", content: "Synthetic diagnostic reply." }, finish_reason: "stop" }] });
|
|
const timer = setTimeout(() => response.end(reply), args.includes("--load") ? 240 : 0);
|
|
response.once("close", () => clearTimeout(timer));
|
|
});
|
|
}, 3099);
|
|
await listen(actionChecks.node, 3101);
|
|
await exec("/usr/bin/mariadb-install-db", ["--no-defaults", "--user=root", `--datadir=${mysqlData}`,
|
|
"--auth-root-authentication-method=normal", "--skip-test-db", "--force"], { cwd: panel, timeout: 20_000 });
|
|
start("MariaDB", "/usr/sbin/mariadbd", ["--no-defaults", "--user=root", `--datadir=${mysqlData}`,
|
|
"--socket=/run/fixture-mysql.sock", "--pid-file=/run/fixture-mysql.pid", "--bind-address=127.0.0.1", "--innodb-buffer-pool-size=64M"]);
|
|
start("Redis", "/usr/bin/redis-server", ["--bind", "127.0.0.1", "--save", "", "--appendonly", "no", "--dir", root]);
|
|
const admin = await until("MariaDB readiness", () => mysql.createConnection(database).catch(() => null));
|
|
try { await admin.query("CREATE DATABASE agent_fixture"); } finally { await admin.end(); }
|
|
pool = mysql.createPool({ ...database, database: "agent_fixture", connectionLimit: 8 });
|
|
await pm2Command("start", "index.js", "--name", "adpanel", "-i", "2");
|
|
await waitPanel();
|
|
const [{ id: serverId }] = await query("SELECT id FROM servers WHERE name = 'fixture'").then(async (rows) => {
|
|
if (rows.length) return rows;
|
|
const result = await query("INSERT INTO servers (name, bot, status) VALUES ('fixture', 'fixture', 'offline')");
|
|
return [{ id: result.insertId }];
|
|
});
|
|
const email = "operator@example.test";
|
|
const adminEmail = "probe-admin@example.test";
|
|
const unentitledEmail = "server-user@example.test";
|
|
const passwordHash = await bcrypt.hash(fixturePassword, 10);
|
|
const account = await query("INSERT INTO users (email, password, agent_access) VALUES (?, ?, 1)", [email, passwordHash]);
|
|
await query("INSERT INTO users (email, password, admin) VALUES (?, ?, 1)", [adminEmail, passwordHash]);
|
|
const unentitled = await query("INSERT INTO users (email, password) VALUES (?, ?)", [unentitledEmail, passwordHash]);
|
|
await query("INSERT INTO user_access (user_id, server_name) VALUES (?, 'fixture'), (?, 'fixture')", [account.insertId, unentitled.insertId]);
|
|
assert.ok(serverId);
|
|
let browser = await login(email);
|
|
const probe = await login(adminEmail);
|
|
const submit = (fields = {}) => browser("/api/ai/chat", { method: "POST", headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ requestKey: randomUUID(), server: "fixture", prompt: "Reply with a synthetic diagnostic.", provider: "openai-compatible", model: "synthetic", ...fields }),
|
|
});
|
|
const admit = async (fields = {}) => {
|
|
const submission = { requestKey: randomUUID(), ...fields };
|
|
return until("panel observes Agent readiness", async () => {
|
|
const response = await submit(submission);
|
|
const payload = await response.json();
|
|
if (response.status === 503 && payload.code === "agent_unavailable") return false;
|
|
assert.equal(response.status, 202, JSON.stringify(payload));
|
|
return payload;
|
|
}, 6000, 600);
|
|
};
|
|
const off = await submit();
|
|
assert.equal(off.status, 503);
|
|
assert.equal((await off.json()).code, "agent_disabled");
|
|
assert.equal(workerStarts, 0);
|
|
assert.equal(providerRequests, 0);
|
|
await assertScene(probe, false);
|
|
await assertServerAgentMarkup(browser, false);
|
|
console.log("PASS: NOT-ASKED hides Agent and makes no provider calls despite inherited ON.");
|
|
|
|
await setAgent("ON");
|
|
await pm2Command("restart", "adpanel");
|
|
await waitPanel();
|
|
await waitWorker();
|
|
const token = await assertScene(probe, true);
|
|
const markup = await assertServerAgentMarkup(browser, true);
|
|
const { createRun, resumeRun } = await loadServedAgentClient(browser, markup);
|
|
if (args.includes("--auto-edits")) {
|
|
const { createScheduleChecks } = require("./agent-staging-schedules");
|
|
schedules = createScheduleChecks({ browser: probe, query, until });
|
|
await actionChecks.seedServer(query);
|
|
await schedules.exerciseAutomaticEdits(actionChecks);
|
|
await schedules.exerciseEditHold(actionChecks, async () => {
|
|
await requestService(["agent-service", "restart"]);
|
|
await waitWorker();
|
|
});
|
|
await schedules.exerciseNoEditCompletion();
|
|
return;
|
|
}
|
|
if (args.includes("--providers")) {
|
|
await assertProviderSetup(probe, browser);
|
|
return;
|
|
}
|
|
const ordinaryUser = await login(unentitledEmail);
|
|
await assertServerAgentMarkup(ordinaryUser, false);
|
|
const denied = await ordinaryUser("/api/ai/chat", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
|
|
assert.equal(denied.status, 403);
|
|
const selection = { server: "fixture", provider: "openai-compatible", model: "synthetic" };
|
|
const firstPrompt = "Reply with a synthetic diagnostic.";
|
|
const reply = "Synthetic diagnostic reply.";
|
|
const receipts = [];
|
|
const firstRun = createRun({ ...selection, chatId: null, prompt: firstPrompt, image: fixtureImage }, {
|
|
fetcher: async (route, options) => {
|
|
const response = await browser(route, options);
|
|
if (route === "/api/ai/chat" && response.status === 202) {
|
|
const { requestKey } = JSON.parse(options.body);
|
|
const { chatId, jobId } = await response.clone().json();
|
|
receipts.push({ http: response.status, chatId, jobId, requestKey });
|
|
if (receipts.length === 1) {
|
|
await response.body.cancel();
|
|
throw new TypeError("Fixture dropped the first Agent acknowledgement");
|
|
}
|
|
}
|
|
return response;
|
|
},
|
|
});
|
|
const accepted = await firstRun.accepted;
|
|
assert.equal(receipts.length, 2);
|
|
assert.deepEqual(receipts[1], receipts[0]);
|
|
assert.equal((await firstRun.result()).content, reply);
|
|
assert.equal(workerStarts, 1);
|
|
assert.equal(providerRequests, 2);
|
|
assert.equal(titleRequests, 1);
|
|
assert.deepEqual(firstProviderCalls, ["title", "reply"]);
|
|
const [[chatOwner], [storedJob], storedMessages] = await Promise.all([
|
|
query("SELECT created_by, title FROM ai_chats WHERE id = ?", [accepted.chatId]),
|
|
query(`SELECT chat_id, user_id, status, started_at, submission_message_id, result_message_id, error
|
|
FROM ai_agent_jobs WHERE id = ?`, [accepted.jobId]),
|
|
query("SELECT id, role, content FROM ai_messages WHERE chat_id = ? ORDER BY id", [accepted.chatId]),
|
|
]);
|
|
assert.equal(chatOwner.created_by, account.insertId);
|
|
assert.equal(chatOwner.title, "Synthetic Diagnostics");
|
|
assert.equal(storedJob.user_id, chatOwner.created_by);
|
|
assert.equal(String(storedJob.chat_id), String(accepted.chatId));
|
|
assert.equal(storedJob.status, "completed");
|
|
assert.ok(storedJob.started_at);
|
|
assert.equal(storedJob.error, null);
|
|
assert.deepEqual(storedMessages.map(({ role, content }) => [role, content]), [["user", firstPrompt], ["assistant", reply]]);
|
|
assert.deepEqual([storedJob.submission_message_id, storedJob.result_message_id].map(String), storedMessages.map(({ id }) => String(id)));
|
|
console.log(`PASS: duplicate submission returned chat=${accepted.chatId} job=${accepted.jobId}, with one title request before one reply and no duplicate writes.`);
|
|
|
|
const history = async () => {
|
|
const response = await browser(`/api/ai/chats/${accepted.chatId}`);
|
|
assert.equal(response.status, 200);
|
|
return (await response.json()).messages;
|
|
};
|
|
browser = await login(email);
|
|
await assertServerAgentMarkup(browser, true);
|
|
const list = await browser("/api/ai/chats");
|
|
assert.equal(list.status, 200);
|
|
const { chats } = await list.json();
|
|
assert.equal(chats.length, 1);
|
|
assert.equal(String(chats[0].id), String(accepted.chatId));
|
|
assert.equal(chats[0].title, chatOwner.title);
|
|
assert.equal(Number(chats[0].message_count), 2);
|
|
assert.deepEqual((await history()).map(({ role, content }) => [role, content]), [["user", firstPrompt], ["assistant", reply]]);
|
|
assert.equal((await history()).find((message) => message.role === "user").image_data, fixtureImage);
|
|
await query("UPDATE ai_messages SET image_expires_at = NOW(3) WHERE chat_id = ? AND image_data IS NOT NULL", [accepted.chatId]);
|
|
const expired = (await history()).find((message) => message.role === "user");
|
|
assert.equal(expired.image_data, null);
|
|
assert.equal(expired.content, firstPrompt);
|
|
assert.equal((await pruneExpiredAgentAttachments({ query })).affectedRows, 1);
|
|
assert.equal((await query("SELECT image_data FROM ai_messages WHERE id = ?", [expired.id]))[0].image_data, null);
|
|
const followupPrompt = "Continue the synthetic diagnostic.";
|
|
const followup = createRun({ ...selection, chatId: Number(accepted.chatId), prompt: followupPrompt }, { fetcher: browser });
|
|
const followed = await followup.accepted;
|
|
assert.equal(String(followed.chatId), String(accepted.chatId));
|
|
assert.notEqual(String(followed.jobId), String(accepted.jobId));
|
|
assert.equal((await followup.result()).content, reply);
|
|
assert.equal(titleRequests, 1, "follow-up messages must not regenerate a title");
|
|
assert.equal(providerRequests, 3);
|
|
assert.deepEqual((await history()).map(({ role, content }) => [role, content]), [
|
|
["user", firstPrompt], ["assistant", reply], ["user", followupPrompt], ["assistant", reply],
|
|
]);
|
|
console.log(`PASS: sidebar list and reopened history contain chat=${accepted.chatId}; follow-up job=${followed.jobId} added one exchange in the same chat; image expiry preserved the transcript.`);
|
|
|
|
const beforeGreeting = providerRequests;
|
|
const greeting = await createRun({ ...selection, prompt: "hello" }, { fetcher: probe }).result();
|
|
assert.equal(greeting.content, "Hello! How can I help with this server?");
|
|
assert.equal(greeting.review_job_id, null);
|
|
assert.equal(providerRequests, beforeGreeting + 1);
|
|
assert.equal(titleRequests, 2);
|
|
console.log("PASS: a new greeting used only the title request; the local reply did not call the provider or create a review.");
|
|
|
|
const beforeRefusal = providerRequests;
|
|
const titleRefusal = createRun({ ...selection, prompt: titleRefusalPrompt }, { fetcher: probe });
|
|
const refusedTitleChatId = (await titleRefusal.accepted).chatId;
|
|
assert.equal((await titleRefusal.result()).content, reply);
|
|
const { chats: titledChats } = await (await probe("/api/ai/chats")).json();
|
|
assert.equal(titledChats.find(({ id }) => String(id) === String(refusedTitleChatId))?.title, "Check why the fixture server restarted");
|
|
assert.equal(titleRequests, 3);
|
|
assert.equal(providerRequests, beforeRefusal + 2, "a rejected title must not trigger a retry or affect the regular reply");
|
|
console.log("PASS: a model refusal produced a local topic title in the chat list without another title request.");
|
|
|
|
const reviewers = [];
|
|
for (let index = 0; index < 11; index += 1) {
|
|
const reviewer = `reviewer-${index}@example.test`;
|
|
await query("INSERT INTO users (email, password, admin) VALUES (?, ?, 1)", [reviewer, passwordHash]);
|
|
reviewers.push(await login(reviewer));
|
|
}
|
|
await actionChecks.exercise({ query, browsers: reviewers, nonOwner: browser, createRun, resumeRun });
|
|
|
|
if (args.includes("--load")) {
|
|
await measureLoad({ browser: probe, login, query, passwordHash, workerPid: worker.child.pid,
|
|
providerStats: () => ({ requests: providerRequests, peak: peakProviderRequests }) });
|
|
}
|
|
|
|
const { createScheduleChecks } = require("./agent-staging-schedules");
|
|
schedules = createScheduleChecks({ browser: probe, query, until });
|
|
await schedules.exerciseEnabled();
|
|
await schedules.exerciseAutomaticEdits(actionChecks);
|
|
|
|
const originalWorker = worker;
|
|
const duplicate = start("Duplicate Agent worker", process.execPath, [path.join(panel, "AgentWorker/worker.js")]);
|
|
assert.deepEqual(await duplicate.closed, [1, null]);
|
|
await pm2Command("scale", "adpanel", "3");
|
|
await pm2Command("reload", "adpanel");
|
|
await waitPanel();
|
|
await waitWorker(3);
|
|
assert.equal(worker, originalWorker);
|
|
assert.equal(workerStarts, 1);
|
|
browser = await login(email);
|
|
|
|
const stalled = { prompt: "Lifecycle fixture waits for cancellation" };
|
|
const interrupted = await admit(stalled);
|
|
await until("in-flight synthetic request", () => activeProviderRequests > 0);
|
|
const [{ owner }] = await query("SELECT IS_USED_LOCK('adpanel:agent-worker:v1') AS owner");
|
|
assert.ok(Number.isSafeInteger(owner) && owner > 0);
|
|
await pool.query(`KILL CONNECTION ${owner}`);
|
|
await until("worker detects its lost lease", () => originalWorker.child.exitCode !== null || originalWorker.child.signalCode !== null);
|
|
assert.deepEqual(await originalWorker.closed, [1, null]);
|
|
const lastAttempt = providerRequests;
|
|
await requestService(["agent-service", "start"]);
|
|
await waitWorker(3);
|
|
const [settled] = await query("SELECT status, error FROM ai_agent_jobs WHERE id = ?", [interrupted.jobId]);
|
|
assert.deepEqual(settled, { status: "failed", error: "agent_interrupted" });
|
|
const reopened = await browser(`/api/ai/chats/${interrupted.chatId}`);
|
|
assert.equal(reopened.status, 200);
|
|
const { chat, messages } = await reopened.json();
|
|
assert.equal(chat.active_job_id, null);
|
|
assert.equal(chat.latest_job_status, "failed");
|
|
assert.equal(chat.latest_job_error, "agent_interrupted");
|
|
assert.equal(chat.latest_message_id, String(messages.at(-1).id));
|
|
assert.equal(messages.at(-1).content, stalled.prompt);
|
|
assert.equal(providerRequests, lastAttempt, "restarting the worker must not replay an ambiguous provider call");
|
|
assert.equal(workerStarts, 2);
|
|
console.log("PASS: PM2 scale/reload kept one consumer; SQL lease loss exited nonzero and the replacement did not replay the job.");
|
|
|
|
const stoppable = await admit(stalled);
|
|
await until("Agent opens the stoppable provider request", () => activeProviderRequests === 1);
|
|
const readStoppableChat = () => browser(`/api/ai/chats/${stoppable.chatId}`);
|
|
const reloadedChat = await readStoppableChat();
|
|
assert.equal(reloadedChat.status, 200);
|
|
assert.equal((await reloadedChat.json()).chat.active_job_id, String(stoppable.jobId));
|
|
assert.equal((await probe(`/api/ai/chats/${stoppable.chatId}`)).status, 404);
|
|
const runningRun = resumeRun(stoppable.jobId, stoppable.chatId, { fetcher: browser });
|
|
assert.deepEqual(await runningRun.cancel(), { ok: true, cancelled: true });
|
|
await assert.rejects(runningRun.result(), { name: "AbortError" });
|
|
await until("Stop aborts provider I/O", () => activeProviderRequests === 0);
|
|
const stoppedResponse = await browser(`/api/ai/jobs/${stoppable.jobId}`);
|
|
assert.equal(stoppedResponse.status, 200);
|
|
const { job: stoppedJob } = await stoppedResponse.json();
|
|
assert.equal(stoppedJob.status, "cancelled");
|
|
assert.equal(stoppedJob.content, null);
|
|
assert.equal((await (await readStoppableChat()).json()).chat.active_job_id, null);
|
|
console.log("PASS: reopening found the owner's running job; Stop cleared it without publishing a result.");
|
|
|
|
const pending = await Promise.all([admit(stalled), admit(stalled), admit(stalled)]);
|
|
const queued = await until("two in-flight requests and a queued job", async () => {
|
|
const rows = await query("SELECT id, chat_id, status FROM ai_agent_jobs WHERE id IN (?, ?, ?)", pending.map(({ jobId }) => jobId));
|
|
return activeProviderRequests === 2 && rows.filter(({ status }) => status === "running").length === 2 && rows.find(({ status }) => status === "queued");
|
|
});
|
|
const requestsBeforeStop = providerRequests;
|
|
const queuedRun = resumeRun(queued.id, queued.chat_id, { fetcher: browser });
|
|
assert.deepEqual(await queuedRun.cancel(), { ok: true, cancelled: true });
|
|
await assert.rejects(queuedRun.result(), { name: "AbortError" });
|
|
const [queuedResult] = await query("SELECT status, started_at, result_message_id FROM ai_agent_jobs WHERE id = ?", [queued.id]);
|
|
assert.deepEqual(queuedResult, { status: "cancelled", started_at: null, result_message_id: null });
|
|
assert.equal(providerRequests, requestsBeforeStop);
|
|
const offPending = [...pending.filter(({ jobId }) => String(jobId) !== String(queued.id)), await admit(stalled)];
|
|
console.log(`PASS: client Stop cancelled queued job=${queued.id} before claim or provider I/O.`);
|
|
|
|
const skipped = await schedules.scheduleOffOccurence();
|
|
await setAgent("OFF");
|
|
await pm2Command("restart", "adpanel");
|
|
await waitPanel();
|
|
await until("OFF reaches the durable queue", async () => !(await query("SELECT enabled FROM ai_agent_worker_state WHERE id = 1"))[0]?.enabled);
|
|
await until("Agent worker exits", () => worker.child.exitCode !== null || worker.child.signalCode !== null);
|
|
assert.deepEqual(await worker.closed, [0, null], "Agent shutdown must be graceful");
|
|
const disabled = await submit();
|
|
assert.equal((await disabled.json()).code, "agent_disabled");
|
|
const staleGrant = await probe(`/api/settings/accounts/${encodeURIComponent(email)}/agent-access`, {
|
|
method: "POST", headers: { "x-action-token": token, "content-type": "application/json" }, body: "{",
|
|
});
|
|
assert.equal((await staleGrant.json()).code, "agent_disabled");
|
|
await assertScene(probe, false);
|
|
await assertServerAgentMarkup(browser, false);
|
|
const cancelled = await query("SELECT status, result_message_id FROM ai_agent_jobs WHERE id IN (?, ?, ?)", offPending.map(({ jobId }) => jobId));
|
|
assert.ok(cancelled.every(({ status, result_message_id }) => ["cancelled", "failed"].includes(status) && result_message_id === null));
|
|
assert.equal((await query("SELECT COUNT(*) AS total FROM ai_messages WHERE chat_id = ?", [accepted.chatId]))[0].total, 4);
|
|
assert.equal((await query("SELECT agent_access FROM users WHERE id = ?", [account.insertId]))[0].agent_access, 1);
|
|
assert.equal(workerStarts, 2);
|
|
console.log("PASS: PM2 OFF stopped active and queued work, blocked a previously minted grant token, and preserved stored history and entitlements.");
|
|
await schedules.verifyOff(skipped);
|
|
await setAgent("ON");
|
|
await pm2Command("restart", "adpanel");
|
|
await waitPanel();
|
|
await waitWorker(3);
|
|
await assertServerAgentMarkup(browser, true);
|
|
await schedules.verifyReenabled(skipped);
|
|
|
|
const workerBeforeRotation = worker;
|
|
const startsBeforeRotation = workerStarts;
|
|
const rotatedSecret = `${fixtureSecret}-rotated`;
|
|
await setAgent("ON", rotatedSecret);
|
|
await pm2Command("restart", "adpanel");
|
|
await waitPanel();
|
|
await waitWorker(3, rotatedSecret);
|
|
assert.deepEqual(await workerBeforeRotation.closed, [0, null]);
|
|
assert.equal(workerStarts, startsBeforeRotation + 1, "only one reconciler may replace the old-key worker");
|
|
browser = await login(email);
|
|
const finalJob = await admit();
|
|
await resumeRun(finalJob.jobId, finalJob.chatId, { fetcher: browser }).result();
|
|
console.log("PASS: plain PM2 restart replaced the old-key worker exactly once after session secret rotation.");
|
|
await assertProviderSetup(await login(adminEmail), browser);
|
|
} catch (error) {
|
|
console.error(`Fixture service counters: starts=${workerStarts}, stops=${serviceStops}, worker exit=${worker?.child.exitCode}, signal=${worker?.child.signalCode}`);
|
|
const logs = await fs.readdir(path.join(processEnv.PM2_HOME, "logs")).catch(() => []);
|
|
for (const file of logs.filter((name) => name.startsWith("adpanel-"))) {
|
|
const contents = await fs.readFile(path.join(processEnv.PM2_HOME, "logs", file), "utf8");
|
|
if (contents.trim()) {
|
|
const fatal = contents.split("\n").find((line) => /failed to start|startup failed|ER_PARSE|fatal/i.test(line));
|
|
console.error(`${file}:\n${fatal || contents.slice(0, 800)}\n${contents.slice(-1400)}`);
|
|
}
|
|
}
|
|
for (const entry of processes) if (entry.output.trim()) console.error(`${entry.label}:\n${entry.output.slice(-1500)}`);
|
|
throw error;
|
|
} finally {
|
|
if (schedules) await schedules.close();
|
|
await pm2Command("kill").catch(() => {});
|
|
if (pool) await pool.end();
|
|
await Promise.all(processes.reverse().map(stop));
|
|
await Promise.all(servers.map((server) => new Promise((resolve) => { server.close(resolve); server.closeAllConnections(); })));
|
|
await fs.rm(root, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
if (require.main === module) {
|
|
Promise.resolve().then(() => process.argv[2] === "--isolated" ? staging(process.argv.slice(3)) : runIsolated(process.argv.slice(2))).catch((error) => {
|
|
console.error(error.message, error.stdout?.slice(-2000) || "", error.stderr?.slice(-2000) || "");
|
|
process.exitCode = 1;
|
|
});
|
|
}
|
|
|
|
module.exports = { requestService }; |