"use strict"; const assert = require("node:assert/strict"); const { randomUUID } = require("node:crypto"); const { once } = require("node:events"); const fs = require("node:fs"); const path = require("node:path"); const { test } = require("node:test"); const express = require("express"); const { createAgentFeatureGate } = require("../AgentWorker/feature-http"); const { createAgentSubmissionParser } = require("../AgentWorker/admission"); const { readAgentRunTranscript } = require("../AgentWorker/job-store"); const { AgentRpcError } = require("../AgentWorker/private-rpc"); const { createAgentLiveRouter } = require("../routes/agent-live"); const { ensureServerAgentChatOwnerSchema, ensureServerAgentChatActionSchema, backfillServerAgentChatOwners, createServerAgentChat, deleteAccountServerAgentChats, isValidServerAgentChatCursor, readOwnedServerAgentChat, readServerAgentChatPage } = require("../services/server-agent-chat-ownership"); test("Agent chat creation binds the owner ID across standalone and transactional inserts", async () => { const calls = []; const db = { query: async (...args) => { calls.push(args); return { insertId: 11 }; } }; const connection = { execute: async (...args) => { calls.push(args); return [{ insertId: 12 }]; } }; assert.equal(await createServerAgentChat(db, { id: 4, email: "first@example.test" }, "First"), 11); assert.equal(await createServerAgentChat(db, { id: 4, email: "changed@example.test" }, "Second", connection), 12); assert.match(calls[0][0], /\(created_by, user_email, title\)/); assert.equal(calls[0][0], calls[1][0]); assert.deepEqual(calls.map(([, values]) => values), [ [4, "first@example.test", "First"], [4, "changed@example.test", "Second"], ]); await assert.rejects(createServerAgentChat(db, { email: "first@example.test" }, "Invalid"), TypeError); assert.equal(calls.length, 2); }); test("Agent chat schema migration is idempotent without hiding other DDL errors", async () => { const statements = []; await ensureServerAgentChatOwnerSchema({ query: async (sql) => { statements.push(sql); throw Object.assign(new Error("already exists"), { code: sql.startsWith("ALTER") ? "ER_DUP_FIELDNAME" : "ER_DUP_KEYNAME" }); } }); assert.equal(statements.length, 2); await assert.rejects(ensureServerAgentChatOwnerSchema({ query: async () => { throw new Error("DDL unavailable"); } }), /DDL unavailable/); }); test("Agent chat migration requires one existing job owner and never infers ownership from email", async () => { const statements = []; await backfillServerAgentChatOwners({ query: async (sql) => { statements.push(sql); } }); assert.equal(statements.length, 1); assert.match(statements[0], /FROM ai_agent_jobs GROUP BY chat_id HAVING MIN\(user_id\) = MAX\(user_id\)/); assert.match(statements[0], /JOIN users AS owner ON owner.id = evidence.owner_id/); assert.match(statements[0], /WHERE chat.created_by IS NULL/); assert.doesNotMatch(statements[0], /email/i); }); test("Agent chat details load the latest live review by owner and the action schema is idempotent", async () => { const chat = { review_job_id: "41", review_message_id: "12" }; assert.equal(await readOwnedServerAgentChat({ query: async (sql, params) => { assert.match(sql, /recent\.chat_id = chat\.id AND recent\.user_id = chat\.created_by AND recent\.source = \?/); assert.match(sql, /ORDER BY recent\.id DESC LIMIT 1/); assert.match(sql, /WHERE chat\.id = \? AND chat\.created_by = \?/); assert.deepEqual(params, ["live_chat", "18446744073709551615", 4]); return [chat]; } }, "18446744073709551615", 4, "live_chat"), chat); await ensureServerAgentChatActionSchema({ query: async (sql) => { assert.match(sql, /ALTER TABLE ai_messages ADD COLUMN agent_actions MEDIUMTEXT/); throw Object.assign(new Error("already exists"), { code: "ER_DUP_FIELDNAME" }); } }); await assert.rejects(ensureServerAgentChatActionSchema({ query: async () => { throw new Error("DDL unavailable"); } }), /DDL unavailable/); }); test("account deletion removes owned messages before chats without matching email", async () => { const calls = []; await deleteAccountServerAgentChats({ execute: async (...args) => { calls.push(args); } }, 4); assert.deepEqual(calls, [ ["DELETE FROM ai_messages WHERE chat_id IN (SELECT id FROM ai_chats WHERE created_by = ?)", [4]], ["DELETE FROM ai_chats WHERE created_by = ?", [4]], ]); }); test("Agent history loads only the rows that fit, and continues before the oldest included message", async () => { const calls = []; const messages = [{ id: 8 }, { id: 9 }]; const db = { query: async (sql, params) => { calls.push([sql, params]); return calls.length === 1 ? [ { cursor_id: "9", stored_bytes: 10 * 1024 * 1024 }, { cursor_id: "8", stored_bytes: 1024 }, { cursor_id: "7", stored_bytes: 3 * 1024 * 1024 }, ] : messages; } }; assert.deepEqual(await readServerAgentChatPage(db, 12, "10"), { messages, nextBeforeId: "8" }); assert.match(calls[0][0], /OCTET_LENGTH\(CASE WHEN image_expires_at IS NULL OR image_expires_at > NOW\(3\) THEN image_data END\)/); assert.match(calls[0][0], /OCTET_LENGTH\(agent_actions\)/); assert.match(calls[0][0], /chat_id = \? AND id < CAST\(\? AS UNSIGNED\)\s+ORDER BY id DESC LIMIT 51/); assert.deepEqual(calls[0][1], [12, "10"]); assert.match(calls[1][0], /chat_id = \? AND id IN \(CAST\(\? AS UNSIGNED\), CAST\(\? AS UNSIGNED\)\)\s+ORDER BY id ASC/); assert.match(calls[1][0], /SELECT id, role, content, agent_actions/); assert.deepEqual(calls[1][1], [12, "9", "8"]); }); test("Agent transcript scopes prior action context to its owner, exact server, and account epoch", async () => { const activity = JSON.stringify([ { action: "create_folder", target: "reports", status: "applied", detail: "Not model context" }, { action: "create_file", target: "reports/summary.txt", status: "dismissed", content: "Not model context" }, { action: "console_command", target: "server", status: "applied", command: "Not model context" }, { action: "create_file", target: "../outside", status: "applied" }, ]); const row = { source: "live_chat", chat_id: "12", user_id: 4, server_id: "18446744073709551615", server_name: "fixture", account_epoch: 9, submission_message_id: "32" }; for (const [job, enabled, include] of [[row, true, true], [row, false, false], [{ ...row, account_epoch: null }, true, false], [{ ...row, source: "scheduler_prompt" }, true, false]]) { let calls = 0; const messages = await readAgentRunTranscript({ query: async (sql, params) => { if (++calls === 1) { assert.deepEqual(params, ["12", 4, "32"]); assert.match(sql, /created_by = \? AND message.id <= \?/); return [{ id: "32", bytes: 20 }, { id: "31", bytes: 30 }]; } assert.match(sql, /WHERE chat.id = \? AND chat.created_by = \? AND message.id IN /); if (include) { assert.match(sql, /OCTET_LENGTH\(message.agent_actions\) <= 131072/); assert.match(sql, /review.chat_id = chat.id AND review.user_id = chat.created_by/); assert.match(sql, /review.result_message_id = message.id AND review.source = \? AND review.server_id = CAST\(\? AS UNSIGNED\)/); assert.match(sql, /review.server_name = \? AND review.account_epoch = CAST\(\? AS UNSIGNED\)/); assert.deepEqual(params, ["live_chat", row.server_id, "fixture", 9, "12", 4, "32", "31"]); } else { assert.doesNotMatch(sql, /agent_actions/); assert.deepEqual(params, ["12", 4, "32", "31"]); } return [{ role: "assistant", content: "Earlier reply", ...(include && { file_activity: activity }) }, { role: "user", content: "Continue with the remaining work." }]; } }, job, { includeFileActivity: enabled }); assert.deepEqual(messages[0].fileActions, include ? [ { action: "create_folder", path: "reports", status: "applied" }, { action: "create_file", path: "reports/summary.txt", status: "dismissed" }, ] : undefined); assert.doesNotMatch(JSON.stringify(messages), /file_activity|Not model context/); assert.equal(calls, 2); } }); test("Agent history limits many small messages and uses exact unsigned cursors", async () => { const rows = Array.from({ length: 51 }, (_, index) => ({ cursor_id: String(51 - index), stored_bytes: "10" })); const calls = []; const db = { query: async (sql, params) => { calls.push(params); return calls.length === 1 ? rows : []; } }; assert.equal((await readServerAgentChatPage(db, 12)).nextBeforeId, "2"); assert.equal(calls[1].length, 51); assert.equal(isValidServerAgentChatCursor("18446744073709551615"), true); for (const value of ["18446744073709551616", "0", "-1", "1.5", "1e3", ["1"], null]) { assert.equal(isValidServerAgentChatCursor(value), false); } }); test("the mounted Agent parser rejects OFF, anonymous, and unentitled traffic without parsing its body", async (context) => { const source = fs.readFileSync(path.join(__dirname, "..", "index.js"), "utf8"); const gate = source.indexOf("app.use(createAgentFeatureGate(() => agentFeature.enabled));"); const start = source.indexOf(' if (req.method === "POST" && /^\\/api\\/ai\\/chat', gate); const end = source.indexOf("\n // adpanel:heartbeat-capture-integrated", start); assert.ok(gate >= 0 && start > gate && end > start); const state = { enabled: false, authenticated: false, entitled: false, unavailable: false, ownerId: 4, parsed: 0, admitted: 0, cancels: 0 }; const isAuthenticated = async () => { if (state.authenticated === "error") throw new Error("fixture database error"); return state.authenticated; }; const hasAgentAccess = async () => state.entitled; const pass = (_req, _res, next) => next(); const json = express.json(); const submissionParser = createAgentSubmissionParser({ parser: (req, res, next) => { state.parsed += 1; return json(req, res, next); }, authenticate: isAuthenticated, hasAgentAccess, anonymousLimiter: pass, accountLimiter: pass, }); const dispatch = new Function("isAuthenticated", "hasAgentAccess", "largeBodyPreAuthRateLimiter", "parseAgentSubmission", ` return (req, res, next) => { ${source.slice(start, end)} return next(); }; `)(isAuthenticated, hasAgentAccess, pass, submissionParser); const app = express(); app.use((req, _res, next) => { if (state.authenticated) req.session = { user: "fixture@example.test" }; next(); }); app.use(createAgentFeatureGate(() => state.enabled), dispatch); app.use("/api/ai", createAgentLiveRouter({ isAuthenticated, hasAgentAccess, getLoggedInUser: async () => ({ id: state.ownerId }), statusLimiter: pass, cancelLimiter: pass, ensureAiChatTablesReady: async () => {}, insertAiAgentChatJob: async ({ user }) => { assert.equal(user.id, 4); state.admitted += 1; if (state.unavailable) throw new AgentRpcError(503, "agent_unavailable"); return { jobId: 15, chatId: 8, status: "queued" }; }, saveSelection: async () => {}, db: { query: async (sql, params) => { assert.match(sql, /user_id = \?/); assert.equal(params[0], "15"); if (sql.startsWith("UPDATE")) { assert.equal(params[1], 4); state.cancels += 1; return { affectedRows: 1 }; } return params[1] === 4 ? [{ id: 15, status: "queued", claim_token: null }] : []; } }, })); app.get("/ordinary", (_req, res) => res.sendStatus(204)); app.use((_error, _req, res, _next) => res.sendStatus(500)); const server = app.listen(0, "127.0.0.1"); await once(server, "listening"); context.after(() => new Promise((resolve) => { server.close(resolve); server.closeAllConnections(); })); const request = (route, method = "GET", body) => fetch(`http://127.0.0.1:${server.address().port}${route}`, { method, body, headers: body ? { "content-type": "application/json" } : {}, signal: AbortSignal.timeout(2000), }); const off = await request("/API/AI/Chat/", "POST", "{"); assert.equal(off.status, 503); assert.equal((await off.json()).code, "agent_disabled"); assert.equal((await request("/api/ai/jobs/15")).status, 503); assert.equal((await request("/ordinary")).status, 204); state.enabled = true; assert.equal((await request("/API/AI/Chat/", "POST", "{")).status, 401); state.authenticated = true; assert.equal((await request("/API/AI/Chat/", "POST", "{")).status, 403); assert.equal((await request("/api/ai/chats/5/messages", "POST", "{")).status, 403); state.entitled = true; for (const route of ["/api/ai/chats/5/messages", "/API/AI/CHATS/5stale/MESSAGES/"]) { const stale = await request(route, "POST", "{"); assert.equal(stale.status, 409); assert.equal((await stale.json()).code, "agent_client_refresh_required"); } assert.equal(state.parsed, 0); assert.equal((await request("/api/ai/chat", "POST", "{}")).status, 409); assert.equal(state.admitted, 0); const prompt = JSON.stringify({ requestKey: randomUUID(), server: "fixture", prompt: "Review", provider: "openai", model: "fixture" }); state.unavailable = true; const unavailable = await request("/api/ai/chat", "POST", prompt); assert.equal(unavailable.status, 503); assert.equal(unavailable.headers.get("retry-after"), "3"); state.unavailable = false; assert.equal((await request("/API/AI/Chat/", "POST", prompt)).status, 202); assert.equal(state.admitted, 2); assert.equal((await request("/api/ai/jobs/not-an-id")).status, 400); state.authenticated = "error"; assert.equal((await request("/api/ai/jobs/15")).status, 500); assert.equal((await request("/api/ai/chat", "POST", prompt)).status, 500); state.authenticated = true; state.ownerId = 5; assert.equal((await request("/api/ai/jobs/15")).status, 404); assert.equal((await request("/api/ai/jobs/15/cancel", "POST")).status, 404); state.ownerId = 4; assert.equal((await request("/api/ai/jobs/15")).status, 200); assert.deepEqual(await (await request("/api/ai/jobs/15/cancel", "POST")).json(), { ok: true, cancelled: true }); assert.equal(state.cancels, 1); }); test("Agent chat routes and queued creation use the authenticated account ID", () => { const source = fs.readFileSync(path.join(__dirname, "..", "index.js"), "utf8"); const routes = source.slice(source.indexOf('app.get("/api/ai/chats"'), source.indexOf("function derivePlannerTitleFromPrompt")); assert.equal((routes.match(/created_by = \?/g) || []).length, 3); assert.equal((routes.match(/req\.currentUser\.id/g) || []).length, 4); assert.equal((routes.match(/createServerAgentChat\(db, req\.currentUser, chatTitle\)/g) || []).length, 2); assert.doesNotMatch(routes, /user_email|req\.session\.user/); assert.doesNotMatch(source, /app\.post\("\/api\/ai\/chats\/:id\/messages"/); assert.match(routes, /readOwnedServerAgentChat\(db, chatId, req\.currentUser\.id, LIVE_SOURCE\)[\s\S]*?if \(!chat\) return res\.status\(404\)[\s\S]*?readServerAgentChatPage\(db, chatId, beforeId\)/); const admission = fs.readFileSync(require.resolve("../AgentWorker/admission"), "utf8"); assert.match(admission, /SELECT id FROM ai_chats WHERE id = \? AND created_by = \? FOR UPDATE/); assert.match(admission, /await createServerAgentChat\(db, user, title, tx\)/); const dbSource = fs.readFileSync(path.join(__dirname, "..", "db.js"), "utf8"); assert.match(dbSource, /await conn\.query\(stmt\);[\s\S]*?await ensureServerAgentChatOwnerSchema\(\{ query \}\);\s*await backfillServerAgentChatOwners\(\{ query \}\);/); assert.match(source, /await db\.ensureSchema\(\);[\s\S]*?await pruneTerminalAiAgentJobs\(\)/); });