Files
Kelx/tests/server-agent-stream.test.js
T
2026-11-30 16:32:37 +00:00

1055 lines
63 KiB
JavaScript

"use strict";
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const { test } = require("node:test");
const vm = require("node:vm");
const { BOT_TOOL_DEFINITIONS, BOT_OPENAI_TOOL_DEFINITIONS, BOT_GOOGLE_FUNCTION_DECLARATIONS, buildBotAssistantSystemPrompt, isBotReadonlyToolName, resolveServerFromAccessibleList } = require("../utils/bot-ai-tools");
const serverAgentHistory = require("../public/js/server-agent-history");
const agentLive = require("../public/js/agent-live");
const { createRun, resumeRun } = agentLive;
const { AI_PROVIDER_CONFIGS } = require("../AgentWorker/provider-config");
const { applyAgentFileEdit, hashAgentFile, revertAgentFileEdit } = require("../AgentWorker/file-edit");
const { createAgentActionReview } = require("../AgentWorker/action-review");
const { createAgentFileDiagnostics } = require("../services/server-agent-file-diagnostics");
const { parseLiveAgentSubmission } = require("../AgentWorker/admission");
const { AGENT_ACTIONS, AGENT_ACTION_TOOL, AGENT_ACTION_INSTRUCTIONS, buildAgentActionOffer, normalizeAgentAction, getAgentCreationConflict,
parseAgentReview, serializeAgentReview, remainingAgentReviewSteps, splitAgentReview, isAgentFilePlan, pendingAgentFileTasks,
canAutoApproveAgentFileEdits, isAutomaticAgentFileEdit } = require("../AgentWorker/action-proposal");
const root = path.join(__dirname, "..");
const panel = fs.readFileSync(path.join(root, "index.js"), "utf8");
const browser = fs.readFileSync(path.join(root, "public/js/bot.js"), "utf8");
test("automatic Agent file edits require explicit consent and advertise only targeted edits", () => {
const row = { source: "planner_send", auto_approve_file_edits: 1, server_id: "2", account_epoch: 0, read_only: 0 };
for (const source of ["planner_send", "scheduler_planner_next", "scheduler_prompt"]) {
assert.equal(canAutoApproveAgentFileEdits({ ...row, source }), true);
}
for (const patch of [{ source: "live_chat" }, { source: "manual" }, { auto_approve_file_edits: 0 },
{ auto_approve_file_edits: undefined }, { server_id: null }, { account_epoch: null }, { read_only: 1 }]) {
assert.equal(canAutoApproveAgentFileEdits({ ...row, ...patch }), false);
}
const perms = { files_read: true, files_write: true, files_create: true, files_delete: true, console_write: true, server_start: true };
const { tool, instructions } = buildAgentActionOffer(perms, { automatic: true });
assert.deepEqual(tool.parameters.properties.action.enum, ["write_file"]);
assert.deepEqual(Object.keys(tool.parameters.properties), ["action", "path", "oldText", "newText"]);
assert.match(instructions, /without another prompt/);
assert.equal(buildAgentActionOffer({ ...perms, files_read: false }, { automatic: true }), null);
assert.equal(buildAgentActionOffer({ ...perms, files_write: false }, { automatic: true }), null);
assert.equal(isAutomaticAgentFileEdit({ action: "replace_file" }), false);
assert.match(buildAgentActionOffer(perms).instructions, /Only the operator can approve/);
});
test("automatic Agent dispatch uses the reviewed text writer without replay or stale writes", async () => {
const entry = { name: "fixture", id: 2 };
const row = { id: 3, user_id: 1, claim_token: "claim", source: "planner_send", auto_approve_file_edits: 1,
server_name: entry.name, server_id: entry.id, account_epoch: 1, read_only: 0, source_ref: "42" };
const original = "enabled=false\nlimit=6\n";
const proposal = { action: "write_file", path: "config/settings.ini", oldText: "enabled=false", newText: "enabled=true" };
const calls = [];
let text = original;
let attempts = 0;
let revoked = false;
let revokeOnRead = false;
let revokeOnLock = false;
let currentNode = "node-a";
let fenced = false;
let heldBy = null;
let preflightExpired = false;
let resumePreflight;
let abandonedPreflight;
const review = createAgentActionReview({
db: { createPanelDatabasePool: () => ({ async getConnection() { return {
async query({ sql, timeout }) {
assert.equal(timeout, 2000);
if (sql === "ROLLBACK") fenced = false;
else assert.equal(sql, "START TRANSACTION");
},
async execute(query, params) {
assert.match(query.sql, /FROM servers WHERE name = \? LIMIT 1 FOR UPDATE/);
assert.deepEqual(params, [entry.name]);
fenced = true;
if (revokeOnLock) revoked = true;
return [[{ id: entry.id, name: entry.name, node_id: currentNode, status: "running", suspended: 0 }]];
},
release() {},
}; } }), async query(sql, params) {
if (sql.startsWith("UPDATE server_planner_items")) {
assert.equal(fenced, true);
assert.match(sql, /job\.status = 'running' AND job\.claim_token = \?/);
assert.deepEqual(params, [row.id, "42", row.claim_token]);
heldBy = row.id;
return { affectedRows: 1 };
}
assert.match(sql, /job\.status = 'running'/);
assert.match(sql, /job\.auto_file_edit_attempts = \?/);
assert.deepEqual(params.slice(1, 3), [row.id, row.claim_token]);
if (params[3] !== attempts) return { affectedRows: 0 };
attempts = params[0];
return { affectedRows: 1 };
} },
featureEnabled: () => true, isRemoteEntry: () => true,
withTimeout(pending, timeout, label) {
assert.equal(timeout, 2000);
if (!preflightExpired) return pending;
abandonedPreflight = pending;
return Promise.reject(new Error(label));
},
resolveRemoteFsContext: async () => ({ remote: true, serverId: entry.id, serverName: entry.name, baseDir: "/fixture", node: {}, nodeId: "node-a" }),
fsRelayDeps: { buildNodeBaseUrl: () => "http://127.0.0.1:8080", buildNodeAuthHeaders: () => ({}), async httpRequestJson(url, _method, _headers, body) {
if (url.endsWith("/v1/fs/read")) {
if (revokeOnRead) revoked = true;
return { status: 200, json: { ok: true, content: Buffer.from(text).toString("base64") } };
}
assert.ok(url.endsWith("/v1/fs/write"));
assert.equal(fenced, true);
assert.equal(heldBy, row.id);
assert.equal(body.mode, "update");
assert.equal(body.expectedSha256, hashAgentFile(text));
assert.equal(body.path, "/fixture/config/settings.ini");
calls.push(body.content);
text = body.content;
return { status: 200, json: { ok: true } };
} },
recordActivity(_server, kind, detail) {
assert.equal(kind, "file_edit");
assert.equal(detail.via, "agent_auto_approved");
},
});
const dispatch = (args = {}, claimedRow = row) => review.applyAutomaticFileEdit({ row: claimedRow, entry,
user: { email: "editor@example.test" }, req: { async readAiAgentFilePermissions() {
if (fenced && preflightExpired) await new Promise((resolve) => { resumePreflight = resolve; });
if (fenced && revokeOnLock) throw Object.assign(new Error("Fixture permission was revoked"), { status: 403 });
return { files_read: true, files_write: !revoked };
} },
args: { proposal, editVersion: { sha256: hashAgentFile(original), nodeId: "node-a", path: `/fixture/${proposal.path}` }, attempt: 1, ...args },
signal: new AbortController().signal });
await assert.rejects(dispatch({}, { ...row, auto_approve_file_edits: 0 }), { code: "agent_automatic_file_edit_denied" });
await assert.rejects(dispatch({ proposal: { action: "delete_file", path: proposal.path } }), { code: "agent_automatic_file_edit_invalid" });
assert.equal((await dispatch()).state, "applied");
await assert.rejects(dispatch(), { code: "agent_automatic_file_edit_used" });
assert.equal((await dispatch({ attempt: 2 })).state, "refused");
text = original;
revokeOnRead = true;
assert.equal((await dispatch({ attempt: 3 })).state, "refused");
revoked = revokeOnRead = false;
currentNode = "node-b";
assert.match((await dispatch({ attempt: 4 })).receipt.text, /server moved/);
currentNode = "node-a";
revokeOnLock = true;
assert.match((await dispatch({ attempt: 5 })).receipt.text, /Permission to make this edit was revoked/);
revoked = revokeOnLock = false;
preflightExpired = true;
attempts = 0;
heldBy = null;
assert.match((await dispatch()).receipt.text, /could not verify permissions in time/);
assert.equal(fenced, false);
resumePreflight();
await abandonedPreflight;
assert.equal(heldBy, null);
assert.deepEqual(calls, ["enabled=true\nlimit=6\n"]);
});
test("Agent diagnostics give an automatic edit only the hash of complete readable text", async () => {
let reply;
const { executeAiAgentFileOperations } = createAgentFileDiagnostics({
env: { AI_AGENT_FILE_READ_MAX_CHARS: "2000" },
resolveRemoteFsContext: async () => ({ remote: true, serverId: "2", serverName: "fixture", baseDir: "/fixture", node: {}, nodeId: "fixture-node" }),
fsRelayDeps: { buildNodeBaseUrl: () => "http://127.0.0.1:8080", buildNodeAuthHeaders: () => ({}), httpRequestJson: async () => reply },
});
const read = async (includeEditVersion) => (await executeAiAgentFileOperations({
operations: [{ action: "read", path: "config/settings.ini" }], serverName: "fixture", serverId: "2",
req: { readAiAgentFilePermissions: async () => ({ files_read: true }) }, structured: true, includeEditVersion,
}))[0];
for (const text of ["", "limit=6\n"]) {
reply = { status: 200, json: { ok: true, content: Buffer.from(text).toString("base64") } };
assert.deepEqual((await read(true)).editVersion, { sha256: hashAgentFile(text), nodeId: "fixture-node", path: "/fixture/config/settings.ini" });
assert.equal((await read(false)).editVersion, undefined);
}
reply = { status: 200, json: { ok: true, content: Buffer.from("A".repeat(2001)).toString("base64") } };
assert.equal((await read(true)).editVersion, undefined);
reply = { status: 404, json: { ok: false } };
assert.equal((await read(true)).editVersion, undefined);
});
test("a reviewed Agent edit distinguishes a missing file from a readable empty file", async () => {
const account = { id: 1, session_epoch: 1, admin: true, email: "operator@example.test" };
const entry = { name: "fixture", id: 2 };
const proposal = { action: "write_file", path: "config/settings.ini", oldText: "enabled=false", newText: "enabled=true" };
const row = { id: 3, user_id: account.id, account_epoch: account.session_epoch, server_name: entry.name,
server_id: entry.id, action_proposal: serializeAgentReview(proposal) };
let reply = { status: 404, json: { ok: false, error: "file not found" } };
const review = createAgentActionReview({
db: { query: async () => [row] }, featureEnabled: () => true, findServer: async () => entry,
isServerSuspended: () => false, isRemoteEntry: () => true, getEffectivePermsForUserOnServer: async () => ({ files_read: true, files_write: true }),
findUserById: async () => account, userCanUseAdpanelAgent: () => true,
resolveRemoteFsContext: async () => ({ remote: true, serverId: entry.id, serverName: entry.name, baseDir: "/fixture" }),
issueActionToken: (_req, action) => action,
fsRelayDeps: {
buildNodeBaseUrl: () => "http://127.0.0.1:8080", buildNodeAuthHeaders: () => ({}), httpRequestJson: async () => reply,
},
});
const preview = () => review.preview({ agentAccount: account }, row.id, entry.name);
const missing = await preview();
assert.equal(missing.before, null);
assert.equal(missing.expectedSha256, null);
assert.match(missing.token, /decline only/);
assert.match(missing.previewError, /node reported that the file was not found/i);
reply = { status: 200, json: { ok: true, content: "" } };
const empty = await preview();
assert.equal(empty.before, "");
assert.equal(empty.expectedSha256, null);
assert.match(empty.previewError, /exact text to replace was not found/i);
const requestedText = "print(6 * 7)\n";
row.action_proposal = serializeAgentReview({ ...proposal, oldText: "", newText: requestedText });
const fill = await preview();
assert.equal(fill.before, "");
assert.equal(fill.proposedText, requestedText);
assert.match(fill.diff, /\+print\(6 \* 7\)/);
assert.equal(fill.expectedSha256, hashAgentFile(""));
assert.doesNotMatch(fill.token, /decline only/);
assert.equal(fill.previewError, undefined);
for (const upstream of [
{ status: 404, json: { ok: false } },
{ status: 200, json: { ok: true } },
{ status: 200, json: { ok: true, content: "!" } },
{ status: 200, json: { ok: true, content: Buffer.from([0xff]).toString("base64") } },
{ status: 200, json: { ok: true, content: Buffer.from("existing settings").toString("base64") } },
]) {
reply = upstream;
const blocked = await preview();
assert.equal(blocked.expectedSha256, null);
assert.match(blocked.token, /decline only/);
}
});
test("a targeted Agent edit preserves unrelated settings and refuses an ambiguous match", () => {
const original = "# Server settings\r\nonline-mode=true\r\nmax-players=20\r\n";
assert.deepEqual(applyAgentFileEdit(original, "online-mode=true", "online-mode=false", 16_000), {
content: "# Server settings\r\nonline-mode=false\r\nmax-players=20\r\n", offset: original.indexOf("online-mode"),
});
assert.deepEqual(applyAgentFileEdit(original, "online-mode=false", "online-mode=true", 16_000), { error: "review_edit_not_found" });
assert.deepEqual(applyAgentFileEdit(`${original}online-mode=true`, "online-mode=true", "online-mode=false", 16_000), { error: "review_edit_ambiguous" });
assert.deepEqual(applyAgentFileEdit(original, original.trim(), "online-mode=false", 16_000), { error: "review_edit_whole_file" });
assert.deepEqual(applyAgentFileEdit("abc", "b", "$&", 4), { content: "a$&c", offset: 1 });
assert.deepEqual(applyAgentFileEdit("abc", "b", "$&", 3), { error: "review_edit_too_large" });
assert.deepEqual(applyAgentFileEdit("", "", "sample\n", 16_000), { content: "sample\n", offset: 0 });
assert.deepEqual(applyAgentFileEdit("", "", "sample\n", 6), { error: "review_edit_too_large" });
assert.deepEqual(applyAgentFileEdit("\n", "", "sample\n", 16_000), { error: "review_edit_not_found" });
assert.deepEqual(applyAgentFileEdit("", "", "", 16_000), { error: "review_edit_invalid" });
});
test("a confirmed Agent replacement can restore the recorded original bytes, including an empty file", () => {
const original = "# Broken settings\r\nonline-mode=false\r\n";
const replacement = "online-mode=true\nmax-players=20\n";
const snapshot = { offset: 0, afterSha256: hashAgentFile(replacement) };
for (const oldText of [original, ""]) {
assert.deepEqual(revertAgentFileEdit(replacement, { oldText, newText: replacement }, snapshot, 16_000), { content: oldText });
}
});
test("an Agent revert uses the recorded offset and fails closed after another file change", () => {
const edit = { oldText: "online-mode=true", newText: "" };
const original = "# Some settings\nonline-mode=true\nmax-players=20\n";
const { content, offset } = applyAgentFileEdit(original, edit.oldText, edit.newText, 16_000);
const snapshot = { offset, afterSha256: hashAgentFile(content) };
assert.deepEqual(revertAgentFileEdit(content, edit, snapshot, 16_000), { content: original });
assert.deepEqual(revertAgentFileEdit(`${content}motd=Changed\n`, edit, snapshot, 16_000), { error: "review_revert_changed" });
assert.deepEqual(revertAgentFileEdit(content, edit, null, 16_000), { error: "review_revert_unavailable" });
});
test("a reviewed Agent action has exact arguments and cannot smuggle authority or a new mode", () => {
const legacyModule = { exports: {} };
const proposalSource = fs.readFileSync(require.resolve("../AgentWorker/action-proposal"), "utf8");
vm.runInNewContext(`String.prototype.isWellFormed = undefined;\n${proposalSource}`, { module: legacyModule, Buffer });
const legacy = legacyModule.exports;
const examples = {
start: {}, stop: {}, restart: {}, kill: {}, console_command: { command: "list" },
write_file: { path: "config/\u{1f4c4}.yml", oldText: "enabled: false", newText: "enabled: true\n# \u{1f4c4}\n" },
replace_file: { path: "server.properties", content: "online-mode=true\nmax-players=20\n" },
revert_file: { path: "config/settings.yml" },
create_file: { path: "README.txt", content: "" }, create_folder: { path: "maps/World 1" },
delete_file: { path: "old.txt" }, create_backup: { name: "Before update", description: "" },
restore_backup: { backup: "backup-1", deleteOldFiles: false }, delete_backup: { backup: "backup-1" },
};
assert.deepEqual(Object.keys(examples).sort(), [...AGENT_ACTIONS].sort());
for (const [action, fields] of Object.entries(examples)) {
const proposal = { action, ...fields };
assert.deepEqual(normalizeAgentAction(proposal), proposal);
assert.equal(JSON.stringify(legacy.normalizeAgentAction(proposal)), JSON.stringify(proposal), action);
for (const forbidden of [{ approved: true }, { server: "other" }, { mode: "monitor" }]) {
assert.equal(normalizeAgentAction({ ...proposal, ...forbidden }), null);
}
}
for (const path of ["/absolute", "foo/../bar", "foo//bar", "foo\\bar", "settings\u202e.yml", "settings\n.yml"]) {
assert.equal(normalizeAgentAction({ action: "write_file", path, oldText: "a", newText: "x" }), null);
}
assert.equal(normalizeAgentAction({ action: "write_file", path: "config.yml", oldText: "a", newText: "é".repeat(8001) }), null);
assert.equal(normalizeAgentAction({ action: "write_file", path: "config.yml", content: "enabled: false" }), null);
const fill = { action: "write_file", path: "sample.py", oldText: "", newText: "print(42)\n" };
assert.deepEqual(normalizeAgentAction(fill), fill);
assert.equal(normalizeAgentAction({ ...fill, newText: "" }), null);
assert.equal(normalizeAgentAction({ action: "replace_file", path: "server.properties", content: "" }), null);
assert.equal(normalizeAgentAction({ action: "replace_file", path: "server.properties", content: "a".repeat(16_001) }), null);
assert.equal(normalizeAgentAction({ action: "replace_file", path: "server.properties", content: "a", oldText: "b" }), null);
assert.equal(normalizeAgentAction({ action: "console_command", command: "list\nstop" }), null);
assert.equal(normalizeAgentAction({ action: "constructor" }), null);
assert.equal(legacy.normalizeAgentAction({ action: "create_file", path: "bad\ud800.txt", content: "" }), null);
assert.equal(legacy.normalizeAgentAction({ action: "write_file", path: "valid.txt", oldText: "a", newText: "broken\udfff" }), null);
assert.equal(legacy.normalizeAgentFileTool("read_server_file", { path: "config/\u{1f4c4}.yml" }).path, "config/\u{1f4c4}.yml");
});
test("the shared Agent prompt describes review and forbids mode changes only in the live action workflow", () => {
assert.deepEqual(AGENT_ACTION_TOOL.parameters.properties.action.enum, AGENT_ACTIONS);
const live = buildBotAssistantSystemPrompt({ actionInstructions: AGENT_ACTION_INSTRUCTIONS });
assert.match(live, /Do not switch to normal chat, monitor mode/);
assert.match(live, /Only the operator can approve it in the panel/);
assert.match(live, /propose_server_action/);
assert.match(live, /Infer the user's intended outcome.*operation verbs are clues to intent.*When the user delegates a choice, decide it yourself/);
assert.match(live, /Do not end with an offer.*If one step is blocked, prepare the next independent requested action/);
assert.match(live, /file_not_found.*does not depend on prior contents.*propose create_file for review even if the user described it as an edit/);
assert.match(live, /Do not create a file if the user required an existing file or ruled out creation.*Do not treat a permission, path, format, or connectivity error as a missing file/);
assert.match(live, /If the read confirms the file exists and is empty, send an empty oldText/);
assert.match(live, /Do not ask the operator to paste file contents you can read/);
assert.match(live, /explicitly asks to replace an existing file.*use replace_file/);
assert.doesNotMatch(buildBotAssistantSystemPrompt({}), /propose_server_action/);
});
test("review schemas and prompts describe only permitted actions and distinguish file reads from changes", () => {
assert.equal(buildAgentActionOffer({ files_read: true, files_write: false }), null);
assert.equal(buildAgentActionOffer({ files_write: true }), null);
const creation = buildAgentActionOffer({ files_create: true });
assert.deepEqual(creation.tool.parameters.properties.action.enum, ["create_file", "create_folder"]);
assert.deepEqual(Object.keys(creation.tool.parameters.properties), ["action", "path", "content", "fileTasks", "changeSummary", "planComplete"]);
assert.deepEqual(creation.tool.parameters.properties.fileTasks.items.properties.action.enum, ["create_file", "create_folder"]);
assert.match(creation.instructions, /create_folder\(path\)/);
assert.doesNotMatch(creation.instructions, /write_file|read_server_file|console_command/);
const editor = buildAgentActionOffer({ files_read: true, files_write: true });
const prompt = buildBotAssistantSystemPrompt({ currentServerPerms: { files_read: true }, actionInstructions: editor.instructions });
assert.deepEqual(editor.tool.parameters.properties.action.enum, ["write_file", "replace_file", "revert_file"]);
assert.match(prompt, /diagnostic permissions: server status, read server files/);
assert.match(prompt, /write_file\(path, oldText, newText\)/);
assert.doesNotMatch(prompt, /propose create_file/);
assert.doesNotMatch(prompt, /server status only|cannot change them/);
});
test("Agent creation conflict checks use path boundaries and do not assume state survived deletion or restore", () => {
const folder = { action: "create_folder", path: "reports" };
const file = { action: "create_file", path: "reports/week/summary.txt", content: "New content" };
const created = { action: file.action, path: file.path, decision: "accepted" };
assert.match(getAgentCreationConflict(folder, [created]).error, /already used this parent directory/);
assert.equal(getAgentCreationConflict({ ...folder, path: "report" }, [created]), null);
assert.equal(getAgentCreationConflict(folder, [{ ...created, decision: "declined" }]), null);
assert.equal(getAgentCreationConflict(file, [created, { action: "delete_file", path: file.path, decision: "accepted" }]), null);
const restored = { action: "restore_backup", decision: "accepted" };
assert.equal(getAgentCreationConflict(folder, [created, restored]), null);
const declined = { ...folder, decision: "declined" };
assert.match(getAgentCreationConflict(folder, [declined, restored]).error, /operator already declined/);
assert.match(getAgentCreationConflict(file, [declined]).error, /declined creation of a parent folder/);
assert.match(getAgentCreationConflict({ ...folder, path: "reports/week" }, [declined]).error, /declined creation of a parent folder/);
assert.equal(getAgentCreationConflict({ ...file, path: "reports-other/week/summary.txt" }, [declined]), null);
assert.equal(getAgentCreationConflict({ ...file, action: "write_file" }, [created]), null);
});
test("Agent plans preserve ordered proposals but cannot carry approval or exceed the step limit", () => {
const actions = [{ action: "create_folder", path: "Hey" }, { action: "create_file", path: "Hey/hey.py", content: "" }];
assert.deepEqual(parseAgentReview(serializeAgentReview(actions[0], actions.slice(1))), { actions, resumeModel: false });
assert.deepEqual(parseAgentReview(serializeAgentReview(actions[0], [], true)), { actions: [actions[0]], resumeModel: true });
assert.equal(serializeAgentReview(actions[0], actions.slice(1), true), null);
assert.equal(normalizeAgentAction({ ...actions[0], resumeModel: true }), null);
assert.equal(parseAgentReview(JSON.stringify({ ...actions[0], approved: true })), null);
assert.equal(serializeAgentReview(actions[0], [{ ...actions[1], approved: true }]), null);
assert.equal(serializeAgentReview(actions[0], new Array(5).fill(actions[1])), null);
assert.equal(serializeAgentReview({ action: "write_file", path: "settings.yml", content: "one truncated line" }), null);
const independent = { action: "create_folder", path: "Other", requiresPrevious: false };
assert.deepEqual(remainingAgentReviewSteps([actions[1], independent], "dismissed"), [independent]);
assert.deepEqual(remainingAgentReviewSteps([independent], "unknown"), []);
});
test("a definite refusal preserves independently reviewable live drafts without replaying a blocked path", () => {
const child = { action: "create_file", path: "reports/today.txt", content: "Notes\n" };
const sibling = { action: "create_file", path: "reports-other.txt", content: "Other\n" };
const rootFile = { action: "create_file", path: "utility.py", content: "print(42)\n" };
const remaining = [child, sibling, rootFile];
const blocked = { action: "create_folder", path: "reports", decision: "refused" };
const live = { resumeModel: true, outcome: blocked };
assert.deepEqual(remainingAgentReviewSteps(remaining, "refused", live), [sibling, rootFile]);
assert.deepEqual(remainingAgentReviewSteps(remaining, "refused", { ...live, outcome: { ...blocked, code: "review_path_exists" } }), remaining);
assert.deepEqual(remainingAgentReviewSteps(remaining, "stale", { ...live, outcome: { action: "write_file", path: "settings.yml" } }), remaining);
for (const state of ["dismissed", "unknown"]) assert.deepEqual(remainingAgentReviewSteps(remaining, state, live), []);
assert.deepEqual(remainingAgentReviewSteps(remaining, "refused", { outcome: blocked }), []);
});
test("file task checklists persist but only the current proposal can enter a review", () => {
const current = { action: "create_folder", path: "reports" };
const tasks = [{ action: "write_file", path: "settings.yml" }, current, { action: "create_file", path: "reports/today.txt" }];
const saved = parseAgentReview(serializeAgentReview(current, [], true, tasks));
assert.deepEqual(saved, { actions: [current], resumeModel: true, fileTasks: tasks });
assert.deepEqual(pendingAgentFileTasks(saved.fileTasks, [{ ...current, decision: "accepted" }]), [tasks[0], tasks[2]]);
assert.deepEqual(pendingAgentFileTasks(saved.fileTasks, [{ ...current, decision: "accepted" }, { ...tasks[0], decision: "declined" }]), [tasks[2]]);
for (const invalid of [[...tasks, current], [{ ...current, approved: true }], [{ ...current, path: "../escape" }], [{ action: "restart", path: "reports" }]]) {
assert.equal(serializeAgentReview(current, [], true, invalid), null);
assert.equal(parseAgentReview(JSON.stringify({ ...current, resumeModel: true, fileTasks: invalid })), null);
}
assert.equal(serializeAgentReview(current, [], false, tasks), null);
});
test("a model's queued file changes each require a distinct review even in General access", () => {
const actions = [{ action: "write_file", path: "settings.yml", oldText: "enabled: false", newText: "enabled: true", changeSummary: "Enabled the requested setting." },
{ action: "create_file", path: "reports/today.txt", content: "Notes\n" }];
const fileTasks = actions.map(({ action, path }) => ({ action, path }));
const saved = parseAgentReview(serializeAgentReview(actions[0], actions.slice(1), true, fileTasks, true));
assert.deepEqual(saved, { actions, resumeModel: true, fileTasks, planComplete: true });
assert.deepEqual(splitAgentReview(saved.actions, true, saved.resumeModel), { steps: actions.slice(0, 1), remainingActions: actions.slice(1) });
assert.deepEqual(splitAgentReview(saved.actions, true), { steps: actions, remainingActions: [] });
assert.equal(serializeAgentReview(actions[0], actions.slice(1), true, fileTasks.slice(0, 1)), null);
assert.equal(serializeAgentReview(actions[0], [{ action: "restart" }], true, fileTasks), null);
assert.equal(serializeAgentReview(actions[0], [], false, undefined, true), null);
assert.equal(normalizeAgentAction({ ...actions[0], changeSummary: "First line\nSecond line" }), null);
assert.equal(normalizeAgentAction({ ...actions[0], changeSummary: "a".repeat(201) }), null);
assert.equal(normalizeAgentAction({ ...actions[0], approved: true }), null);
});
test("a file plan can group edits and creations on distinct paths, never non-file or destructive actions", () => {
const edit = { action: "replace_file", path: "server.properties", content: "online-mode=true\n" };
assert.equal(isAgentFilePlan([edit, { action: "create_folder", path: "hey" }]), true);
assert.equal(isAgentFilePlan([edit]), false);
assert.equal(isAgentFilePlan([edit, { ...edit, path: "SERVER.PROPERTIES" }]), false);
for (const action of ["console_command", "restart", "delete_file", "revert_file", "restore_backup"]) {
assert.equal(isAgentFilePlan([edit, { action, path: "other" }]), false);
}
});
test("the saved Agent access picker is scoped to its account and server, and cannot grant full access", () => {
const view = fs.readFileSync(path.join(root, "views/bot.ejs"), "utf8");
const options = view.match(/<select\b[^>]*\bid="aiAgentAccessMode"[^>]*>([\s\S]*?)<\/select>/)?.[1] || "";
assert.deepEqual(Array.from(options.matchAll(/<option value="([^"]+)">([^<]+)<\/option>/g), ([, value, label]) => [value, label]), [
["file_plan", "General access"], ["read_only", "Read only"],
]);
const values = new Map();
const storage = { getItem: (key) => values.get(key), setItem: (key, value) => values.set(key, value) };
const picker = () => ({ addEventListener(_event, handler) { this.change = handler; } });
const first = picker();
const current = agentLive.bindAccessMode(first, "fixture@example.test", "fixture", storage);
assert.equal(current(), "file_plan");
first.value = "read_only";
first.change();
assert.equal(agentLive.bindAccessMode(picker(), "fixture@example.test", "fixture", storage)(), "read_only");
assert.equal(agentLive.bindAccessMode(picker(), "another@example.test", "fixture", storage)(), "file_plan");
assert.equal(agentLive.bindAccessMode(picker(), "fixture@example.test", "another", storage)(), "file_plan");
const [key] = values.keys();
values.set(key, "general");
assert.equal(agentLive.bindAccessMode(picker(), "fixture@example.test", "fixture", storage)(), "file_plan");
first.value = "file_plan";
first.change();
assert.equal(agentLive.bindAccessMode(picker(), "fixture@example.test", "fixture", storage)(), "file_plan");
first.value = "full";
assert.equal(current(), "file_plan");
const request = { requestKey: "ca17f659-08dc-4437-ac7b-ca4884f08ff3", prompt: "Check status", server: "fixture" };
assert.equal(parseLiveAgentSubmission({ ...request, accessMode: "read_only" }).accessMode, "read_only");
assert.equal(parseLiveAgentSubmission({ ...request, accessMode: "file_plan" }).accessMode, "file_plan");
assert.throws(() => parseLiveAgentSubmission({ ...request, accessMode: "full" }), { code: "agent_invalid_access_mode" });
});
test("the custom provider form reopens the complete manual model list without losing punctuation", () => {
const field = { hidden: true };
const input = { value: "" };
const window = { document: { getElementById: (id) => ({ aiManualModelField: field, aiManualModelInput: input })[id] } };
vm.runInNewContext(fs.readFileSync(require.resolve("../public/js/agent-live"), "utf8"), window);
const client = window.adpanelAgentLive;
const models = ["Team/Chat", "Team/chat,preview:2"];
client.showProviderModelInput(true, models);
assert.equal(field.hidden, false);
assert.equal(input.value, models.join("\n"));
input.value += "\r\n \r\n new-model:7b \r\n";
assert.deepEqual(Array.from(client.readProviderModelIds()), [...models, "new-model:7b"]);
input.value = "";
assert.equal(client.readProviderModelIds().length, 0);
client.showProviderModelInput(true, "legacy-id");
assert.deepEqual(Array.from(client.readProviderModelIds()), ["legacy-id"]);
client.showProviderModelInput(false, models);
assert.equal(field.hidden, true);
assert.equal(input.value, "");
assert.equal(client.readProviderModelIds(), undefined);
});
test("inline Agent review is reply scoped and only a trusted decision sends approval", async () => {
const nodes = new Map();
const requests = [];
const events = [];
let loseAcknowledgement = false;
let statusReads = 0;
let finishPreview;
const expectedSha256 = "a".repeat(64);
const activity = [
{ action: "write_file", target: "config.yml", status: "applied", detail: "Confirmed a version-checked write.", addedLines: 1, removedLines: 2 },
{ action: "console_command", target: "fixture", status: "applied", command: "say <tag>", detail: "Delivery acknowledged; output not verified." },
];
const window = {};
function element() {
return {
listeners: {}, parentElement: {}, children: [], hidden: true,
addEventListener(event, handler) { this.listeners[event] = handler; },
setAttribute(name, value) { this[name] = value; },
append(...children) { this.children.push(...children); for (const child of children) if (typeof child === "object") child.parentElement = this; },
prepend(child) { this.children.unshift(child); child.parentElement = this; },
querySelector(selector) { return selector === ":scope > .agent-action-log" ? this.children.find((child) => child.className === "agent-action-log") : null; },
get lastElementChild() { return this.children.at(-1); },
set textContent(value) { this.text = value; this.children.length = 0; },
get textContent() { return this.text; },
set innerHTML(_value) { assert.fail("review data must be displayed as text"); },
};
}
const messageBody = element();
const thread = { lastElementChild: { classList: { contains: (value) => value === "ai" }, querySelector: () => messageBody } };
const document = {
documentElement: { dataset: { bot: "fixture" } },
dispatchEvent(event) { events.push(event); },
createElement: element,
getElementById(id) {
if (!nodes.has(id)) nodes.set(id, element());
return nodes.get(id);
},
};
const data = { chat: { review_job_id: "41", review_message_id: "30", review_server: "fixture" }, messages: [{ id: 30, role: "assistant", content: "Review it." }] };
const history = serverAgentHistory.clone(serverAgentHistory.fromPage(data, 14));
assert.equal(serverAgentHistory.reviewJobId(history, 14, "fixture"), "41");
assert.equal(serverAgentHistory.reviewJobId(history, 14, "another"), null);
assert.equal(serverAgentHistory.reviewJobId(history, 15, "fixture"), null);
assert.equal(serverAgentHistory.reviewJobId(serverAgentHistory.fromPage({ ...data, messages: [{ id: 31, role: "assistant" }] }, 14), 14, "fixture"), null);
history.push({ role: "user", content: "A new message." });
assert.equal(serverAgentHistory.reviewJobId(history, 14, "fixture"), null);
const source = fs.readFileSync(path.join(root, "public/js/server-agent-review.js"), "utf8");
vm.runInNewContext(source, { document, window, URLSearchParams, AbortSignal, serverAgentHistory, setTimeout: (run) => run(),
CustomEvent: class { constructor(type, { detail }) { this.type = type; this.detail = detail; } },
fetch: async (route, options) => {
requests.push({ route, options });
if (route === "/api/ai/jobs/71/review?server=fixture") return new Promise((resolve) => { finishPreview = resolve; });
if (loseAcknowledgement && options.method === "POST") throw new TypeError("Connection lost after approval");
if (route === "/api/ai/jobs/51") {
const settled = ++statusReads > 1;
return Response.json({ job: { id: "51", chat_id: "15", review_server: "fixture",
review_state: settled ? "applied" : "applying",
...(settled && { review_conclusion_job_id: "52", agent_actions: JSON.stringify(activity) }) } });
}
if (route === "/api/ai/jobs/61/review?server=fixture") return Response.json({
server: "fixture", proposal: { action: "write_file", path: "missing.yml", content: "new" },
before: null, expectedSha256: null, token: "decline-token", previewError: "This file could not be verified.",
});
if (route === "/api/ai/jobs/61/review") return Response.json({ state: "dismissed", chatId: "16", conclusionJobId: "62" });
if (route === "/api/ai/jobs/42/review?server=fixture") return Response.json({
server: "fixture", proposal: { action: "create_file", path: "reports/today.txt", content: "Notes\n" },
expectedSha256: "", token: "continuation-token",
});
if (route === "/api/ai/jobs/91/review?server=fixture") return Response.json({
server: "fixture", expectedSha256: [expectedSha256, ""], token: "plan-token", plan: [
{ proposal: { action: "replace_file", path: "server.properties", content: "online-mode=true\n" },
before: "online-mode=false\n", diff: "@@ -1 +1 @@\n-online-mode=false\n+online-mode=true\n" },
{ proposal: { action: "create_folder", path: "hey" } },
],
});
return options.method === "POST" ? Response.json({ state: "applied", chatId: "14", conclusionJobId: "42", activity: activity.slice(0, 1) }) : Response.json({
server: "fixture", proposal: { action: "write_file", path: "config.yml", content: "<tag>\n" },
before: "old\n", diff: "@@ -1 +1 @@\n-old\n+<tag>\n", expectedSha256, token: "fixture-token",
});
},
});
const click = (id, isTrusted) => nodes.get(id).listeners.click({ isTrusted });
await window.adpanelAgentReview.bind("41", thread);
assert.equal(nodes.get("aiReviewCard").parentElement, messageBody);
assert.equal(nodes.get("aiReviewCard").hidden, false);
assert.equal(nodes.get("aiReviewAfter").textContent, "<tag>\n");
const rows = nodes.get("aiReviewDiff").children;
assert.match(rows[1].className, /line-remove/);
assert.match(rows[2].className, /line-add/);
assert.equal(rows[2].textContent, "+<tag>");
await click("aiReviewApply", false);
assert.equal(requests.length, 1);
await click("aiReviewApply", true);
await click("aiReviewApply", true);
assert.equal(requests.length, 2);
assert.equal(requests[0].route, "/api/ai/jobs/41/review?server=fixture");
assert.equal(requests[1].route, "/api/ai/jobs/41/review");
assert.equal(requests[1].options.headers["x-action-token"], "fixture-token");
assert.deepEqual(JSON.parse(requests[1].options.body), { server: "fixture", decision: "apply", expectedSha256 });
assert.equal(nodes.get("aiReviewCard").hidden, true);
assert.equal(events.length, 1);
assert.equal(events[0].type, "adpanel:agent-review-settled");
assert.equal(events[0].detail.chatId, "14");
assert.equal(events[0].detail.conclusionJobId, "42");
const visibleActions = messageBody.querySelector(":scope > .agent-action-log").lastElementChild.children;
assert.equal(visibleActions.length, 1);
assert.match(visibleActions[0].lastElementChild.textContent, /\+1 \/ -2 lines/);
const completed = serverAgentHistory.fromPage({ messages: [{ role: "assistant", id: 30,
content: "Finished the server update.", agent_actions: JSON.stringify(activity) }] }, 14);
const reopenedBody = element();
const reopened = { children: [{ querySelector: () => reopenedBody }] };
await window.adpanelAgentReview.bind(null, reopened, completed);
await window.adpanelAgentReview.bind(null, reopened, completed);
const savedActions = reopenedBody.querySelector(":scope > .agent-action-log").lastElementChild.children;
assert.equal(savedActions.length, 2, "rendering the saved transcript must not duplicate entries");
assert.equal(savedActions[0].children[0].textContent, "Edit file: config.yml");
assert.equal(savedActions[0].children[1].textContent, "Confirmed");
assert.equal(savedActions[1].children[1].textContent, "Sent");
assert.equal(savedActions[1].children[2].textContent, "say <tag>");
assert.match(savedActions[1].lastElementChild.textContent, /output not verified/);
assert.equal(completed[0].content, "Finished the server update.");
assert.deepEqual(serverAgentHistory.readActions("not JSON"), []);
loseAcknowledgement = true;
await window.adpanelAgentReview.bind("51", thread);
await click("aiReviewApply", true);
assert.deepEqual(requests.slice(2).map(({ route, options }) => [route, options.method || "GET"]), [
["/api/ai/jobs/51/review?server=fixture", "GET"], ["/api/ai/jobs/51/review", "POST"], ["/api/ai/jobs/51", "GET"], ["/api/ai/jobs/51", "GET"],
]);
assert.equal(nodes.get("aiReviewCard").hidden, true);
assert.equal(events[1].detail.chatId, "15");
assert.equal(events[1].detail.conclusionJobId, "52");
assert.equal(messageBody.querySelector(":scope > .agent-action-log").lastElementChild.children.length, 2);
loseAcknowledgement = false;
await window.adpanelAgentReview.bind("61", thread);
assert.equal(nodes.get("aiReviewApply").disabled, true);
assert.equal(nodes.get("aiReviewDismiss").disabled, false);
assert.equal(nodes.get("aiReviewStatus").textContent, "This file could not be verified.");
await click("aiReviewApply", true);
await click("aiReviewDismiss", false);
assert.equal(requests.length, 7);
await click("aiReviewDismiss", true);
assert.equal(requests.length, 8);
assert.equal(requests[7].options.headers["x-action-token"], "decline-token");
assert.deepEqual(JSON.parse(requests[7].options.body), { server: "fixture", decision: "dismiss", expectedSha256: null });
assert.equal(nodes.get("aiReviewCard").hidden, true);
assert.equal(events[2].detail.conclusionJobId, "62");
const oldPreview = window.adpanelAgentReview.bind("71", thread);
await window.adpanelAgentReview.bind("81", thread);
finishPreview(Response.json({ server: "fixture", proposal: { action: "console_command", command: "old command" }, expectedSha256: "", token: "old-token" }));
await oldPreview;
assert.equal(nodes.get("aiReviewHeading").textContent, "Edit file");
assert.match(nodes.get("aiReviewSummary").textContent, /config\.yml/);
assert.equal(requests.length, 10);
await window.adpanelAgentReview.bind("91", thread);
const plan = nodes.get("aiReviewPlan");
assert.equal(plan.hidden, false);
assert.equal(nodes.get("aiReviewHeading").textContent, "File plan (2 steps)");
assert.equal(nodes.get("aiReviewApplyLabel").textContent, "Accept plan");
assert.match(nodes.get("aiReviewStatus").textContent, /Replacement removes settings/);
assert.match(nodes.get("aiReviewStatus").textContent, /Changes already applied are kept/);
assert.deepEqual(plan.children.map((item) => item.children[1].textContent), ["Path: server.properties", "Path: hey"]);
assert.equal(plan.children[0].children[2].children[1].children[2].textContent, "+online-mode=true");
await click("aiReviewApply", false);
assert.equal(requests.length, 11, "preview and synthetic clicks must not submit a plan");
await click("aiReviewApply", true);
await click("aiReviewApply", true);
assert.equal(requests.length, 12);
assert.equal(requests[11].options.headers["x-action-token"], "plan-token");
assert.deepEqual(JSON.parse(requests[11].options.body), { server: "fixture", decision: "apply", expectedSha256: [expectedSha256, ""] });
const continuation = serverAgentHistory.fromPage({ ...data, chat: { ...data.chat, review_job_id: events[0].detail.conclusionJobId },
messages: [{ ...data.messages[0], content: "The previous edit was confirmed.", agent_actions: JSON.stringify(activity.slice(0, 1)) }],
}, 14);
await window.adpanelAgentReview.bind(serverAgentHistory.reviewJobId(continuation, 14, "fixture"), thread);
assert.equal(nodes.get("aiReviewCard").hidden, false);
assert.equal(nodes.get("aiReviewHeading").textContent, "Create file");
assert.match(nodes.get("aiReviewSummary").textContent, /reports\/today\.txt/);
assert.equal(nodes.get("aiReviewApply").disabled, false);
assert.equal(nodes.get("aiReviewDismiss").disabled, false);
assert.deepEqual(requests.slice(12).map(({ route, options }) => [route, options.method || "GET"]), [["/api/ai/jobs/42/review?server=fixture", "GET"]]);
await click("aiReviewApply", true);
assert.equal(requests[13].route, "/api/ai/jobs/42/review");
assert.equal(requests[13].options.headers["x-action-token"], "continuation-token");
});
for (const [profile, avatarUrl, expectedUrl] of [
["default", "/images/normal-2.webp", "/images/normal-2.webp"],
["configured", "https://example.com/avatar.webp?size=48&fit=cover", "https://example.com/avatar.webp?size=48&amp;fit=cover"],
]) {
test(`the Agent renderer uses the ${profile} avatar from the page bootstrap`, () => {
const start = browser.indexOf(" function isAiServerContextMessage(");
const end = browser.indexOf(" function aiCopyToClipboard(", start);
const escapeStart = browser.indexOf(" function escapeHtml(");
const escapeEnd = browser.indexOf("\n }", escapeStart) + "\n }".length;
const aiChatMessages = {};
const render = vm.runInNewContext(`${browser.slice(escapeStart, escapeEnd)}\n${browser.slice(start, end)}\nrenderChatHistory`, {
aiChatMessages,
aiChatHistory: [{ role: "user", content: "Check the server." }],
aiCurrentChatId: 14,
aiChatLoadToken: 1,
document: { getElementById: () => null },
serverAgentHistory,
loadChatFromDb: () => assert.fail("The renderer should not fetch a page"),
window: { __ADPANEL_BOOTSTRAP__: { currentUser: { avatarUrl } } },
buildThinkingBadgeHtml: () => "",
bindAiCodeCopyButtons() {},
});
render();
assert.ok(aiChatMessages.innerHTML.includes(`<img src="${expectedUrl}" alt="You" class="ai-user-avatar-img">`));
assert.match(aiChatMessages.innerHTML, /Check the server\./);
});
}
test("Agent history prepends one page without applying a stale chat response", async () => {
const button = {};
const scrollPane = { scrollTop: 20, scrollHeight: 200 };
const messages = serverAgentHistory.clone(serverAgentHistory.fromPage({
messages: [{ role: "assistant", content: "Recent reply" }], nextBeforeId: "9",
}, 14));
const applied = [];
let current = true;
let completePage;
serverAgentHistory.bindOlderButton(button, {
messages, chatId: 14, scrollPane,
loadPage: async (chatId, before) => {
assert.equal(chatId, 14);
assert.equal(before, "9");
return new Promise((resolve) => { completePage = resolve; });
},
isCurrent: () => current,
applyPage: (history) => { applied.push(history); scrollPane.scrollHeight += 50; },
showError: () => assert.fail("Expected a valid transcript page"),
});
assert.equal(button.hidden, false);
const staleLoad = button.onclick();
assert.equal(button.disabled, true);
current = false;
completePage({ messages: [{ role: "user", content: "Older message" }] });
await staleLoad;
assert.deepEqual(applied, []);
current = true;
const visibleLoad = button.onclick();
completePage({ messages: [{ role: "user", content: "Older message" }] });
await visibleLoad;
assert.deepEqual(applied[0].map(({ role, content }) => [role, content]), [
["user", "Older message"], ["ai", "Recent reply"],
]);
assert.equal(scrollPane.scrollTop, 70);
});
test("reopening an interrupted chat keeps the prompt and shows the worker outcome", () => {
const page = {
chat: { latest_job_status: "failed", latest_job_error: "agent_interrupted", latest_message_id: "52" },
messages: [{ id: 52, role: "user", content: "Check status" }],
};
const [prompt] = serverAgentHistory.fromPage(page, 14);
assert.equal(prompt.content, "Check status");
assert.deepEqual(prompt.agentOutcome, { status: "failed", error: "agent_interrupted" });
assert.match(agentLive.jobOutcomeMessage(prompt.agentOutcome), /worker stopped before this reply was saved/);
const older = { ...page, messages: [{ id: 51, role: "user", content: "Older prompt" }] };
assert.equal(serverAgentHistory.fromPage(older, 14)[0].agentOutcome, undefined);
});
test("neither interactive nor queued Agent runs can dispatch mutable tools", async () => {
const start = panel.indexOf("async function runBotAssistantTool(");
const end = panel.indexOf("\n}", start) + 2;
const names = BOT_TOOL_DEFINITIONS.map((tool) => tool.name);
const checkedPermissions = { ok: false, error: "permission check reached" };
const dispatch = new Function("BOT_AI_TOOL_NAMES", "isBotReadonlyToolName", "resolveBotToolServerOrError",
`${panel.slice(start, end)}\nreturn runBotAssistantTool;`
)(new Set(names), isBotReadonlyToolName, async () => ({ error: checkedPermissions }));
const interactiveRequest = { body: { askMode: "dont_ask" } };
const queuedRequest = { readAiAgentJobPermissions: async () => ({ server_start: true, backups_delete: true, console_write: true }) };
for (const req of [interactiveRequest, queuedRequest]) {
for (const name of names.filter((name) => !isBotReadonlyToolName(name))) {
const result = await dispatch({ req, name, args: { action: "start" } });
assert.equal(result.ok, false, name);
assert.match(result.error, /cannot change servers/, name);
}
assert.equal(await dispatch({ req, name: "inspect_server", args: {} }), checkedPermissions);
}
});
test("interactive chat sends through the installed Agent chat API", () => {
const start = browser.indexOf("async function sendAiMessage(");
const end = browser.indexOf("async function refreshChatsListAfterRun(", start);
const send = browser.slice(start, end);
assert.ok(send.includes("window.adpanelAgentLive.createRun("));
assert.ok(send.includes("await queuedRun.result()"));
assert.ok(!send.includes("saveMessageToDb("));
assert.ok(!send.includes("callAiBackendProxy("));
assert.ok(!send.includes("runAgentStream("));
const routes = fs.readFileSync(path.join(root, "routes/agent-live.js"), "utf8");
assert.ok(panel.includes('app.use("/api/ai", createAgentLiveRouter('));
assert.ok(routes.includes('router.post("/chat", authorize,'));
assert.ok(panel.includes('accountLimiter: settingsRateLimiters.serverAgentChatRateLimiter,'));
});
test("the shared model loader does not exceed the worker's discovery slots", async () => {
const start = browser.indexOf(" async function fetchModels(");
const end = browser.indexOf(" function closeAiModelDropdown(", start);
const providers = ["openai", "google", "anthropic"];
const { DISCOVERY_CONCURRENCY } = require("../AgentWorker/budgets");
let inFlight = 0;
let peak = 0;
const fetchModels = vm.runInNewContext(`${browser.slice(start, end)}\nfetchModels`, {
AI_PROVIDERS: Object.fromEntries(providers.map((provider) => [provider, {}])),
aiProviderModelsCache: {}, aiProviderStateCache: {}, window: { adpanelAgentLive: agentLive },
console: { warn() {} },
fetchWithTimeout: async (url) => {
if (inFlight === DISCOVERY_CONCURRENCY) {
return Response.json({ code: "agent_discovery_busy" }, { status: 503 });
}
peak = Math.max(peak, ++inFlight);
await new Promise(setImmediate);
inFlight -= 1;
return Response.json({ ok: true, models: [`${url.split("/").at(-1)}-model`] });
},
});
const models = await Promise.all(providers.map((provider) => fetchModels(provider)));
assert.deepEqual(models.map((entries) => Array.from(entries)), providers.map((provider) => [`${provider}-model`]));
assert.equal(peak, DISCOVERY_CONCURRENCY);
});
test("repeated composer activations do not stop the just-submitted run", () => {
const start = browser.indexOf(" if (aiChatInput) {\n aiChatInput.addEventListener('input'");
const end = browser.indexOf(" syncAiModelSelectorFromNative();", start);
const listeners = {};
const control = { addEventListener: (name, handler) => { listeners[name] = handler; } };
let activations = 0;
vm.runInNewContext(browser.slice(start, end), {
aiChatInput: control, aiChatSend: control, sendAiMessage: () => { activations += 1; },
});
listeners.click({ detail: 1 });
listeners.click({ detail: 2 });
assert.equal(activations, 1);
const enter = { key: "Enter", preventDefault() {} };
listeners.keydown(enter);
listeners.keydown({ ...enter, repeat: true });
assert.equal(activations, 2);
listeners.click({ detail: 0 });
assert.equal(activations, 3);
});
test("a lost 202 body retries the same submission and delivers a pending Stop", async () => {
const paths = [];
const submissions = [];
const requestKey = "c559a2f1-72cf-4afa-babf-295edb610c65";
const run = createRun({ prompt: "Check the server." }, {
requestKey,
fetcher: async (route, options) => {
paths.push(route);
if (route !== "/api/ai/chat") return Response.json({ ok: true, cancelled: true });
submissions.push(JSON.parse(options.body));
if (submissions.length === 1) {
const interrupted = new ReadableStream({ start: (stream) => stream.error(new TypeError("connection closed")) });
return new Response(interrupted, { status: 202 });
}
return Response.json({ chatId: 14, jobId: 42 }, { status: 202 });
},
});
const [accepted, stopped] = await Promise.all([run.accepted, run.cancel()]);
assert.equal(accepted.jobId, 42);
assert.equal(stopped.cancelled, true);
assert.deepEqual(paths, ["/api/ai/chat", "/api/ai/chat", "/api/ai/jobs/42/cancel"]);
assert.deepEqual(submissions, Array(2).fill({ prompt: "Check the server.", requestKey }));
await assert.rejects(run.result(), { name: "AbortError" });
});
test("manually retrying an unchanged unacknowledged submission reuses its job key", async () => {
const keys = [];
const fetcher = async (route, options) => {
assert.equal(route, "/api/ai/chat");
const { chatId, requestKey } = JSON.parse(options.body);
if (chatId === 23) return Response.json({ chatId, jobId: 43 }, { status: 202 });
keys.push(requestKey);
if (keys.length <= 2) throw new TypeError("connection closed after admission");
return Response.json({ chatId: 14, jobId: 42 }, { status: 202 });
};
const submission = { chatId: 14, prompt: "Check the server again." };
await assert.rejects(createRun(submission, { fetcher }).accepted, TypeError);
await createRun({ chatId: 23, prompt: "A separate chat." }, { fetcher }).accepted;
await createRun(submission, { fetcher }).accepted;
assert.ok(keys[0]);
assert.deepEqual(keys, Array(3).fill(keys[0]));
await createRun(submission, { fetcher }).accepted;
assert.notEqual(keys[3], keys[0]);
});
test("reopening a pending chat can stop its existing job without posting another submission", async () => {
const run = resumeRun("42", 14, { fetcher: async (route, options) => {
assert.equal(route, "/api/ai/jobs/42/cancel");
assert.equal(options.method, "POST");
return Response.json({ cancelled: true });
} });
assert.deepEqual(await run.accepted, { jobId: "42", chatId: 14 });
assert.deepEqual(await run.cancel(), { cancelled: true });
await assert.rejects(run.result(), { name: "AbortError" });
});
test("Agent provider schemas advertise the same diagnostic tool allowlist", () => {
const expected = BOT_TOOL_DEFINITIONS.map(({ name }) => name).filter(isBotReadonlyToolName);
assert.deepEqual(BOT_OPENAI_TOOL_DEFINITIONS.map((tool) => tool.function.name), expected);
assert.deepEqual(BOT_GOOGLE_FUNCTION_DECLARATIONS.map((tool) => tool.name), expected);
});
test("Agent setup only advertises providers available to the backend", () => {
const view = fs.readFileSync(path.join(root, "views/bot.ejs"), "utf8");
const nameList = (source, name) => {
const declaration = new RegExp(`const ${name} = (\\{[\\s\\S]*?\\n\\s*\\});`).exec(source)?.[1];
assert.ok(declaration, `Missing ${name}`);
return Object.keys(vm.runInNewContext(`(${declaration})`, { BRAND_NAME: "ADPanel" })).sort();
};
const registered = Object.keys(AI_PROVIDER_CONFIGS).sort();
const configured = nameList(browser, "AI_PROVIDERS");
const advertised = Array.from(view.matchAll(/class="ai-provider-card" data-provider="([^"]+)"/g), (match) => match[1]).sort();
assert.deepEqual(configured, registered);
assert.deepEqual(advertised, registered);
});
test("Agent server resolution prefers the canonical name and never falls back from a missing current server", () => {
const other = { name: "other-server", displayName: "main-server" };
const current = { name: "main-server", displayName: "Main" };
assert.equal(resolveServerFromAccessibleList([other, current], "current server", "main-server").entry, current);
assert.equal(resolveServerFromAccessibleList([other, current], "main-server").entry, current);
assert.equal(resolveServerFromAccessibleList([other], "current server", "main-server").entry, null);
assert.equal(resolveServerFromAccessibleList([other], "current server").entry, other);
});
test("a pending Agent reply is saved to its original chat and leaves the selected view alone", async () => {
const start = browser.indexOf(" async function sendAiMessage(");
const end = browser.indexOf("\n }", start) + 4;
const submissions = [];
const rendered = [];
let finishReply;
let markRequested;
const reply = new Promise((resolve) => { finishReply = resolve; });
const requested = new Promise((resolve) => { markRequested = resolve; });
const state = {
serverAgentHistory, bot: "srv1", hasAgentAccess: () => true,
aiChatLoadToken: 0, aiCurrentChatId: 14,
aiChatInput: { value: "Check status" }, aiAttachedFile: null, aiChatHistory: [],
aiActiveRuns: new Map(), aiChatTranscriptCache: new Map(), aiModelSelect: { value: "selected" },
clearAttachedFile() {}, updateSendButton() {}, saveSelectedAiModelToStorage() {},
decodeAiModelSelection: () => ({ providerId: "openai", modelName: "test-model" }),
isValidChatId: Number.isSafeInteger,
window: { adpanelAgentLive: { createRun: (submission) => {
submissions.push([submission.chatId, submission.prompt, submission.server]);
return { accepted: Promise.resolve({ chatId: 14, jobId: 42 }), result: () => { markRequested(); return reply; }, detach() {} };
} } },
pushLocalChatMessage: (role, content) => rendered.push([role, content]),
createAgentActivityMessage: () => ({ detach() {}, addThinking() {}, fail: markRequested }),
refreshChatsListAfterRun: async () => {},
};
const send = vm.runInNewContext(`(${browser.slice(start, end)})`, state);
const sending = send();
assert.equal(await requested, undefined);
state.aiCurrentChatId = 23;
state.aiChatLoadToken += 1;
finishReply({ content: "Server is running" });
await sending;
assert.deepEqual(submissions, [[14, "Check status", "srv1"]]);
assert.deepEqual(rendered, [["user", "Check status"]]);
assert.equal(state.aiCurrentChatId, 23);
assert.equal(state.aiActiveRuns.size, 0);
});
test("a rejected Agent submission keeps the unsent draft and attachment", async () => {
const start = browser.indexOf(" async function sendAiMessage(");
const end = browser.indexOf("\n }", start) + 4;
const draft = { value: "Look at this log" };
const attachment = { name: "server.log", data: "Fixture log" };
const failures = [];
const state = {
serverAgentHistory, bot: "srv1", hasAgentAccess: () => true,
aiChatLoadToken: 0, aiCurrentChatId: 14,
aiChatInput: draft, aiAttachedFile: attachment, aiChatHistory: [], aiModelSelect: { value: "selected" },
aiActiveRuns: new Map(), updateSendButton() {}, refreshChatsListAfterRun: async () => {},
saveSelectedAiModelToStorage() {},
clearAttachedFile: assert.fail, pushLocalChatMessage: assert.fail,
decodeAiModelSelection: () => ({ providerId: "openai", modelName: "test-model" }),
window: { adpanelAgentLive: { createRun: () => ({
accepted: Promise.reject(new Error("ADPanel Agent is temporarily unavailable.")), detach() {},
}) } },
createAgentActivityMessage: () => ({ fail: (message) => failures.push(message) }),
};
const send = vm.runInNewContext(`(${browser.slice(start, end)})`, state);
await send();
assert.equal(draft.value, "Look at this log");
assert.equal(state.aiAttachedFile, attachment);
assert.deepEqual(failures, ["Error: ADPanel Agent is temporarily unavailable."]);
assert.equal(state.aiActiveRuns.size, 0);
});
test("loading and switching pending chats restores Stop for the selected job", async () => {
const functions = ["loadChatHistory", "switchToChat", "sendAiMessage"].map((name) => {
const start = browser.search(new RegExp(`^ (?:async )?function ${name}\\(`, "m"));
return browser.slice(start, browser.indexOf("\n }", start) + 4);
});
const calls = [];
const reviewBindings = [];
const messages = [{ role: "user", content: "Check status" }];
let complete;
const reply = new Promise((resolve) => { complete = resolve; });
const state = {
serverAgentHistory, bot: "fixture", aiChatMessages: {}, hasAgentAccess: () => true, aiChatLoadToken: 0, aiCurrentChatId: null,
aiChatInput: { value: "Unsent draft" }, aiModelSelect: null, aiAttachedFile: null,
aiActiveRuns: new Map(), aiChatTranscriptCache: new Map(), aiChatsList: [], renderChatHistory() {}, renderChatsList() {},
loadChatsFromDb: async () => { state.aiChatsList = [{ id: 14 }, { id: 23 }]; },
loadChatFromDb: async (id) => {
if (id === 23) assert.equal(reviewBindings.at(-1), null);
return { messages, chat: { active_job_id: id === 14 ? "42" : "43" } };
},
showTypingIndicator() {}, hideTypingIndicator() {},
isChatLoadAborted: () => false, isValidChatId: Number.isSafeInteger, decodeAiModelSelection: () => ({}),
window: { adpanelAgentReview: { bind: (jobId) => { reviewBindings.push(jobId); } }, adpanelAgentLive: { resumeRun: (jobId, chatId) => {
calls.push(["resume", jobId, chatId]);
return { accepted: Promise.resolve({ jobId, chatId }), result: () => reply,
cancel: async () => { calls.push(["cancel", jobId]); return { cancelled: false }; }, detach() {} };
} } },
updateSendButton() {}, createAgentActivityMessage: () => ({ detach() {}, fail: assert.fail }),
reloadVisibleChatFromDb: async (id) => { calls.push(["reload", id]); },
refreshChatsListAfterRun: async () => {},
};
const { load, activate, switchChat } = vm.runInNewContext(`${functions.join("\n")}\n({ load: loadChatHistory, activate: sendAiMessage, switchChat: switchToChat })`, state);
await load();
assert.equal(state.aiActiveRuns.has(14), true);
assert.equal(state.aiChatInput.value, "Unsent draft");
assert.equal(state.aiChatHistory.length, 1);
await switchChat(23);
await activate();
assert.deepEqual(calls, [["resume", "42", 14], ["resume", "43", 23], ["cancel", "43"]]);
const pending = [...state.aiActiveRuns.values()].map((run) => run.promise);
complete({ content: "Synthetic reply" });
await Promise.all(pending);
assert.deepEqual(calls.filter(([op]) => op === "reload"), [["reload", 14], ["reload", 23]]);
assert.equal(state.aiActiveRuns.size, 0);
});
test("Agent markdown preserves link destinations independently of text formatting", () => {
const escapeAt = browser.indexOf(" function escapeHtmlAi(");
const renderAt = browser.indexOf(" function renderAiMarkdown(");
const escape = browser.slice(escapeAt, browser.indexOf("\n }", escapeAt) + 4);
const render = browser.slice(renderAt, browser.indexOf("\n }", renderAt) + 4);
const renderMarkdown = new Function(`${escape}\n${render}\nreturn renderAiMarkdown;`)();
assert.equal(renderMarkdown('[docs](https://example.test/`api`?name="config"&part=1) **Guide**'),
'<a href="https://example.test/`api`?name=&quot;config&quot;&amp;part=1" target="_blank" rel="noopener noreferrer" class="ai-md-link">docs</a> <strong>Guide</strong>');
assert.equal(renderMarkdown('`[docs](https://example.test)`'),
'<code class="ai-inline-code">[docs](https://example.test)</code>');
});
test("Agent startup removes unowned undo data without reading it", () => {
const start = browser.indexOf(" function clearLegacyAiFileBackups(");
const end = browser.indexOf("\n }", start) + 4;
const keys = ["ai-file-backups-server-one", "adpanel-ai-selected-model", "ai-file-backups-server-two"];
const localStorage = {
get length() { return keys.length; },
key: (index) => keys[index],
removeItem: (key) => keys.splice(keys.indexOf(key), 1),
};
new Function("localStorage", `${browser.slice(start, end)}\nclearLegacyAiFileBackups();`)(localStorage);
assert.deepEqual(keys, ["adpanel-ai-selected-model"]);
assert.doesNotMatch(browser, /localStorage\.setItem\([^\n]+JSON\.stringify\(aiFileBackups\)/);
});