⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat: enrich webhook payloads and cap webhook response reads (#446)
Croffdd4d0b54433b
diff --git a/apps/api/src/modules/columns/service.ts b/apps/api/src/modules/columns/service.tsindex dc1bf3a1..594baba6 100644--- a/apps/api/src/modules/columns/service.ts+++ b/apps/api/src/modules/columns/service.ts@@ -3,6 +3,9 @@ import { and, eq, inArray, isNull, sql } from 'drizzle-orm';import { HttpError } from '#shared/lib';import { getMembership } from '#modules/members/service';import { recordActivityForIssues, statusSide } from '#modules/issues/activity';+import { getIssues } from '#modules/issues/service';+import { emitIssueEvents, issuePayloads } from '#modules/issues/webhook-payload';+import { emitWebhookEvents, subscribedWebhooks } from '#modules/webhooks/emit';import { recordStatusChange } from '#modules/issues/status-history';export interface ColumnRow {@@ -229,6 +232,13 @@ export async function deleteColumn(throw new HttpError(400, 'Target column must differ from the deleted column');}+ // Built before the transaction: the payloads name the column, which it deletes.+ let deletedPayloads: unknown[] = [];+ if (opts.mode === 'delete' && (await subscribedWebhooks(projectId, 'issue.deleted')).length > 0) {+ const rows = await db.select({ id: issue.id }).from(issue).where(eq(issue.columnId, columnId));+ deletedPayloads = await issuePayloads(await getIssues(rows.map((r) => r.id)));+ }+const movedIssueIds = await db.transaction(async (tx) => {let moved: number[] = [];if (opts.mode === 'move') {@@ -256,5 +266,10 @@ export async function deleteColumn({ action: 'status', from: statusSide(column), to: statusSide(target) },actorUserId,);+ const moved = () => getIssues(movedIssueIds);+ await emitIssueEvents(projectId, 'issue.updated', moved, actorUserId);+ await emitIssueEvents(projectId, 'issue.state_changed', moved, actorUserId);+ } else {+ await emitWebhookEvents(projectId, 'issue.deleted', async () => deletedPayloads, actorUserId);}}diff --git a/apps/api/src/modules/issues/__tests__/integration/auto-archive.test.ts b/apps/api/src/modules/issues/__tests__/integration/auto-archive.test.tsindex 5b0cc2c2..f7e9872c 100644--- a/apps/api/src/modules/issues/__tests__/integration/auto-archive.test.ts+++ b/apps/api/src/modules/issues/__tests__/integration/auto-archive.test.ts@@ -52,6 +52,27 @@ describe('auto-archive sweep', () => {expect(feed.items.map((entry) => entry.action)).toContain('archived');});+ it('sends issue.updated with the sweep as a system actor', async () => {+ const { api, doneId } = await setup();+ const webhookId = (+ await api.projects({ projectKey: 'MKT' }).webhooks.post({+ url: 'https://example.com/hook',+ events: ['issue.updated'],+ })+ ).data!.id;+ const issueId = await addIssue(api, doneId, 'Shipped');+ await backdate(issueId, 20);++ await sweepStaleIssues();++ const deliveries = (await api.webhooks({ webhookId }).deliveries.get()).data!.items;+ expect(deliveries).toHaveLength(1);+ expect(deliveries[0].payload).toMatchObject({+ actor: { type: 'system', id: null, name: 'Auto-archive' },+ data: { id: issueId },+ });+ });+it('leaves an issue that is still active, recently touched, or in a live column', async () => {const { api, doneId, todoId } = await setup();const recent = await addIssue(api, doneId, 'Just done');diff --git a/apps/api/src/modules/issues/activity.ts b/apps/api/src/modules/issues/activity.tsindex 6ec8f3d8..f0b01204 100644--- a/apps/api/src/modules/issues/activity.ts+++ b/apps/api/src/modules/issues/activity.ts@@ -13,7 +13,7 @@ import {} from '@repo/db';import { and, desc, eq, gte, inArray, isNull, lt, sql } from 'drizzle-orm';import { HttpError, iso } from '#shared/lib';-import { emitWebhookEvent } from '#modules/webhooks/emit';+import { emitCommentEvent } from './webhook-payload';import { addedMentionHandles, parseMentionHandles, resolveMentionHandles } from '#shared/mentions';import { isAgentUser, listMentionTriggerAgents } from '#modules/agents/core/service';import { enqueueAgentRun } from '#modules/agents/core/run-queue';@@ -295,7 +295,7 @@ export async function createComment(input: {.where(eq(issue.id, input.issueId));const projectId = projectRows[0]?.projectId;if (projectId != null) {- await emitWebhookEvent(projectId, 'comment.created', comment);+ await emitCommentEvent(projectId, 'comment.created', comment, actorUserId);// Resolved once: the agent halves start runs, the member half is notified.const mentioned = await resolveMentionHandles(projectId,@@ -355,7 +355,7 @@ export async function updateComment(const comment = mapFeedItem(row);await recordActivity(comment.issueId, [{ action: 'comment_edited' }], actorUserId);- await emitWebhookEvent(projectId, 'comment.updated', comment);+ await emitCommentEvent(projectId, 'comment.updated', comment, actorUserId);const added = addedMentionHandles(before.body ?? '', body);if (added.length > 0) {@@ -384,7 +384,7 @@ export async function deleteComment(if (!before) return false;await db.delete(issueActivity).where(eq(issueActivity.id, commentId));await recordActivity(before.issueId as number, [{ action: 'comment_deleted' }], actorUserId);- await emitWebhookEvent(projectId, 'comment.deleted', mapFeedItem(before));+ await emitCommentEvent(projectId, 'comment.deleted', mapFeedItem(before), actorUserId);return true;}diff --git a/apps/api/src/modules/issues/auto-archive.ts b/apps/api/src/modules/issues/auto-archive.tsindex 8f5138a8..403e95b9 100644--- a/apps/api/src/modules/issues/auto-archive.ts+++ b/apps/api/src/modules/issues/auto-archive.ts@@ -1,6 +1,8 @@import { db } from '@repo/db';import { sql } from 'drizzle-orm';import { recordActivityForIssues } from './activity';+import { getIssues } from './service';+import { emitIssueEvents } from './webhook-payload';// Archives active issues that have sat inactive in a completed/canceled column past// their project's threshold. Inactivity is measured by issue.updated_at: moving to a@@ -29,9 +31,19 @@ export async function sweepStaleIssues(): Promise<number> {AND (s.value->>'canceledDays') ~ '^[0-9]{1,4}$'AND i.updated_at < now() - make_interval(days => (s.value->>'canceledDays')::int)))- RETURNING i.id+ RETURNING i.id, i.project_id`);- const archived = (rows as unknown as Array<{ id: number }>).map((row) => row.id);- await recordActivityForIssues(archived, { action: 'archived' }, { system: 'Auto-archive' });+ const archivedRows = rows as unknown as Array<{ id: number; project_id: number }>;+ const archived = archivedRows.map((row) => row.id);+ const actor = { system: 'Auto-archive' };+ await recordActivityForIssues(archived, { action: 'archived' }, actor);+ const idsByProject = new Map<number, number[]>();+ for (const row of archivedRows) {+ const ids = idsByProject.get(row.project_id) ?? [];+ ids.push(row.id);+ idsByProject.set(row.project_id, ids);+ }+ for (const [projectId, ids] of idsByProject)+ await emitIssueEvents(projectId, 'issue.updated', () => getIssues(ids), actor);return archived.length;}diff --git a/apps/api/src/modules/issues/index.ts b/apps/api/src/modules/issues/index.tsindex 7a3724f6..072c3d4d 100644--- a/apps/api/src/modules/issues/index.ts+++ b/apps/api/src/modules/issues/index.ts@@ -351,7 +351,11 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issuesdisposition(body),requireUser(user).id,);- const { deleted, attachments } = await bulkDeleteIssues(project.id, body.ids);+ const { deleted, attachments } = await bulkDeleteIssues(+ project.id,+ body.ids,+ requireUser(user).id,+ );await purgeObjects([...fromSubtasks, ...attachments]);return { deleted };},@@ -732,7 +736,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issuesdisposition(query),requireUser(user).id,);- const attachments = await deleteIssue(params.issueId);+ const attachments = await deleteIssue(params.issueId, requireUser(user).id);if (!attachments) throw new HttpError(404, 'Issue not found');await purgeObjects([...fromSubtasks, ...attachments]);return noContent();diff --git a/apps/api/src/modules/issues/links.ts b/apps/api/src/modules/issues/links.tsindex 2bb50221..440dbba8 100644--- a/apps/api/src/modules/issues/links.ts+++ b/apps/api/src/modules/issues/links.ts@@ -3,7 +3,7 @@ import { and, eq, isNull, or, sql } from 'drizzle-orm';import { alias } from 'drizzle-orm/pg-core';import { HttpError } from '#shared/lib';import { recordActivityEntries, rowSide, textSide, type ActivityInput } from './activity';-import { emitWebhookEvents } from '#modules/webhooks/emit';+import { emitIssueEvents } from './webhook-payload';import { getIssues } from './service';// Relations between issues of one project. A relation is one row (issue_link);@@ -278,8 +278,11 @@ export async function addIssueLink(return { target, linkId: target.linkId };});- await emitWebhookEvents(target.projectId, 'issue.link_changed', () =>- getIssues([issueId, targetIssueId]),+ await emitIssueEvents(+ target.projectId,+ 'issue.link_changed',+ () => getIssues([issueId, targetIssueId]),+ actorUserId,);return {@@ -364,8 +367,11 @@ export async function removeIssueLink(});if (!removed) return false;- await emitWebhookEvents(removed.projectId, 'issue.link_changed', () =>- getIssues(removed.issueIds),+ await emitIssueEvents(+ removed.projectId,+ 'issue.link_changed',+ () => getIssues(removed.issueIds),+ actorUserId,);return true;}diff --git a/apps/api/src/modules/issues/service.ts b/apps/api/src/modules/issues/service.tsindex 9597edf5..50c664d6 100644--- a/apps/api/src/modules/issues/service.ts+++ b/apps/api/src/modules/issues/service.ts@@ -59,7 +59,7 @@ import { recordCycleChange } from './cycle-history';import { recordStatusChange } from './status-history';import { mapAttachment, type AttachmentRow } from '#modules/attachments/service';import { notifyIssueChange, notifyTextMentions } from '#modules/notifications/service';-import { emitWebhookEvent } from '#modules/webhooks/emit';+import { emitIssueEvent } from './webhook-payload';import {getAssignTriggerAgent,getFieldTriggerAgent,@@ -452,7 +452,9 @@ export async function archiveIssue(return getIssue(id);}await recordActivity(id, [{ action: 'archived' }], actorUserId);- return getIssue(id);+ const archived = await getIssue(id);+ if (archived) await emitIssueEvent('issue.updated', archived, actorUserId);+ return archived;}// Restores an archived issue back onto the board (archived_at -> null). Records a@@ -468,7 +470,9 @@ export async function restoreIssue(.returning({ id: issue.id });if (!row) return getIssue(id);await recordActivity(id, [{ action: 'restored' }], actorUserId);- return getIssue(id);+ const restored = await getIssue(id);+ if (restored) await emitIssueEvent('issue.updated', restored, actorUserId);+ return restored;}// Expands what an issue is planned under — its initiative and its cycle — to@@ -900,7 +904,7 @@ export async function createIssue(// The author follows what they filed; the assignee is subscribed by the// assignment notification below, the same as a later assignment does.await autoWatchIssue(project.id, issueId, [actorUserId]);- await emitWebhookEvent(project.id, 'issue.created', created);+ await emitIssueEvent('issue.created', created, actorUserId);// An issue created already delegated to an agent enqueues a run, the same as// delegating one later does.await enqueueDelegateRun(created, actorUserId);@@ -1076,13 +1080,13 @@ export async function updateIssue(if (before.parentId !== after.parentId)await recordParentChange(id, before.parentId, after.parentId, actor);if (changed) {- await emitWebhookEvent(after.projectId, 'issue.updated', after);+ await emitIssueEvent('issue.updated', after, actor);// Granular events fire in addition to issue.updated when their field changed.if (before.assigneeUserId !== after.assigneeUserId)- await emitWebhookEvent(after.projectId, 'issue.assigned', after);+ await emitIssueEvent('issue.assigned', after, actor);if (before.delegateUserId !== after.delegateUserId) await enqueueDelegateRun(after, actor);if (before.columnId !== after.columnId) {- await emitWebhookEvent(after.projectId, 'issue.state_changed', after);+ await emitIssueEvent('issue.state_changed', after, actor);await applySubtaskAutomation(after, actor);}}@@ -1113,31 +1117,24 @@ async function enqueueDelegateRun(after: IssueRow, actor?: ActivityActor): Promi// attachments, and activity all go by their ON DELETE CASCADE on issue_id. Returns// the deleted attachment rows so the caller can remove their objects from the store.// Returns null if the issue did not exist.-export async function deleteIssue(issueId: number): Promise<AttachmentRow[] | null> {- const result = await db.transaction(async (tx) => {- const rows = await tx- .select({ projectId: issue.projectId, seq: issue.sequenceNumber, key: projectTable.key })- .from(issue)- .innerJoin(projectTable, eq(projectTable.id, issue.projectId))- .where(eq(issue.id, issueId));- if (rows.length === 0) return null;+export async function deleteIssue(+ issueId: number,+ actorUserId?: string | null,+): Promise<AttachmentRow[] | null> {+ // Read before the delete: the issue.deleted payload is the issue as it last read.+ const deleted = await getIssue(issueId);+ if (!deleted) return null;+ const attachments = await db.transaction(async (tx) => {const attachmentRows = await tx.select().from(issueAttachment).where(eq(issueAttachment.issueId, issueId));- await tx.delete(issue).where(eq(issue.id, issueId));- return {- attachments: attachmentRows.map(mapAttachment),- projectId: rows[0].projectId,- identifier: `${rows[0].key}-${rows[0].seq}`,- };- });- if (!result) return null;- await emitWebhookEvent(result.projectId, 'issue.deleted', {- id: issueId,- identifier: result.identifier,+ const removed = await tx.delete(issue).where(eq(issue.id, issueId)).returning({ id: issue.id });+ return removed.length ? attachmentRows.map(mapAttachment) : null;});- return result.attachments;+ if (!attachments) return null;+ await emitIssueEvent('issue.deleted', deleted, actorUserId);+ return attachments;}// Replaces the issue's full label set (not an add/remove diff) and logs the@@ -1188,7 +1185,7 @@ export async function setIssueLabels(if (emitEvent && (added.length > 0 || removed.length > 0)) {const issueRow = await getIssue(issueId);- if (issueRow) await emitWebhookEvent(issueRow.projectId, 'issue.label_changed', issueRow);+ if (issueRow) await emitIssueEvent('issue.label_changed', issueRow, actorUserId);}}@@ -1324,11 +1321,12 @@ export async function bulkArchiveIssues(export async function bulkDeleteIssues(projectId: number,ids: number[],+ actorUserId: string | null,): Promise<{ deleted: number; attachments: AttachmentRow[] }> {const valid = await issuesInProject(projectId, ids);const attachments: AttachmentRow[] = [];for (const id of valid) {- const rows = await deleteIssue(id);+ const rows = await deleteIssue(id, actorUserId);if (rows) attachments.push(...rows);}return { deleted: valid.length, attachments };diff --git a/apps/api/src/modules/issues/subtasks.ts b/apps/api/src/modules/issues/subtasks.tsindex cf3743cd..4607941b 100644--- a/apps/api/src/modules/issues/subtasks.ts+++ b/apps/api/src/modules/issues/subtasks.ts@@ -157,7 +157,8 @@ async function disposeSubtasks(if (mode === 'cascade') {const attachments: AttachmentRow[] = [];for (const subtask of subtasks) {- if (action === 'delete') attachments.push(...((await deleteIssue(subtask.id)) ?? []));+ if (action === 'delete')+ attachments.push(...((await deleteIssue(subtask.id, actorUserId)) ?? []));else await archiveIssue(subtask.id, actorUserId);}return attachments;diff --git a/apps/api/src/modules/issues/webhook-payload.ts b/apps/api/src/modules/issues/webhook-payload.tsnew file mode 100644index 00000000..8675ca96--- /dev/null+++ b/apps/api/src/modules/issues/webhook-payload.ts@@ -0,0 +1,147 @@+import { db, issue, issueType, label, project, projectColumn, team, user } from '@repo/db';+import { eq, inArray } from 'drizzle-orm';+import { emitWebhookEvents } from '#modules/webhooks/emit';+import type { WebhookEventType } from '#modules/webhooks/service';+import { issueUrl, teamRef } from '#modules/teams/ref';+import type { ActivityActor, FeedItemRow } from './activity';+import type { IssueRow } from './service';++// Webhook payloads carry names next to ids: a receiver has no API session to resolve+// a column, user, type, or label id, and a message built from the payload needs the+// words. The ids stay in place, so the named fields are additive.++// A query per kind of id, skipped when there is nothing to look up.+function byIds<K, R>(ids: K[], query: (ids: K[]) => Promise<R[]>): Promise<R[]> {+ const unique = [...new Set(ids)];+ return unique.length ? query(unique) : Promise.resolve([]);+}++// The issue's page URL per project, keyed by project id.+async function projectUrls(+ projectIds: number[],+): Promise<Map<number, (seq: number) => string | null>> {+ const rows = await byIds(projectIds, (ids) =>+ db+ .select({ id: project.id, key: project.key, teamId: team.id, teamSlug: team.slug })+ .from(project)+ .innerJoin(team, eq(team.id, project.teamId))+ .where(inArray(project.id, ids)),+ );+ return new Map(+ rows.map((r) => [+ r.id,+ (seq: number) => issueUrl(teamRef({ id: r.teamId, slug: r.teamSlug }), r.key, seq) ?? null,+ ]),+ );+}++export async function issuePayloads(issues: IssueRow[]) {+ const [columns, users, types, labels, urls] = await Promise.all([+ byIds(+ issues.map((i) => i.columnId),+ (ids) =>+ db+ .select({ id: projectColumn.id, name: projectColumn.name, type: projectColumn.stateType })+ .from(projectColumn)+ .where(inArray(projectColumn.id, ids)),+ ),+ byIds(+ issues.flatMap((i) => [i.assigneeUserId, i.delegateUserId]).filter((id) => id !== null),+ (ids) => db.select({ id: user.id, name: user.name }).from(user).where(inArray(user.id, ids)),+ ),+ byIds(+ issues.map((i) => i.typeId).filter((id) => id !== null),+ (ids) =>+ db+ .select({ id: issueType.id, name: issueType.name })+ .from(issueType)+ .where(inArray(issueType.id, ids)),+ ),+ byIds(+ issues.flatMap((i) => i.labelIds),+ (ids) =>+ db+ .select({ id: label.id, name: label.name, color: label.color })+ .from(label)+ .where(inArray(label.id, ids)),+ ),+ projectUrls(issues.map((i) => i.projectId)),+ ]);+ const columnById = new Map(columns.map((c) => [c.id, c]));+ const userById = new Map(users.map((u) => [u.id, u]));+ const typeById = new Map(types.map((t) => [t.id, t]));+ const labelById = new Map(labels.map((l) => [l.id, l]));+ const person = (id: string | null) => (id ? (userById.get(id) ?? { id, name: null }) : null);++ return issues.map((i) => ({+ ...i,+ url: urls.get(i.projectId)?.(i.sequenceNumber) ?? null,+ state: columnById.get(i.columnId) ?? null,+ assignee: person(i.assigneeUserId),+ delegate: person(i.delegateUserId),+ issueType: i.typeId === null ? null : (typeById.get(i.typeId) ?? null),+ labels: i.labelIds.flatMap((id) => labelById.get(id) ?? []),+ }));+}++// Emits one issue event per issue. The payloads are built only when a webhook of the+// project subscribes to eventType.+export async function emitIssueEvents(+ projectId: number,+ eventType: WebhookEventType,+ load: () => Promise<IssueRow[]>,+ actor: ActivityActor,+): Promise<void> {+ await emitWebhookEvents(projectId, eventType, async () => issuePayloads(await load()), actor);+}++export async function emitIssueEvent(+ eventType: WebhookEventType,+ row: IssueRow,+ actor: ActivityActor,+): Promise<void> {+ await emitIssueEvents(row.projectId, eventType, async () => [row], actor);+}++// A comment payload names the issue it is on, so a receiver can link to it.+export async function emitCommentEvent(+ projectId: number,+ eventType: WebhookEventType,+ comment: FeedItemRow,+ actor: ActivityActor,+): Promise<void> {+ await emitWebhookEvents(+ projectId,+ eventType,+ async () => {+ const [row] = await db+ .select({+ seq: issue.sequenceNumber,+ title: issue.title,+ key: project.key,+ teamId: team.id,+ teamSlug: team.slug,+ })+ .from(issue)+ .innerJoin(project, eq(project.id, issue.projectId))+ .innerJoin(team, eq(team.id, project.teamId))+ .where(eq(issue.id, comment.issueId));+ return [+ {+ ...comment,+ issue: row+ ? {+ id: comment.issueId,+ identifier: `${row.key}-${row.seq}`,+ title: row.title,+ url:+ issueUrl(teamRef({ id: row.teamId, slug: row.teamSlug }), row.key, row.seq) ??+ null,+ }+ : null,+ },+ ];+ },+ actor,+ );+}diff --git a/apps/api/src/modules/notifications/outbound.ts b/apps/api/src/modules/notifications/outbound.tsindex c34704d9..94add236 100644--- a/apps/api/src/modules/notifications/outbound.ts+++ b/apps/api/src/modules/notifications/outbound.ts@@ -15,7 +15,7 @@ import { readRedactedSettings } from '#modules/notification-settings/service';import { getPreferencesForUsers } from '#modules/notification-preferences/service';import { getTelegramChatIds, hasUsableInstanceBot } from '#modules/telegram/service';import { escapeHtml } from '#shared/lib';-import { issueWebPath, teamRef } from '#modules/teams/ref';+import { issueUrl, teamRef } from '#modules/teams/ref';import type { NotificationType, NewNotificationRow } from './service';// Outbound notification delivery: turns the inbox notification rows produced by an@@ -43,13 +43,6 @@ function issueRef(projectKey: string, seq: number): string {return `${projectKey}-${seq}`;}-// The public URL of an issue, or undefined when the web origin is not configured-// (then messages carry no link rather than a localhost fallback).-function issueUrl(teamRef: string, projectKey: string, seq: number): string | undefined {- const base = process.env.APP_URL;- return base ? `${base}${issueWebPath(teamRef, projectKey, seq)}` : undefined;-}-interface StateChange {from: string;to: string;diff --git a/apps/api/src/modules/teams/ref.ts b/apps/api/src/modules/teams/ref.tsindex c7e63d07..29098448 100644--- a/apps/api/src/modules/teams/ref.ts+++ b/apps/api/src/modules/teams/ref.ts@@ -45,3 +45,10 @@ export const projectRefSql = sql<string>`coalesce(${team.slug}, ${team.id}::textexport function issueWebPath(teamRef: string, key: string, seq: number): string {return `/${teamRef}/issue/${key}-${seq}`;}++// The full URL of an issue's page, or undefined when the web origin is not configured+// (then messages carry no link rather than a localhost fallback).+export function issueUrl(teamRef: string, key: string, seq: number): string | undefined {+ const base = process.env.APP_URL;+ return base ? `${base}${issueWebPath(teamRef, key, seq)}` : undefined;+}diff --git a/apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.ts b/apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.tsindex 94b20378..b2e8b7b7 100644--- a/apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.ts+++ b/apps/api/src/modules/webhooks/__tests__/integration/webhooks.test.ts@@ -1,16 +1,29 @@import { describe, it, expect, beforeEach } from 'bun:test';-import { authedApi, type Api } from '#tests/helpers/app';+import { apiKeyApi, authedApi, type Api } from '#tests/helpers/app';import { signUpTestUser } from '#tests/helpers/auth';import { resetDb } from '#tests/helpers/db';+import { createAgent } from '#tests/helpers/agents';import type { WebhookEventType } from '../../service';async function setupOwnerProject() {- const owner = await signUpTestUser();+ const owner = await signUpTestUser({ name: 'Owner' });const asOwner = authedApi(owner.cookie);const project = await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });// createProject seeds five default columns; the first is the target for issues.const view = await asOwner.projects({ projectKey: 'MKT' }).get();- return { asOwner, projectId: project.data!.id, columnId: view.data!.columns[0].id };+ return {+ owner,+ asOwner,+ projectId: project.data!.id,+ columnId: view.data!.columns[0].id,+ columns: view.data!.columns,+ };+}++// The payloads queued for a webhook, newest first.+async function payloads(client: Api, webhookId: number) {+ const res = await client.webhooks({ webhookId }).deliveries.get();+ return res.data!.items.map((d) => d.payload as { actor: unknown; data: Record<string, unknown> });}// Registers a webhook on MKT and returns its id.@@ -378,6 +391,154 @@ describe('webhooks', () => {});});+ describe('payload', () => {+ it('names the actor, state, assignee, type, and labels of an issue event', async () => {+ const { owner, asOwner, columnId, columns } = await setupOwnerProject();+ const id = await createWebhook(asOwner, ['issue.assigned']);+ const label = (+ await asOwner.projects({ projectKey: 'MKT' }).labels.post({ name: 'bug', color: '#ff0000' })+ ).data!;+ const issue = (+ await asOwner+ .projects({ projectKey: 'MKT' })+ .issues.post({ columnId, title: 'Task', labelIds: [label.id] })+ ).data!;++ await asOwner.issues({ issueId: issue.id }).patch({ assigneeUserId: owner.userId });++ const [payload] = await payloads(asOwner, id);+ expect(payload.actor).toEqual({ type: 'human', id: owner.userId, name: 'Owner' });+ expect(payload.data).toMatchObject({+ id: issue.id,+ title: 'Task',+ assigneeUserId: owner.userId,+ assignee: { id: owner.userId, name: 'Owner' },+ delegate: null,+ state: { id: columnId, name: columns[0].name, type: columns[0].stateType },+ labels: [{ id: label.id, name: 'bug', color: '#ff0000' }],+ });+ });++ it('marks an agent as the actor of what it does', async () => {+ const { asOwner, columnId } = await setupOwnerProject();+ const id = await createWebhook(asOwner, ['issue.created']);+ const created = (+ await createAgent(asOwner, 'MKT', {+ name: 'Triage Bot',+ username: 'triage',+ kind: 'external',+ })+ ).data!;++ const res = await apiKeyApi(created.apiKey!)+ .projects({ projectKey: 'MKT' })+ .issues.post({ columnId, title: 'Filed by the agent' });+ expect(res.status).toBe(201);++ const [payload] = await payloads(asOwner, id);+ expect(payload.actor).toEqual({+ type: 'agent',+ id: created.agent.userId,+ name: 'Triage Bot',+ });+ });++ it('carries the issue as it last read on issue.deleted', async () => {+ const { asOwner, columnId } = await setupOwnerProject();+ const id = await createWebhook(asOwner, ['issue.deleted']);+ const issue = (+ await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Doomed' })+ ).data!;++ await asOwner.issues({ issueId: issue.id }).delete();++ const [payload] = await payloads(asOwner, id);+ expect(payload).toMatchObject({ action: 'remove', actor: { type: 'human' } });+ expect(payload.data).toMatchObject({+ id: issue.id,+ identifier: issue.identifier,+ title: 'Doomed',+ state: { id: columnId },+ });+ });++ it('names the issue a comment is on', async () => {+ const { asOwner, columnId } = await setupOwnerProject();+ const id = await createWebhook(asOwner, ['comment.created']);+ const issue = (+ await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Task' })+ ).data!;++ await asOwner.issues({ issueId: issue.id }).comments.post({ body: 'looks good' });++ const [payload] = await payloads(asOwner, id);+ expect(payload.data.issue).toMatchObject({+ id: issue.id,+ identifier: issue.identifier,+ title: 'Task',+ });+ });+ });++ describe('events without a field edit', () => {+ it('fires issue.updated on archive and restore', async () => {+ const { asOwner, columnId } = await setupOwnerProject();+ const id = await createWebhook(asOwner, ['issue.updated']);+ const issue = (+ await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Task' })+ ).data!;++ await asOwner.issues({ issueId: issue.id }).archive.post({});+ await asOwner.issues({ issueId: issue.id }).restore.post();++ const [restored, archived] = await payloads(asOwner, id);+ expect(archived.data.archivedAt).not.toBeNull();+ expect(restored.data.archivedAt).toBeNull();+ });++ it('fires issue.state_changed for the issues a deleted column moves', async () => {+ const { asOwner, columns } = await setupOwnerProject();+ const [from, to] = columns.filter((c) => c.stateType !== 'backlog');+ const id = await createWebhook(asOwner, ['issue.state_changed']);+ const issue = (+ await asOwner+ .projects({ projectKey: 'MKT' })+ .issues.post({ columnId: from.id, title: 'Task' })+ ).data!;++ await asOwner+ .projects({ projectKey: 'MKT' })+ .columns({ columnId: from.id })+ .delete({ mode: 'move', targetColumnId: to.id });++ const [payload] = await payloads(asOwner, id);+ expect(payload.data).toMatchObject({ id: issue.id, state: { id: to.id } });+ });++ it('fires issue.deleted for the issues a deleted column removes', async () => {+ const { asOwner, columns } = await setupOwnerProject();+ const column = columns.find((c) => c.stateType !== 'backlog')!;+ const id = await createWebhook(asOwner, ['issue.deleted']);+ const issue = (+ await asOwner+ .projects({ projectKey: 'MKT' })+ .issues.post({ columnId: column.id, title: 'Task' })+ ).data!;++ await asOwner+ .projects({ projectKey: 'MKT' })+ .columns({ columnId: column.id })+ .delete({ mode: 'delete' });++ const [payload] = await payloads(asOwner, id);+ expect(payload.data).toMatchObject({+ id: issue.id,+ title: 'Task',+ state: { id: column.id, name: column.name },+ });+ });+ });+describe('access', () => {it('returns 404 for an unknown project', async () => {const { asOwner } = await setupOwnerProject();diff --git a/apps/api/src/modules/webhooks/emit.ts b/apps/api/src/modules/webhooks/emit.tsindex 9864bd4a..f2382933 100644--- a/apps/api/src/modules/webhooks/emit.ts+++ b/apps/api/src/modules/webhooks/emit.ts@@ -1,6 +1,7 @@import { randomUUID } from 'node:crypto';-import { db, webhook, webhookDelivery } from '@repo/db';+import { aiAgent, db, user, webhook, webhookDelivery } from '@repo/db';import { and, eq, sql } from 'drizzle-orm';+import type { ActivityActor } from '#modules/issues/activity';import type { WebhookEventType } from './service';// Maps our granular event type to the Linear-style envelope's action + resource@@ -21,37 +22,30 @@ const EVENT_SHAPE: Record<WebhookEventType, { action: string; type: string }> ='comment.deleted': { action: 'remove', type: 'Comment' },};-// Fan-out for outgoing webhooks. Queues one delivery per active webhook of the-// project that subscribes to eventType. The deliveries share one eventId, which stays-// the same across retries so a receiver can deduplicate. Call it right after a domain-// mutation, next to the activity log, the same way the issue service handles its other-// post-write side effects. It does nothing when no webhook matches, so a project with-// no webhooks pays one indexed SELECT.-//-// The body follows Linear's webhook envelope: top-level action, type, data, plus-// createdAt and webhookTimestamp (epoch ms). `event` is our extension, and it carries-// the granular event type. We omit organizationId and url, because there is no-// organization concept and issues have no public URL. The shared dedup id goes in the-// X-Itsaplan-Event-Id header, not in the body.-export async function emitWebhookEvent(- projectId: number,- eventType: WebhookEventType,- data: unknown,-): Promise<void> {- await emitWebhookEvents(projectId, eventType, () => Promise.resolve([data]));+// Who caused the event. An agent acts through its own bot user, so a user id is an+// agent when an ai_agent row points at it. A system write has no user: it carries+// the system's name ('GitHub', 'Auto-archive'), or null for an unnamed one.+interface WebhookActor {+ type: 'human' | 'agent' | 'system';+ id: string | null;+ name: string | null;}-// Several events of one type at once. It builds the payloads only after it finds a-// subscribed webhook. Use it for a write whose payload costs its own queries to-// build: linking two issues has to load both of them. A project with no webhook then-// pays one indexed SELECT and nothing else. Each event gets its own eventId. The-// deliveries go in as one insert.-export async function emitWebhookEvents(- projectId: number,- eventType: WebhookEventType,- load: () => Promise<unknown[]>,-): Promise<void> {- const matching = await db+async function resolveActor(actor: ActivityActor): Promise<WebhookActor> {+ if (!actor) return { type: 'system', id: null, name: null };+ if (typeof actor === 'object') return { type: 'system', id: null, name: actor.system };+ const [row] = await db+ .select({ name: user.name, agentId: aiAgent.id })+ .from(user)+ .leftJoin(aiAgent, eq(aiAgent.userId, user.id))+ .where(eq(user.id, actor))+ .limit(1);+ return { type: row?.agentId != null ? 'agent' : 'human', id: actor, name: row?.name ?? null };+}++// The active webhooks of the project that subscribe to eventType.+export function subscribedWebhooks(projectId: number, eventType: WebhookEventType) {+ return db.select({ id: webhook.id }).from(webhook).where(@@ -62,12 +56,34 @@ export async function emitWebhookEvents(sql`${webhook.events} @> ${JSON.stringify([eventType])}::jsonb`,),);+}++// Fan-out for outgoing webhooks. Queues one delivery per active webhook of the+// project that subscribes to eventType, for each payload `load` returns. Each event+// gets its own eventId, shared by its deliveries and kept across retries so a+// receiver can deduplicate; the deliveries go in as one insert. Call it right after a+// domain mutation, next to the activity log. The payloads are built only after a+// subscribed webhook is found, so a project with no webhooks pays one indexed SELECT.+//+// The body follows Linear's webhook envelope: top-level action, type, actor, data,+// plus createdAt and webhookTimestamp (epoch ms). `event` is our extension, and it+// carries the granular event type. We omit organizationId, because there is no+// organization concept. The shared dedup id goes in the X-Itsaplan-Event-Id header,+// not in the body.+export async function emitWebhookEvents(+ projectId: number,+ eventType: WebhookEventType,+ load: () => Promise<unknown[]>,+ actor: ActivityActor,+): Promise<void> {+ const matching = await subscribedWebhooks(projectId, eventType);if (matching.length === 0) return;const payloads = await load();if (payloads.length === 0) return;const { action, type } = EVENT_SHAPE[eventType];+ const resolvedActor = await resolveActor(actor);const now = new Date();const createdAt = now.toISOString();const webhookTimestamp = now.getTime();@@ -83,6 +99,7 @@ export async function emitWebhookEvents(action,type,event: eventType,+ actor: resolvedActor,createdAt,data,webhookTimestamp,diff --git a/apps/api/src/modules/webhooks/service.ts b/apps/api/src/modules/webhooks/service.tsindex 4ff48156..9323c36a 100644--- a/apps/api/src/modules/webhooks/service.ts+++ b/apps/api/src/modules/webhooks/service.ts@@ -9,12 +9,12 @@ import { iso } from '#shared/lib';// The delivery side is separate.// The event types a subscription can select. Keep this list in sync with the events-// the delivery side emits (modules/issues/service.ts, activity.ts, links.ts) and-// with the frontend list (apps/web src/lib/api/endpoints/webhooks.ts).+// emitted through modules/issues/webhook-payload.ts and with the frontend list+// (apps/web src/lib/api/endpoints/webhooks.ts).//-// issue.updated fires on any field change. The granular issue.assigned,-// issue.state_changed, and issue.label_changed fire in addition, and only when that-// specific field changes on an existing issue. issue.state_changed fires when the+// issue.updated fires on any field change, archiving and restoring included. The+// granular issue.assigned, issue.state_changed, and issue.label_changed fire in+// addition, and only when that specific field changes on an existing issue. issue.state_changed fires when the// issue moves to a different state (column). issue.link_changed fires for both issues// of an added or removed relation, and without issue.updated: no field of either// issue changed.diff --git a/apps/worker/src/delivery.ts b/apps/worker/src/delivery.tsindex 2bee18f1..f636c088 100644--- a/apps/worker/src/delivery.ts+++ b/apps/worker/src/delivery.ts@@ -52,6 +52,9 @@ export async function deliver(input: DeliverInput): Promise<DeliveryResult> {'X-Itsaplan-Signature': signature,},body: input.body,+ // Only a prefix is kept, so the rest is never read; a UTF-8 char is at most 4 bytes.+ maxBytes: MAX_RESPONSE_CHARS * 4,+ truncateBody: true,});const responseBody = (await res.text().catch(() => '')).slice(0, MAX_RESPONSE_CHARS);if (res.status >= 200 && res.status < 300)