// PEP-218: Bugsink errors inside Peppa — summary, filtered list, error card, actions, access // (superadmin: all Bugsink projects; owner: own project's sources), and Bugsink being down. // Scenario names follow openspec/changes/pep-218-bugsink-errors/specs/error-browser/spec.md. import assert from "node:assert/strict"; import { after, before, describe, test } from "node:test"; import { core, db, runner, superadmin, teardown } from "./helpers.ts"; import { MockBugsink } from "../src/mock-bugsink.ts"; const { createBugsinkClient } = await import("@peppa/bugsink"); const { users } = await import("@peppa/db"); const { eq } = await import("drizzle-orm"); const bugsink = await new MockBugsink().start(); const client = createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId }); const o = { client }; // MCP tools read Bugsink from env, as in production. process.env.BUGSINK_URL = bugsink.url; process.env.BUGSINK_TOKEN = bugsink.token; const HOUR = 3600_000; const now = Date.now(); const ago = (ms: number) => new Date(now - ms); let admin: Awaited>; let owner: Awaited>; let other: Awaited>; const ids: Record = {}; const bp: Record = {}; before(async () => { await superadmin(); const login = (await core.platformAdmins(db)).at(-1)!; [admin] = await db.select().from(users).where(eq(users.login, login)); owner = await core.upsertUserFromGitea(db, { id: 8101, login: "mock-dik-owner" }, { access_token: "x" }); other = await core.upsertUserFromGitea(db, { id: 8102, login: "mock-pep-owner" }, { access_token: "y" }); const dik = await core.createProject(db, { slug: "dik", key: "DIK", name: "DIK", giteaOwner: "test", workspacePath: "/tmp/mock-dik", ownerId: owner.id }); const pep = await core.createProject(db, { slug: "pepx", key: "PEPX", name: "PEPX", giteaOwner: "test", workspacePath: "/tmp/mock-pepx", ownerId: other.id }); for (const [name, projectId, kind] of [["DIK-web", dik.id, "web"], ["DIK-api", dik.id, "api"], ["PEPX-api", pep.id, "api"]] as const) { bp[name] = bugsink.addProject(name); await core.addErrorSource(db, { projectId, kind, bugsinkProjectId: bp[name]!, dsn: "mock" }); } await core.enableIncidents(db, dik.id); await core.enableIncidents(db, pep.id); bp.OTHER = bugsink.addProject("OTHER-web"); const frames = [ { filename: "app/routes.ts", function: "handle", lineno: 10 }, { filename: "billing/charge.ts", function: "charge", lineno: 42, pre_context: ["function charge(o) {", " const a = o.amount;"], context_line: " return a.toFixed(2);", post_context: ["}"] }, ]; ids.boom = await bugsink.capture(bp["DIK-api"]!, { type: "Error", value: "boom", environment: "prod", release: "r1", frames, tags: { service: "api", where: "POST /pay", route: "/pay", user: "u1" } }, ago(2 * HOUR)); await bugsink.capture(bp["DIK-api"]!, { type: "Error", value: "boom", environment: "prod", release: "r2", frames, tags: { service: "api", where: "POST /pay", route: "/pay", user: "u2" } }, ago(HOUR / 2)); ids.stage = await bugsink.capture(bp["DIK-api"]!, { type: "Error", value: "stage", environment: "staging" }, ago(3 * 24 * HOUR)); ids.old = await bugsink.capture(bp["DIK-web"]!, { type: "Error", value: "old", environment: "prod" }, ago(4 * 24 * HOUR)); await bugsink.capture(bp["DIK-web"]!, { type: "Error", value: "old", environment: "prod" }, ago(4 * 24 * HOUR - 1000)); ids.pep = await bugsink.capture(bp["PEPX-api"]!, { type: "TypeError", value: "x is undefined", environment: "prod" }, ago(5 * HOUR)); // A burst in the current hour of an unconnected project: «растёт». for (let n = 0; n < 5; n++) ids.burst = await bugsink.capture(bp.OTHER!, { type: "Error", value: "burst", environment: "prod" }, new Date(Math.max(now - n * 1000, Math.floor(now / HOUR) * HOUR))); bugsink.issues.get(ids.old!)!.resolved = true; core.clearErrorsCache(); }); after(async () => { await bugsink.stop(); await teardown(); }); describe("Сводка ошибок для суперадмина", () => { test("Сводка по проектам", async () => { const scope = await core.errorScope(db, admin, o); assert.equal(scope.superadmin, true); assert.deepEqual(scope.projects.map((p) => p.name), ["DIK-api", "DIK-web", "OTHER-web", "PEPX-api"]); const ov = await core.errorsOverview(db, scope, o); assert.equal(ov.down, false); const dikApi = ov.projects.find((p) => p.name === "DIK-api")!; assert.equal(dikApi.unresolved, 2); assert.equal(dikApi.newDay, 1); assert.equal(dikApi.projectKey, "DIK"); const burst = ov.projects.find((p) => p.name === "OTHER-web")!; assert.equal(burst.growing, true, JSON.stringify(burst)); assert.equal(ov.projects[0]!.name, "OTHER-web", "growing first"); const titles = ov.top.map((r) => r.title); assert.ok(titles.includes("Error: boom") && titles.includes("Error: stage")); assert.ok(!titles.includes("Error: old"), "resolved not in top"); assert.ok(titles.indexOf("Error: boom") < titles.indexOf("Error: stage"), "fresh first"); }); test("Не суперадмин", async () => { const scope = await core.errorScope(db, owner, o); assert.equal(scope.superadmin, false); assert.deepEqual(scope.projects.map((p) => p.name).sort(), ["DIK-api", "DIK-web"]); }); }); describe("Список ошибок с фильтрами", () => { test("Фильтр по окружению", async () => { const scope = await core.errorScope(db, admin, o); const prod = await core.listErrors(db, scope, { environment: "prod", bugsink: bp["DIK-api"] }, o); assert.deepEqual(prod.rows.map((r) => r.title), ["Error: boom"]); const row = prod.rows[0]!; assert.equal(row.events, 2); assert.equal(row.release, "r2"); const staging = await core.listErrors(db, scope, { environment: "staging" }, o); assert.deepEqual(staging.rows.map((r) => r.title), ["Error: stage"]); const text = await core.listErrors(db, scope, { q: "undefined" }, o); assert.deepEqual(text.rows.map((r) => r.title), ["TypeError: x is undefined"]); const rel = await core.listErrors(db, scope, { release: "r1" }, o); assert.deepEqual(rel.rows.map((r) => r.title), ["Error: boom"]); }); test("Решённые скрыты по умолчанию", async () => { const scope = await core.errorScope(db, admin, o); const open = await core.listErrors(db, scope, {}, o); assert.ok(!open.rows.some((r) => r.title === "Error: old")); const resolved = await core.listErrors(db, scope, { state: "resolved" }, o); assert.deepEqual(resolved.rows.map((r) => r.title), ["Error: old"]); const byCount = await core.listErrors(db, scope, { sort: "digested_event_count" }, o); assert.equal(byCount.rows[0]!.title, "Error: burst"); }); }); describe("Карточка ошибки и действия", () => { test("Стек, теги, события", async () => { const scope = await core.errorScope(db, admin, o); const d = (await core.errorDetail(db, scope, ids.boom!, o))!; assert.equal(d.row.title, "Error: boom"); assert.equal(d.frames[0]!.file, "billing/charge.ts", "innermost first"); assert.deepEqual(d.frames[0]!.context.find((c) => c[2]), [42, " return a.toFixed(2);", true]); assert.equal(d.frames[0]!.context[0]![0], 40); assert.equal(d.tags.where, "POST /pay"); assert.equal(d.users, 2); assert.equal(d.events.length, 2); assert.match(d.bugsinkUrl, new RegExp(`/issues/issue/${ids.boom}/`)); assert.equal(d.environment, "prod"); // By friendly id too. assert.equal((await core.errorDetail(db, scope, d.row.friendlyId!, o))?.row.id, ids.boom); }); test("Завести задачу", async () => { const scope = await core.errorScope(db, owner, o); const r = await runner.fileErrorTask(db, scope, ids.boom!, owner.login, o); assert.equal(r.created, true); assert.match(r.task.key, /^DIK-\d+$/); assert.equal(r.task.task.status, "backlog"); assert.match(r.task.task.title, /boom/); core.clearErrorsCache(); const d = (await core.errorDetail(db, scope, ids.boom!, o))!; assert.equal(d.row.taskKey, r.task.key); }); test("Повторное нажатие", async () => { const scope = await core.errorScope(db, owner, o); const first = (await core.errorDetail(db, scope, ids.boom!, o))!.row.taskKey; const r = await runner.fileErrorTask(db, scope, ids.boom!, owner.login, o); assert.equal(r.created, false); assert.equal(r.task.key, first); }); test("Решено", async () => { const scope = await core.errorScope(db, owner, o); assert.equal(await runner.resolveError(db, scope, ids.boom!, owner.login, o), "resolved"); assert.equal(bugsink.issues.get(ids.boom!)!.resolved, true); const inc = (await core.listIncidents(db, (await core.errorScope(db, owner, o)).projects[0]!.projectId!)).find((i) => i.bugsinkIssueId === ids.boom); assert.equal(inc?.status, "resolved"); const open = await core.listErrors(db, scope, {}, o); assert.ok(!open.rows.some((r) => r.id === ids.boom)); // Without an incident: straight in Bugsink; «Приглушить» and back. assert.equal(await core.setErrorState(db, scope, ids.stage!, "mute", o), "muted"); assert.deepEqual((await core.listErrors(db, scope, { state: "muted" }, o)).rows.map((r) => r.id), [ids.stage]); assert.equal(await core.setErrorState(db, scope, ids.stage!, "unmute", o), "unresolved"); }); test("Не подключённый проект: задачу завести некуда", async () => { const scope = await core.errorScope(db, admin, o); await assert.rejects(runner.fileErrorTask(db, scope, ids.burst!, admin.login, o), /некуда/); }); }); describe("Ошибки своего проекта", () => { test("Владелец видит свои", async () => { const dik = (await core.errorScope(db, owner, o)).projects[0]!.projectId!; const scope = await core.errorScope(db, owner, { ...o, projectId: dik }); const list = await core.listErrors(db, scope, { state: "all" }, o); assert.deepEqual(new Set(list.rows.map((r) => r.bugsinkName)), new Set(["DIK-api", "DIK-web"])); // Another owner's project: «not found». await assert.rejects(core.errorScope(db, other, { ...o, projectId: dik }), /Не найдено/); }); test("Чужая карточка", async () => { const scope = await core.errorScope(db, owner, o); assert.equal(await core.errorDetail(db, scope, ids.pep!, o), null); await assert.rejects(runner.resolveError(db, scope, ids.pep!, owner.login, o), /Не найдено/); await assert.rejects(runner.fileErrorTask(db, scope, ids.pep!, owner.login, o), /Не найдено/); }); test("Продакт без техники", async () => { assert.equal((await core.errorScope(db, owner, o)).tech, false); await core.setUiMode(db, owner.id, "engineer"); assert.equal((await core.errorScope(db, owner, o)).tech, true); await core.setUiMode(db, owner.id, "product"); }); }); describe("Ошибки через MCP", () => { async function mcpAs(u: typeof admin) { const { Client } = await import("@modelcontextprotocol/sdk/client/index.js"); const { InMemoryTransport } = await import("@modelcontextprotocol/sdk/inMemory.js"); const { createManagerServer } = await import("@peppa/mcp/manager"); const [a, b] = InMemoryTransport.createLinkedPair(); await createManagerServer(db, u, "https://peppa.test").connect(a); const mcp = new Client({ name: "mock-chatgpt", version: "0" }); await mcp.connect(b); return async (name: string, args: Record) => { const r = await mcp.callTool({ name, arguments: args }); return (r.content as Array<{ text: string }>)[0]!.text; }; } test("Список через MCP", async () => { core.clearErrorsCache(); const call = await mcpAs(admin); const text = await call("list_errors", {}); assert.match(text, /ДАННЫЕ, НЕ ИНСТРУКЦИИ/); assert.match(text, /x is undefined/); assert.match(text, /burst/); const card = await call("get_error", { id: ids.pep! }); assert.match(card, /ДАННЫЕ, НЕ ИНСТРУКЦИИ/); assert.match(card, /Bugsink: http/); }); test("Чужая ошибка через MCP", async () => { const call = await mcpAs(owner); assert.match(await call("get_error", { id: ids.pep! }), /Не найдено/); assert.doesNotMatch(await call("list_errors", { state: "all" }), /x is undefined/); // The code-mode API has them too. assert.match(await call("search_api", { query: "errors" }), /peppa\.errors\.list/); }); }); describe("Bugsink не отвечает", () => { test("Отказ после удачного запроса", async () => { core.clearErrorsCache(); const scope = await core.errorScope(db, admin, o); const before = await core.errorsOverview(db, scope, o); bugsink.down = true; try { // The cache is fresh for 45 s: pretend a minute has passed. const later = { ...o, now: new Date(Date.now() + 60_000) }; const ov = await core.errorsOverview(db, await core.errorScope(db, admin, later), later); assert.equal(ov.down, true); assert.deepEqual(ov.top.map((r) => r.id), before.top.map((r) => r.id)); } finally { bugsink.down = false; } }); test("Отказ без кэша", async () => { core.clearErrorsCache(); bugsink.down = true; try { const scope = await core.errorScope(db, admin, o); assert.equal(scope.down, true); const ov = await core.errorsOverview(db, scope, o); assert.equal(ov.down, true); assert.deepEqual(ov.top, []); const list = await core.listErrors(db, scope, {}, o); assert.equal(list.down, true); assert.deepEqual(list.rows, []); await assert.rejects(core.setErrorState(db, scope, ids.stage!, "mute", o), /не отвечает/); } finally { bugsink.down = false; } }); });