197 lines
12 KiB
TypeScript
197 lines
12 KiB
TypeScript
// PEP-159: files in the analyst chat, in story comments and in a new story — type by content,
|
||
// size, access, the analyst and the story's agent seeing them.
|
||
import assert from "node:assert/strict";
|
||
import { deflateRawSync } from "node:zlib";
|
||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||
import { tmpdir } from "node:os";
|
||
import { join, resolve } from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { core, db, project as mockProject, runner, teardown, waitFor } from "./helpers.ts";
|
||
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||
const TMP = mkdtempSync(join(tmpdir(), "peppa-attach-"));
|
||
const scenario = join(TMP, "scenario.json");
|
||
const calls = () => readFileSync(`${scenario}.log.jsonl`, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { role: string; prompt: string; files?: string[] });
|
||
const { formatTask } = await import("../../mcp/src/format.ts");
|
||
|
||
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(64)]);
|
||
const PDF = Buffer.from("%PDF-1.4\n1 0 obj\n<<>>\nendobj\n%%EOF\n");
|
||
const TXT = Buffer.from("Требования заказчика:\n- кнопка «Купить» зелёная\n");
|
||
|
||
/** A minimal ZIP (central directory with the given entry names) — enough for the type check. */
|
||
function zip(names: string[]): Buffer {
|
||
const locals: Buffer[] = [];
|
||
const centrals: Buffer[] = [];
|
||
let offset = 0;
|
||
for (const n of names) {
|
||
const name = Buffer.from(n);
|
||
const data = deflateRawSync(Buffer.from("x"));
|
||
const lh = Buffer.alloc(30);
|
||
lh.writeUInt32LE(0x04034b50, 0);
|
||
lh.writeUInt16LE(8, 8);
|
||
lh.writeUInt32LE(data.length, 18);
|
||
lh.writeUInt32LE(1, 22);
|
||
lh.writeUInt16LE(name.length, 26);
|
||
const local = Buffer.concat([lh, name, data]);
|
||
const ch = Buffer.alloc(46);
|
||
ch.writeUInt32LE(0x02014b50, 0);
|
||
ch.writeUInt16LE(8, 10);
|
||
ch.writeUInt32LE(data.length, 20);
|
||
ch.writeUInt32LE(1, 24);
|
||
ch.writeUInt16LE(name.length, 28);
|
||
ch.writeUInt32LE(offset, 42);
|
||
centrals.push(Buffer.concat([ch, name]));
|
||
locals.push(local);
|
||
offset += local.length;
|
||
}
|
||
const cd = Buffer.concat(centrals);
|
||
const end = Buffer.alloc(22);
|
||
end.writeUInt32LE(0x06054b50, 0);
|
||
end.writeUInt16LE(names.length, 8);
|
||
end.writeUInt16LE(names.length, 10);
|
||
end.writeUInt32LE(cd.length, 12);
|
||
end.writeUInt32LE(offset, 16);
|
||
return Buffer.concat([...locals, cd, end]);
|
||
}
|
||
const DOCX = zip(["[Content_Types].xml", "word/document.xml"]);
|
||
|
||
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let pm: User;
|
||
let stranger: User;
|
||
let proj: Awaited<ReturnType<typeof core.createProject>>;
|
||
let chat: Awaited<ReturnType<typeof core.ensureProjectChat>>;
|
||
const upload = (name: string, data: Uint8Array, user: User = pm, projectId = proj.id) => core.saveAttachment(db, user, { projectId, name, data });
|
||
|
||
before(async () => {
|
||
process.env.PEPPA_INTAKE_BIN = join(ROOT, "packages/testkit/bin/mock-intake");
|
||
process.env.MOCK_INTAKE_SCENARIO = scenario;
|
||
writeFileSync(scenario, "{}");
|
||
pm = await core.upsertUserFromGitea(db, { id: 1591, login: "asel" }, { access_token: "x" });
|
||
stranger = await core.upsertUserFromGitea(db, { id: 1592, login: "outsider" }, { access_token: "x" });
|
||
const ws = join(TMP, "ws");
|
||
mkdirSync(join(ws, ".peppa"), { recursive: true });
|
||
proj = await core.createProject(db, { slug: "mock-attach", key: "ATT", name: "Вложения", giteaOwner: "x", workspacePath: ws, ownerId: pm.id });
|
||
chat = await core.ensureProjectChat(db, proj.id);
|
||
});
|
||
after(teardown);
|
||
|
||
describe("PEP-159: type by content", () => {
|
||
test("Scenario: картинки, PDF, текст и документы Office принимаются по содержимому", async () => {
|
||
assert.deepEqual(core.sniffAttachment(PNG, "x.bin"), { mime: "image/png", ext: "png", kind: "image" }, "the name does not matter for a picture");
|
||
assert.equal(core.sniffAttachment(PDF, "тз").kind, "pdf");
|
||
assert.equal(core.sniffAttachment(TXT, "тз.txt").kind, "text");
|
||
assert.equal(core.sniffAttachment(Buffer.from("a,b\n1,2\n"), "t.csv").mime, "text/csv");
|
||
assert.equal(core.sniffAttachment(DOCX, "тз.docx").ext, "docx");
|
||
assert.equal(core.sniffAttachment(zip(["[Content_Types].xml", "xl/workbook.xml"]), "t.xlsx").ext, "xlsx");
|
||
assert.equal(core.sniffAttachment(zip(["[Content_Types].xml", "ppt/presentation.xml"]), "t.pptx").ext, "pptx");
|
||
});
|
||
|
||
test("Scenario: SVG, HTML, скрипт, архив и исполняемый файл отклоняются с причиной", async () => {
|
||
const bad: Array<[string, Uint8Array]> = [
|
||
["logo.svg", Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>')],
|
||
["page.html", Buffer.from("<!doctype html><script>alert(1)</script>")],
|
||
["fake.txt", Buffer.from("<html><body onload=alert(1)>")],
|
||
["run.sh", Buffer.from("#!/bin/sh\nrm -rf /\n")],
|
||
["fake.txt", Buffer.from("#!/bin/sh\nrm -rf /\n")],
|
||
["a.zip", zip(["a.txt"])],
|
||
["app.exe", Buffer.concat([Buffer.from("MZ"), Buffer.alloc(64, 1)])],
|
||
["bin.txt", Buffer.from([0x7f, 0x45, 0x4c, 0x46, 0, 0, 0])],
|
||
["notes.json", Buffer.from("{не json")],
|
||
];
|
||
for (const [name, data] of bad) assert.throws(() => core.sniffAttachment(data, name), /не принят/, name);
|
||
await assert.rejects(upload("logo.svg", bad[0]![1]), /не принят.*картинку.*PDF/s);
|
||
assert.equal((await db.select().from((await import("@peppa/db")).attachments)).length, 0, "nothing saved");
|
||
});
|
||
|
||
test("Scenario: файл больше 20 МБ — понятная ошибка", async () => {
|
||
await assert.rejects(upload("big.png", Buffer.concat([PNG, Buffer.alloc(20 * 1024 * 1024)])), /больше 20 МБ/);
|
||
});
|
||
});
|
||
|
||
describe("PEP-159: access", () => {
|
||
test("Scenario: посторонний не открывает файл чужого проекта", async () => {
|
||
const a = await upload("макет.png", PNG);
|
||
const mine = await core.attachmentForUser(db, pm, a.id);
|
||
assert.ok(mine && existsSync(mine.path) && mine.path.includes(`/files/${proj.id}/${a.id}/`), "stored under files/<project>/<id>/");
|
||
assert.equal(await core.attachmentForUser(db, stranger, a.id), null, "outsider: not found");
|
||
await assert.rejects(upload("x.png", PNG, stranger), /Не найдено/, "and cannot upload into the project either");
|
||
});
|
||
|
||
test("Scenario: чужой файл нельзя привязать к своему сообщению", async () => {
|
||
const a = await upload("секрет.png", PNG);
|
||
await assert.rejects(core.linkAttachments(db, stranger, proj.id, [a.id], { taskId: 1 }), /Файл не найден/);
|
||
await assert.rejects(core.linkAttachments(db, pm, proj.id + 999, [a.id], { taskId: 1 }), /Файл не найден/, "nor into another project");
|
||
});
|
||
});
|
||
|
||
describe("PEP-159: chat with the analyst", () => {
|
||
test("Scenario: приложенные PDF, картинка и текст доходят до аналитика", async () => {
|
||
const files = [await upload("макет.png", PNG), await upload("тз.pdf", PDF), await upload("требования.txt", TXT), await upload("тз.docx", DOCX)];
|
||
const { message } = await runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text: "Посмотрите файлы", via: "web", attachmentIds: files.map((f) => f.id) });
|
||
const shown = (await core.attachmentsByMessage(db, [message.id])).get(message.id)!;
|
||
assert.deepEqual(shown.map((f) => [f.name, f.kind]), [["макет.png", "image"], ["тз.pdf", "pdf"], ["требования.txt", "text"], ["тз.docx", "office"]]);
|
||
await runner.analystChatTick(db, { wait: true });
|
||
const c = calls().filter((x) => x.role === "chat").at(-1)!;
|
||
assert.deepEqual(c.files!.filter((f) => f.startsWith("file-")).sort(), [`file-${files[0]!.id}.png`, `file-${files[1]!.id}.pdf`], "image and PDF are files in the call's directory");
|
||
assert.match(c.prompt, /«макет.png» \(\d+ B\) — картинка, файл file-\d+\.png/);
|
||
assert.match(c.prompt, /«требования.txt»[^\n]* — текстовый файл:\n---\nТребования заказчика:\n- кнопка «Купить» зелёная/, "text files go in as content");
|
||
assert.match(c.prompt, /«тз.docx»[^\n]* документ Office/, "office files by name and type");
|
||
});
|
||
|
||
test("Scenario: сообщение только с файлом получает подпись из имён", async () => {
|
||
const f = await upload("логотип.png", PNG);
|
||
const { message } = await runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text: "", via: "web", attachmentIds: [f.id] });
|
||
assert.equal(message.text, "📎 логотип.png");
|
||
await assert.rejects(runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text: "", via: "web" }), /Пустое сообщение/);
|
||
});
|
||
|
||
test("Scenario: больше пяти файлов не принимается", () => {
|
||
assert.throws(() => core.parseAttachmentIds([1, 2, 3, 4, 5, 6]), /не больше 5/);
|
||
});
|
||
});
|
||
|
||
describe("PEP-159: story comment and the story's agent", () => {
|
||
test("Scenario: файл комментария к стори в бэклоге уходит аналитику", async () => {
|
||
const ref = await core.createTask(db, { projectId: proj.id, title: "Корзина", description: "Покупатель складывает товары в корзину" });
|
||
const f = await upload("скриншот.png", PNG);
|
||
const c = await core.addStoryComment(db, ref, pm, "Вот как должно выглядеть");
|
||
await core.linkAttachments(db, pm, proj.id, [f.id], { taskId: ref.task.id, eventId: c.id });
|
||
await runner.storyRefineTick(db, { wait: true });
|
||
const call = calls().filter((x) => x.role === "refine").at(-1)!;
|
||
assert.ok(call.files!.includes(`file-${f.id}.png`));
|
||
assert.match(call.prompt, /«скриншот.png»/);
|
||
assert.equal((await core.attachmentsByEvent(db, [c.id])).get(c.id)![0]!.name, "скриншот.png", "shown under the comment");
|
||
});
|
||
|
||
test("Scenario: агент находит файлы в .peppa/attachments/ и в get_task", async () => {
|
||
const p = await mockProject({ turns: [[{ mcp: "get_task", args: { task: "1" } }, { say: "ok" }]] });
|
||
const pr = await core.getProject(db, p.key);
|
||
const ref = await core.resolveTask(db, p.taskKey);
|
||
const a = await core.saveAttachment(db, { id: pr.ownerId! }, { projectId: pr.id, name: "ТЗ клиента.pdf", data: PDF });
|
||
const own = await core.saveAttachment(db, { id: pr.ownerId! }, { projectId: pr.id, name: "лого.png", data: PNG });
|
||
const c = await core.addStoryComment(db, ref, { id: pr.ownerId!, login: "asel" }, "Вот ТЗ от клиента");
|
||
await core.linkAttachments(db, { id: pr.ownerId! }, pr.id, [a.id], { taskId: ref.task.id, eventId: c.id });
|
||
await core.linkAttachments(db, { id: pr.ownerId! }, pr.id, [own.id], { taskId: ref.task.id });
|
||
const sid = await p.start();
|
||
const dir = join(p.dir, ".peppa/attachments");
|
||
await waitFor("files copied", async () => existsSync(dir) && readdirSync(dir).length >= 3);
|
||
assert.deepEqual(readdirSync(dir).sort(), [".gitignore", `${a.id}-ТЗ_клиента.pdf`, `${own.id}-лого.png`].sort());
|
||
assert.equal(readFileSync(join(dir, ".gitignore"), "utf8"), "*\n", "never committed");
|
||
const text = formatTask(await core.getTaskDetails(db, ref));
|
||
assert.match(text, new RegExp(`## Приложенные файлы\\n- \`.peppa/attachments/${a.id}-ТЗ_клиента.pdf\` — «ТЗ клиента.pdf» \\(application/pdf, \\d+ B\\), приложил asel: Вот ТЗ от клиента`));
|
||
assert.match(text, /`.peppa\/attachments\/\d+-лого.png` — «лого.png»/);
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
|
||
test("Scenario: неотправленные файлы старше суток удаляются", async () => {
|
||
const f = await upload("забытый.png", PNG);
|
||
const found = (await core.attachmentForUser(db, pm, f.id))!;
|
||
assert.equal(await core.pruneAttachments(db, new Date()), 0, "fresh ones stay");
|
||
assert.ok(await core.pruneAttachments(db, new Date(Date.now() + 25 * 3600_000)) >= 1);
|
||
assert.equal(existsSync(found.path), false);
|
||
assert.equal(await core.attachmentForUser(db, pm, f.id), null);
|
||
});
|
||
});
|