Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Add webhook message history and session links (#1196)

Joshua Francef617e01d9994
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index c994d33f4..f0049ebb8 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -2375,6 +2375,18 @@ const apiRoutes: readonly WebRoute[] = [
return relay(res, await coreFetch("GET", `/v1/webhooks?viewer=${encodeURIComponent(user)}`));
},
},
+ {
+ method: "GET",
+ path: "/api/webhooks/:id/events",
+ handle: async ({ res, user, params }) =>
+ relay(
+ res,
+ await coreFetch(
+ "GET",
+ `/v1/webhooks/${encodeURIComponent(params.id!)}/events?viewer=${encodeURIComponent(user)}`,
+ ),
+ ),
+ },
{
method: "POST",
path: "/api/loops",
diff --git a/plugins/web-ui/src/webhooks.ts b/plugins/web-ui/src/webhooks.ts
index aecafe30b..1607f5799 100644
--- a/plugins/web-ui/src/webhooks.ts
+++ b/plugins/web-ui/src/webhooks.ts
@@ -211,6 +211,7 @@ function copyRow(text: string) {
function openWebhook(w: WebhookView, opts: { push?: boolean } = {}): void {
if (!appState.mainEl) return;
syncWebhookUrl(w.id, opts.push);
+ const eventsHost = document.createElement("section");
const notice = webhooksNotice || webhooksNoticeSticky;
webhooksNotice = "";
webhooksNoticeSticky = "";
@@ -282,6 +283,7 @@ function openWebhook(w: WebhookView, opts: { push?: boolean } = {}): void {
</div>`
: ""
}
+ ${eventsHost}
<div class="actions">
${
w.enabled
@@ -294,6 +296,62 @@ function openWebhook(w: WebhookView, opts: { push?: boolean } = {}): void {
host,
);
appState.mainEl.replaceChildren(host);
+ void loadWebhookEvents(w.id, eventsHost);
+}
+
+interface WebhookEventView {
+ receivedAt: number;
+ payload: string;
+ sessionId?: string;
+}
+
+async function loadWebhookEvents(id: string, host: HTMLElement): Promise<void> {
+ render(
+ html`<h3>Message history</h3>
+ <p class="hint" role="status">Loading messages…</p>`,
+ host,
+ );
+ try {
+ const { events } = await api<{ events: WebhookEventView[] }>(`/api/webhooks/${encodeURIComponent(id)}/events`);
+ if (!host.isConnected) return;
+ render(
+ html`
+ <h3>Message history</h3>
+ <p class="hint">
+ Latest 50 accepted events. Payloads show what was passed to the agent, capped at 16,000 characters. Earlier
+ events are not backfilled.
+ </p>
+ ${
+ events.length
+ ? events.map(
+ (event) => html`
+ <details class="code-card">
+ <summary class="tool-payload-label">
+ <time datetime=${new Date(event.receivedAt).toISOString()}
+ >${new Date(event.receivedAt).toLocaleString()}</time
+ >
+ </summary>
+ <pre class="tool-payload-body">${event.payload}</pre>
+ <div class="code-card-foot">
+ ${event.sessionId ? html`<a class="btn" href=${deepLinkPath(UI_BASE, "chats", event.sessionId)}>Open session</a>` : html`<span class="hint">No session available.</span>`}
+ </div>
+ </details>
+ `,
+ )
+ : html`<p class="hint">No messages recorded yet.</p>`
+ }
+ `,
+ host,
+ );
+ } catch (error) {
+ if (!host.isConnected) return;
+ render(
+ html`<h3>Message history</h3>
+ <p role="alert">${errMessage(error, "Couldn't load messages.")}</p>
+ <button class="btn" @click=${() => void loadWebhookEvents(id, host)}>Retry</button>`,
+ host,
+ );
+ }
}
async function setWebhookEnabled(id: string, enabled: boolean): Promise<void> {
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index 6e9dcc3ae..c180224f7 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -495,6 +495,7 @@ const FAMILIES: AgentApiFamily[] = [
{
match: (m, p) =>
(p === "/v1/webhooks" && (m === "POST" || m === "GET")) ||
+ (m === "GET" && /^\/v1\/webhooks\/[^/]+\/events$/.test(p)) ||
(m === "POST" && /^\/v1\/webhooks\/[^/]+\/(disable|enable)$/.test(p)),
when: () => false,
routes: [
@@ -504,6 +505,7 @@ const FAMILIES: AgentApiFamily[] = [
summary: "register an inbound webhook that runs a prompt when an external system calls it (secret shown once)",
},
{ method: "GET", path: "/v1/webhooks", summary: "list your webhooks" },
+ { method: "GET", path: "/v1/webhooks/:id/events", summary: "recent webhook payloads and sessions" },
{ method: "POST", path: "/v1/webhooks/:id/disable", summary: "disable a webhook" },
{ method: "POST", path: "/v1/webhooks/:id/enable", summary: "re-enable a webhook" },
],
diff --git a/src/api/app-messaging.ts b/src/api/app-messaging.ts
index eaa95c5e1..2124537b5 100644
--- a/src/api/app-messaging.ts
+++ b/src/api/app-messaging.ts
@@ -49,6 +49,7 @@ export function createMessagingMethods(
| "createWebhook"
| "getWebhook"
| "listWebhooks"
+ | "listWebhookEvents"
| "setWebhookEnabled"
| "setWebhookRecipientConsent"
| "pendingDeliveries"
@@ -276,6 +277,16 @@ export function createMessagingMethods(
getWebhook(id) {
return deps.webhooks.get(id);
},
+ async listWebhookEvents(id, viewer) {
+ const events = await deps.webhooks.listEvents(id);
+ return Promise.all(
+ events.map(async (event) => {
+ const session = await deps.sessions.getByThread(`webhook:${id}:${event.deliveryId}`);
+ const visible = session && (await h.sessionForViewer(session.id, viewer));
+ return { ...event, ...(visible ? { sessionId: session.id } : {}) };
+ }),
+ );
+ },
listWebhooks() {
return deps.webhooks.list();
},
diff --git a/src/api/app-turn.ts b/src/api/app-turn.ts
index 45b3d277d..28b69e737 100644
--- a/src/api/app-turn.ts
+++ b/src/api/app-turn.ts
@@ -125,6 +125,10 @@ export function createTurnMethods(
}
}
+ if (req.surface === "webhook" && req.triggered && !sessionParticipantIds) {
+ sessionParticipantIds = [actor.id];
+ }
+
const orgRuntimeScope = scopeId("org", orgIdOf());
const turnRuntimeScope =
req.conversation.kind === "dm"
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index ee55c0041..2998c938a 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -52,7 +52,7 @@ import type { ScopedConfigStore } from "../resolution/config-store.ts";
import { type AdminService } from "../admin/admin-service.ts";
import type { CronStore, CreateCronInput, CronPatch } from "../cron/cron-store.ts";
import type { CronFireRecord } from "../cron/fire-store.ts";
-import type { WebhookStore, CreateWebhookInput } from "../webhooks/webhook-store.ts";
+import type { WebhookStore, WebhookEvent, CreateWebhookInput } from "../webhooks/webhook-store.ts";
import type { DeliveryStore } from "../delivery/delivery-store.ts";
import type {
ChannelMembership,
@@ -409,6 +409,7 @@ export interface App {
setCronRecipientConsent(id: string, recipientConsent: RecipientConsent): Promise<void>;
createWebhook(input: CreateWebhookInput): Promise<Webhook>;
getWebhook(id: string): Promise<Webhook | null>;
+ listWebhookEvents(id: string, viewer: string): Promise<Array<WebhookEvent & { sessionId?: string }>>;
listWebhooks(): Promise<Webhook[]>;
setWebhookEnabled(id: string, enabled: boolean): Promise<void>;
setWebhookRecipientConsent(id: string, recipientConsent: RecipientConsent): Promise<void>;
diff --git a/src/api/routes/webhooks.ts b/src/api/routes/webhooks.ts
index ca8cb208f..1131fbe3b 100644
--- a/src/api/routes/webhooks.ts
+++ b/src/api/routes/webhooks.ts
@@ -144,6 +144,16 @@ async function listWebhooks(ctx: ApiCtx): Promise<void> {
});
}
+async function listWebhookEvents(ctx: ApiCtx): Promise<void> {
+ const { res, app, params, capability, actor, url } = ctx;
+ const webhook = await app.getWebhook(params.id!);
+ const viewer = capability?.actorId ?? actor?.p ?? url.searchParams.get("viewer");
+ if (!viewer || !webhook || !(await canAdministerWebhook(app, webhook, viewer))) {
+ return sendJson(res, 404, { error: "not_found" });
+ }
+ return sendJson(res, 200, { events: await app.listWebhookEvents(webhook.id, viewer) });
+}
+
async function setWebhookEnabled(ctx: ApiCtx, enabled: boolean): Promise<void> {
const { res, app, params, capability, actor, url } = ctx;
const id = params.id!;
@@ -171,6 +181,7 @@ export const webhookRawRoutes: ReadonlyArray<Route<BaseCtx>> = [
export const webhookRoutes: ReadonlyArray<Route<ApiCtx>> = [
{ method: "POST", path: "/v1/webhooks", auth: "either", handle: createWebhook },
{ method: "GET", path: "/v1/webhooks", auth: "either", handle: listWebhooks },
+ { method: "GET", path: "/v1/webhooks/:id/events", auth: "either", handle: listWebhookEvents },
{ method: "POST", path: "/v1/webhooks/:id/disable", auth: "either", handle: disableWebhook },
{ method: "POST", path: "/v1/webhooks/:id/enable", auth: "either", handle: enableWebhook },
];
diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.ts
index b46d0bd83..9f1b17b48 100644
--- a/src/api/user-scoped-routes.ts
+++ b/src/api/user-scoped-routes.ts
@@ -69,6 +69,7 @@ const USER_SCOPED: Rule[] = [
pat("POST", "/v1/soul", { in: "body", name: "actorId" }),
pat("POST", "/v1/webhooks", { in: "body", name: "createdBy" }),
pat("GET", "/v1/webhooks", { in: "query", name: "viewer" }),
+ pat("GET", "/v1/webhooks/:id/events", { in: "query", name: "viewer" }),
pat("GET", "/v1/crons", { in: "query", name: "viewer" }),
pat("POST", "/v1/crons", { in: "body", name: "createdBy" }),
pat("GET", "/v1/crons/:id", { in: "query", name: "principalId" }),
diff --git a/src/webhooks/webhook-receiver.ts b/src/webhooks/webhook-receiver.ts
index 2b64c94a8..d27625e6c 100644
--- a/src/webhooks/webhook-receiver.ts
+++ b/src/webhooks/webhook-receiver.ts
@@ -106,6 +106,11 @@ export function createWebhookReceiver(deps: WebhookReceiverDeps): WebhookReceive
const event = renderEvent(wh, deliveryId, parsed, req.rawBody);
const destination: Destination | undefined = wh.destination;
+ await deps.webhooks.recordEvent(wh.id, {
+ deliveryId,
+ receivedAt: Date.now(),
+ payload: event.securityScreenData,
+ });
void runTrigger(triggerDeps, {
owner: wh.owner,
diff --git a/src/webhooks/webhook-store.ts b/src/webhooks/webhook-store.ts
index ee5ae4385..d5ab0338f 100644
--- a/src/webhooks/webhook-store.ts
+++ b/src/webhooks/webhook-store.ts
@@ -18,7 +18,19 @@ export interface CreateWebhookInput extends CreateTriggerInput {
filters?: Webhook["filters"];
}
+export interface WebhookEvent {
+ deliveryId: string;
+ receivedAt: number;
+ payload: string;
+}
+
+export interface WebhookHistory {
+ events: WebhookEvent[];
+}
+
export interface WebhookStore {
+ recordEvent(id: string, event: WebhookEvent): Promise<void>;
+ listEvents(id: string): Promise<WebhookEvent[]>;
create(input: CreateWebhookInput): Promise<Webhook>;
get(id: string): Promise<Webhook | null>;
list(): Promise<Webhook[]>;
@@ -27,8 +39,33 @@ export interface WebhookStore {
recordFire(id: string, info: { at: number; deliveryId?: string; error?: string }): Promise<void>;
}
-export function createWebhookStore(backing: DurableMap<Webhook> = createMemoryMap<Webhook>()): WebhookStore {
+export function createWebhookStore(
+ backing: DurableMap<Webhook> = createMemoryMap<Webhook>(),
+ history: DurableMap<WebhookHistory> = createMemoryMap<WebhookHistory>(),
+): WebhookStore {
+ if (!history.update) throw new Error("webhook history requires atomic updates");
+ const updateHistory = history.update.bind(history);
return {
+ async recordEvent(id, event) {
+ await history.putIfAbsent(id, { events: [] });
+ await updateHistory(id, (value) => {
+ if (value.events.some((e) => e.deliveryId === event.deliveryId)) return value;
+ return {
+ events: [
+ ...value.events,
+ {
+ ...event,
+ payload: event.payload.slice(0, 16_100),
+ },
+ ]
+ .sort((a, b) => b.receivedAt - a.receivedAt || a.deliveryId.localeCompare(b.deliveryId))
+ .slice(0, 50),
+ };
+ });
+ },
+ async listEvents(id) {
+ return structuredClone((await history.get(id))?.events ?? []);
+ },
async create(input) {
assertNoEscalation(input);
if (!getVerifier(input.verification.scheme) || !input.verification.secret) {
diff --git a/src/wiring.ts b/src/wiring.ts
index 0c42946d0..cfb371589 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -133,7 +133,7 @@ import {
import { createIdempotencyStore, type IdempotencyRecord } from "./idempotency/idempotency-store.ts";
import { createScheduler, type Scheduler } from "./cron/scheduler.ts";
import { createPgBossCronQueue } from "./cron/job-queue.ts";
-import { createWebhookStore } from "./webhooks/webhook-store.ts";
+import { createWebhookStore, type WebhookHistory } from "./webhooks/webhook-store.ts";
import { createWebhookReceiver, type WebhookReceiver } from "./webhooks/webhook-receiver.ts";
import { createDeployStore, deployTouchDebounceMs, type Deployment } from "./deploy/deploy-store.ts";
import { viewerIdentityKey } from "./deploy/access-token.ts";
@@ -1508,7 +1508,7 @@ export function buildApp(
cronChanged.notify?.(id);
},
};
- const webhooks = createWebhookStore(artifactMap<Webhook>("webhooks"));
+ const webhooks = createWebhookStore(artifactMap<Webhook>("webhooks"), artifactMap<WebhookHistory>("webhook_history"));
pgArtifactMap?.pool.registerMigration({
id: "durable-map/webhooks/0002-disable-rows-orphaned-by-webhook-removal",
legacyId: "durable-map/webhooks/0002-disable-rows-orphaned-by-webhook-removal",
diff --git a/test/postgres-map.test.ts b/test/postgres-map.test.ts
index 3c8e612bf..e7af74dfe 100644
--- a/test/postgres-map.test.ts
+++ b/test/postgres-map.test.ts
@@ -2,7 +2,8 @@ import { test, before } from "node:test";
import assert from "node:assert/strict";
import { createMemoryMap, createPostgresMapFactory } from "../src/persistence/durable-map.ts";
import { createCronStore } from "../src/cron/cron-store.ts";
-import { scopeId, type Cron } from "../src/types.ts";
+import { createWebhookStore, type WebhookHistory } from "../src/webhooks/webhook-store.ts";
+import { scopeId, type Webhook, type Cron } from "../src/types.ts";
import {
createKeychain,
KeychainError,
@@ -21,7 +22,7 @@ before(async () => {
const p = new pg.Pool({ connectionString: URL });
await p.query("DROP TABLE IF EXISTS qm_schema_migrations CASCADE");
await p.query(
- "DROP TABLE IF EXISTS map_widgets, map_crons, map_keychain_creds, map_keychain_grants, map_keychain_asks, process_sessions, durable_map_versions CASCADE",
+ "DROP TABLE IF EXISTS map_webhooks, map_webhook_history, map_widgets, map_crons, map_keychain_creds, map_keychain_grants, map_keychain_asks, process_sessions, durable_map_versions CASCADE",
);
await p.end();
});
@@ -309,3 +310,38 @@ test("pg map: concurrent keychain instances claim a once grant exactly once", {
await second.pool.close();
}
});
+
+test("pg map: webhook history retains concurrent deliveries across store instances", { skip }, async () => {
+ const factory = createPostgresMapFactory(URL!);
+ const makeStore = () =>
+ createWebhookStore(factory.map<Webhook>("map_webhooks"), factory.map<WebhookHistory>("map_webhook_history"));
+ const a = makeStore();
+ const b = makeStore();
+ const webhook = await a.create({
+ ownerScopeId: scopeId("personal", "U1"),
+ owner: "U1",
+ createdBy: "U1",
+ action: "summarize",
+ verification: { scheme: "github", secret: "test-only" },
+ });
+ await Promise.all(
+ Array.from({ length: 60 }, (_, i) =>
+ (i % 2 ? a : b).recordEvent(webhook.id, {
+ deliveryId: `event-${i}`,
+ receivedAt: i,
+ payload: "hello 🌊",
+ }),
+ ),
+ );
+ await b.recordEvent(webhook.id, {
+ deliveryId: "event-59",
+ receivedAt: 59,
+ payload: "hello 🌊",
+ });
+ const events = await makeStore().listEvents(webhook.id);
+ assert.equal(events.length, 50);
+ assert.equal(events[0]?.receivedAt, 59);
+ assert.equal(events[0]?.payload, "hello 🌊");
+ assert.equal(events.at(-1)?.receivedAt, 10);
+ assert.equal(new Set(events.map((e) => e.deliveryId)).size, 50);
+});
diff --git a/test/web-ui-webhooks.test.ts b/test/web-ui-webhooks.test.ts
index 0c137b9e2..71b300470 100644
--- a/test/web-ui-webhooks.test.ts
+++ b/test/web-ui-webhooks.test.ts
@@ -216,3 +216,20 @@ test("public web creation rejects unauthenticated verification and malformed fil
);
assert.equal(destination.status, 400);
});
+
+test("webhook history is relayed with the authenticated viewer, not a query-string impersonation", async () => {
+ const res = await fetch(
+ `${webBase}/api/webhooks`,
+ asUser("history-owner", {
+ method: "POST",
+ body: JSON.stringify({ action: "history test", verification: { scheme: "github" } }),
+ }),
+ );
+ const { webhook } = (await res.json()) as { webhook: { id: string } };
+ const path = `${webBase}/api/webhooks/${webhook.id}/events`;
+ const owner = await fetch(path, asUser("history-owner"));
+ assert.equal(owner.status, 200);
+ assert.deepEqual(await owner.json(), { events: [] });
+ const stranger = await fetch(`${path}?viewer=history-owner`, asUser("stranger"));
+ assert.equal(stranger.status, 404);
+});
diff --git a/test/webhook-receiver.test.ts b/test/webhook-receiver.test.ts
index 9d411787a..cc09c3f47 100644
--- a/test/webhook-receiver.test.ts
+++ b/test/webhook-receiver.test.ts
@@ -323,3 +323,51 @@ test("linear rejects signed untimed deliveries without firing a turn", async ()
await flush();
assert.equal(calls.length, 1);
});
+
+const historyWebhook = {
+ ownerScopeId: scopeId("personal", "U1"),
+ owner: "U1",
+ createdBy: "U1",
+ action: "summarize",
+ verification: { scheme: "github" as const, secret: SECRET },
+};
+
+test("history records the agent payload once per delivery without request headers", async () => {
+ const { webhooks, receiver } = harness();
+ const wh = await webhooks.create(historyWebhook);
+ const req = githubReq(JSON.stringify({ message: "<script>alert(1)</script>", long: "x".repeat(20_000) }));
+ await Promise.all([receiver.deliver(wh.id, req), receiver.deliver(wh.id, req)]);
+ await flush();
+ const events = await webhooks.listEvents(wh.id);
+ assert.equal(events.length, 1);
+ assert.match(events[0]?.payload ?? "", /truncated/);
+ assert.ok(events[0]!.payload.length < 16_100);
+ assert.equal(JSON.stringify(events).includes(SECRET), false);
+ assert.equal(JSON.stringify(events).includes("x-hub-signature"), false);
+});
+
+test("history excludes rejected signatures, handshakes and filtered deliveries", async () => {
+ const { webhooks, receiver } = harness();
+ const wh = await webhooks.create({
+ ...historyWebhook,
+ filters: [{ path: "action", in: ["opened"] }],
+ });
+ const bad = githubReq('{"action":"opened"}');
+ bad.headers["x-hub-signature-256"] = "invalid";
+ await receiver.deliver(wh.id, bad);
+ await receiver.deliver(wh.id, githubReq("{}", "ping", "ping"));
+ await receiver.deliver(wh.id, githubReq('{"action":"closed"}'));
+ await flush();
+ assert.deepEqual(await webhooks.listEvents(wh.id), []);
+});
+
+test("history capture failure rejects before acknowledging or starting a turn", async () => {
+ const { webhooks, calls, receiver } = harness();
+ const wh = await webhooks.create(historyWebhook);
+ webhooks.recordEvent = async () => {
+ throw new Error("history unavailable");
+ };
+ await assert.rejects(receiver.deliver(wh.id, githubReq("{}")), /history unavailable/);
+ await flush();
+ assert.equal(calls.length, 0);
+});
diff --git a/test/webhook-routes.test.ts b/test/webhook-routes.test.ts
index 88e4a2329..2357bd649 100644
--- a/test/webhook-routes.test.ts
+++ b/test/webhook-routes.test.ts
@@ -239,3 +239,53 @@ test("inbound per-webhook auth holds even in core dev mode (no core secret)", as
await srv.close();
}
});
+
+test("signed webhook history enforces viewer permissions and links to an owner-readable worklog", async () => {
+ const srv = start(SECRET);
+ try {
+ const body = regBody();
+ const created = await fetch(`${srv.base}/v1/webhooks`, {
+ method: "POST",
+ headers: sign("POST", "/v1/webhooks", body),
+ body,
+ });
+ const { webhook } = (await created.json()) as { webhook: { id: string } };
+ for (const [suffix, status] of [
+ ["?viewer=U1", 200],
+ ["?viewer=U2", 404],
+ ["", 404],
+ ] as const) {
+ const path = `/v1/webhooks/${webhook.id}/events${suffix}`;
+ const res = await fetch(`${srv.base}${path}`, { headers: sign("GET", path, "") });
+ assert.equal(res.status, status);
+ if (status === 200) assert.deepEqual(await res.json(), { events: [] });
+ }
+ assert.equal((await fetch(`${srv.base}/v1/webhooks/${webhook.id}/events?viewer=U1`)).status, 401);
+ const eventBody = JSON.stringify({ message: "agent message for worklog" });
+ const accepted = await fetch(`${srv.base}/v1/webhooks/incoming/${webhook.id}`, {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-hub-signature-256": githubSig(eventBody) },
+ body: eventBody,
+ });
+ assert.equal(accepted.status, 202);
+ const historyPath = `/v1/webhooks/${webhook.id}/events?viewer=U1`;
+ let events: Array<{ sessionId?: string; payload: string }> = [];
+ for (let i = 0; i < 100; i++) {
+ const history = await fetch(`${srv.base}${historyPath}`, { headers: sign("GET", historyPath, "") });
+ ({ events } = (await history.json()) as { events: typeof events });
+ if (events[0]?.sessionId) break;
+ await new Promise((r) => setTimeout(r, 10));
+ }
+ assert.equal(events.length, 1);
+ assert.ok(events[0]?.sessionId);
+ assert.match(events[0]!.payload, /agent message for worklog/);
+ const sessionPath = `/v1/sessions/${events[0]!.sessionId}?viewer=U1`;
+ const worklog = await fetch(`${srv.base}${sessionPath}`, { headers: sign("GET", sessionPath, "") });
+ assert.equal(worklog.status, 200);
+ assert.match(JSON.stringify(await worklog.json()), /agent message for worklog/);
+ const otherPath = `/v1/sessions/${events[0]!.sessionId}?viewer=U2`;
+ assert.equal((await fetch(`${srv.base}${otherPath}`, { headers: sign("GET", otherPath, "") })).status, 404);
+ } finally {
+ await srv.close();
+ }
+});
diff --git a/test/webhook-store.test.ts b/test/webhook-store.test.ts
index 7604a14d2..b09a79f62 100644
--- a/test/webhook-store.test.ts
+++ b/test/webhook-store.test.ts
@@ -125,3 +125,46 @@ test("re-creating a byte-identical disabled webhook re-enables it", async () =>
assert.equal(second.enabled, true);
assert.equal((await store.get(first.id))?.enabled, true);
});
+
+test("history survives reconstruction without entering webhook listings", async () => {
+ const history = createMemoryMap<import("../src/webhooks/webhook-store.ts").WebhookHistory>();
+ const backing = createMemoryMap<Webhook>();
+ const store = createWebhookStore(backing, history);
+ const wh = await store.create(base);
+ const event = { deliveryId: "one", receivedAt: 1, payload: "hello" };
+ await store.recordEvent(wh.id, event);
+ const restored = createWebhookStore(backing, history);
+ assert.deepEqual(await restored.listEvents(wh.id), [event]);
+ assert.equal(JSON.stringify(await restored.list()).includes("hello"), false);
+ assert.deepEqual(await restored.listEvents("unknown"), []);
+});
+
+test("history atomically retains the latest 50 and bounds payloads", async () => {
+ const store = createWebhookStore();
+ const wh = await store.create(base);
+ await Promise.all(
+ Array.from({ length: 70 }, (_, i) =>
+ store.recordEvent(wh.id, {
+ deliveryId: `delivery-${i}`,
+ receivedAt: i,
+ payload: "x".repeat(20_000),
+ }),
+ ),
+ );
+ const events = await store.listEvents(wh.id);
+ assert.equal(events.length, 50);
+ assert.equal(events[0]?.receivedAt, 69);
+ assert.equal(events[1]?.payload.length, 16_100);
+ assert.equal(events.at(-1)?.receivedAt, 20);
+ events.pop();
+ assert.equal((await store.listEvents(wh.id)).length, 50);
+});
+
+test("a repeated receipt preserves the original payload and timestamp", async () => {
+ const store = createWebhookStore();
+ const wh = await store.create(base);
+ const original = { deliveryId: "one", receivedAt: 1, payload: "hello" };
+ await store.recordEvent(wh.id, original);
+ await store.recordEvent(wh.id, { ...original, receivedAt: 2, payload: "changed" });
+ assert.deepEqual(await store.listEvents(wh.id), [original]);
+});