Skip to content

⭐️⭐️⭐️ 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.

feat: agent_run.finished webhook event when an agent run ends (#741)

Croff30e31d5cc923
diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md
index a91d45de..0e64764b 100644
--- a/apps/api/AGENTS.md
+++ b/apps/api/AGENTS.md
@@ -317,8 +317,10 @@ undoes one.
- `setRunRefusal` (`modules/agents/core/run-refusal.ts`): whether an internal agent works
at all, asked in the poller before a queued run starts and in `prepareRun` before a chat
answer. A reason fails the run without a retry, and answers the chat with 403.
-- `onProjectEvent` (`modules/webhooks/emit.ts`): every issue and comment event the
- webhooks get, inside the request that caused it.
+- `onProjectEvent` (`modules/webhooks/emit.ts`): every event the webhooks get, inside the
+ request or the run that caused it: the issues and comments, and `agent_run.finished`
+ once a run ends, whose `emitRunsCanceled` (`modules/agents/core/run-finished.ts`)
+ serves a build that cancels runs of its own.
- `setRequestTracker` (`shared/request-tracker.ts`): every request, with its declared
route, params and body, before the guards run; a request it follows gets its status,
its account and the handler's value back after the handler, before the answer is sent,
diff --git a/apps/api/src/modules/agents/core/__tests__/integration/run-finished.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/run-finished.test.ts
new file mode 100644
index 00000000..96dbcd35
--- /dev/null
+++ b/apps/api/src/modules/agents/core/__tests__/integration/run-finished.test.ts
@@ -0,0 +1,167 @@
+import { describe, it, expect, beforeEach } from 'bun:test';
+import { db, agentRun } from '@repo/db';
+import { eq } from 'drizzle-orm';
+import { apiKeyApi, authedApi, createProject } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { createAgent } from '#tests/helpers/agents';
+import { onProjectEvent, type ProjectEvent } from '#modules/webhooks/emit';
+import { enqueueAgentRun, markRunFailed, markRunSuccess } from '../../run-queue';
+
+// 'agent_run.finished': the end of a run, for the webhooks and the api's extensions.
+
+async function setup() {
+ const owner = await signUpTestUser({ name: 'Owner' });
+ const asOwner = authedApi(owner.cookie);
+ const projectId = (await createProject(asOwner, { key: 'MKT', name: 'Marketing' })).data!.id;
+ const columnId = (await asOwner.projects({ projectKey: 'MKT' }).get()).data!.columns[0].id;
+ return { owner, asOwner, projectId, columnId };
+}
+
+// The run events a listener gets while `body` runs, with their payloads.
+async function heard(body: () => Promise<void>) {
+ const events: (Omit<ProjectEvent, 'load'> & { payloads: unknown[] })[] = [];
+ const off = onProjectEvent(async ({ load, ...event }) => {
+ if (event.type === 'agent_run.finished') events.push({ ...event, payloads: await load() });
+ });
+ try {
+ await body();
+ } finally {
+ off();
+ }
+ return events;
+}
+
+describe('agent_run.finished', () => {
+ beforeEach(resetDb);
+
+ it("tells listeners and webhooks how an agent's run ended, once", async () => {
+ const { asOwner, projectId, columnId } = await setup();
+ const agent = (
+ await createAgent(asOwner, 'MKT', { name: 'Bot', username: 'bot', kind: 'internal' })
+ ).data!.agent;
+ const issue = (
+ await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Task' })
+ ).data!;
+ const hook = (
+ await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
+ url: 'https://example.com/hook',
+ events: ['agent_run.finished'],
+ })
+ ).data!.id;
+ await enqueueAgentRun({
+ agentId: agent.id,
+ projectId,
+ issueId: issue.id,
+ sourceActivityId: null,
+ prompt: 'do it',
+ });
+ const [run] = await db.select().from(agentRun).where(eq(agentRun.issueId, issue.id));
+
+ const events = await heard(async () => {
+ await markRunSuccess(run.id, 'Done.', { inputTokens: 10, outputTokens: 2 });
+ await markRunFailed(run.id, 'too late');
+ });
+
+ expect(events).toEqual([
+ {
+ projectId,
+ type: 'agent_run.finished',
+ actor: agent.userId,
+ payloads: [
+ expect.objectContaining({
+ id: run.id,
+ status: 'success',
+ trigger: 'delegation',
+ agent: { id: agent.id, userId: agent.userId, username: 'bot', name: 'Bot' },
+ projectId,
+ issueId: issue.id,
+ issueIdentifier: `MKT-${issue.sequenceNumber}`,
+ error: null,
+ inputTokens: 10,
+ outputTokens: 2,
+ }),
+ ],
+ },
+ ]);
+ const deliveries = (await asOwner.webhooks({ webhookId: hook }).deliveries.get()).data!.items;
+ expect(deliveries.map((d) => d.payload)).toEqual([
+ expect.objectContaining({
+ action: 'update',
+ type: 'AgentRun',
+ event: 'agent_run.finished',
+ actor: { type: 'agent', id: agent.userId, name: 'Bot' },
+ data: expect.objectContaining({ id: run.id, status: 'success' }),
+ }),
+ ]);
+ expect((deliveries[0]!.payload as { data: object }).data).not.toHaveProperty('output');
+ });
+
+ it("sends how an external agent's run ended", async () => {
+ const { asOwner, columnId } = await setup();
+ const created = (
+ await createAgent(asOwner, 'MKT', {
+ name: 'Ext',
+ username: 'ext',
+ kind: 'external',
+ triggerOnMention: true,
+ })
+ ).data!;
+ const asRunner = apiKeyApi(created.apiKey!);
+ const issue = (
+ await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Task' })
+ ).data!;
+ await asOwner.issues({ issueId: issue.id }).comments.post({ body: 'look @ext' });
+ const run = (await asRunner['agent-runs'].claim.post()).data!.run!;
+
+ const events = await heard(async () => {
+ await asRunner['agent-runs']({ runId: run.id }).result.post({
+ status: 'failed',
+ error: 'exit 1',
+ });
+ });
+
+ expect(events.map((e) => [e.actor, e.payloads])).toEqual([
+ [
+ created.agent.userId,
+ [
+ expect.objectContaining({
+ id: run.id,
+ status: 'failed',
+ trigger: 'mention',
+ error: 'exit 1',
+ }),
+ ],
+ ],
+ ]);
+ });
+
+ it('names who canceled the runs', async () => {
+ const { owner, asOwner } = await setup();
+ const agent = (
+ await createAgent(asOwner, 'MKT', { name: 'Hook', username: 'hook', kind: 'external' })
+ ).data!.agent;
+ const schedules = asOwner.projects({ projectKey: 'MKT' })['agent-schedules'];
+ const scheduleId = (
+ await schedules.post({
+ agentId: agent.id,
+ name: 'Daily',
+ prompt: 'Triage.',
+ cron: '0 9 * * *',
+ })
+ ).data!.id;
+ await schedules({ scheduleId }).run.post();
+ await schedules({ scheduleId }).run.post();
+
+ const events = await heard(async () => {
+ await schedules({ scheduleId }).runs.cancel.post();
+ });
+
+ expect(events).toHaveLength(1);
+ expect(events[0].actor).toBe(owner.userId);
+ expect(events[0].payloads).toEqual([
+ expect.objectContaining({ status: 'canceled', scheduleId, trigger: 'manual', issueId: null }),
+ expect.objectContaining({ status: 'canceled', scheduleId, trigger: 'manual', issueId: null }),
+ ]);
+ });
+});
diff --git a/apps/api/src/modules/agents/core/run-finished.ts b/apps/api/src/modules/agents/core/run-finished.ts
new file mode 100644
index 00000000..8e7e6a79
--- /dev/null
+++ b/apps/api/src/modules/agents/core/run-finished.ts
@@ -0,0 +1,107 @@
+import { agentRun, aiAgent, db, issue, project, user } from '@repo/db';
+import { eq, inArray } from 'drizzle-orm';
+import { alias } from 'drizzle-orm/pg-core';
+import type { ActivityActor } from '#modules/issues/activity';
+import { emitWebhookEvents } from '#modules/webhooks/emit';
+
+// 'agent_run.finished', for the webhooks and the api's extensions: one event per project
+// and actor with a payload per run, once the run is success, failed or canceled. A run deleted
+// with its agent, issue or project sends none. The payload leaves out what the agent
+// returned: whoever sets up a webhook may not read the agents, and the run's trace is
+// served to those who do.
+
+// Runs their agent ended, which is also the event's actor.
+export function emitRunsFinished(runIds: number[]): Promise<void> {
+ return emitEnded(runIds, (agentUserId) => agentUserId);
+}
+
+// Runs someone ended before their agent did.
+export function emitRunsCanceled(runIds: number[], actor: ActivityActor): Promise<void> {
+ return emitEnded(runIds, () => actor);
+}
+
+async function emitEnded(
+ runIds: number[],
+ actorOf: (agentUserId: string) => ActivityActor,
+): Promise<void> {
+ if (runIds.length === 0) return;
+ const groups = new Map<string, { projectId: number; actor: ActivityActor; runs: EndedRun[] }>();
+ for (const row of await selectRuns(runIds)) {
+ const actor = actorOf(row.agentUserId);
+ const key = `${row.projectId}:${JSON.stringify(actor ?? null)}`;
+ const group = groups.get(key) ?? { projectId: row.projectId, actor, runs: [] };
+ group.runs.push(row);
+ groups.set(key, group);
+ }
+ for (const { projectId, actor, runs } of groups.values()) {
+ await emitWebhookEvents(
+ projectId,
+ 'agent_run.finished',
+ async () => runs.map(runPayload),
+ actor,
+ );
+ }
+}
+
+// An issue moved to another project keeps its runs in the project they worked in.
+const issueProject = alias(project, 'issue_project');
+
+function selectRuns(runIds: number[]) {
+ return db
+ .select({
+ id: agentRun.id,
+ status: agentRun.status,
+ trigger: agentRun.trigger,
+ agentId: agentRun.agentId,
+ agentUserId: aiAgent.userId,
+ agentUsername: aiAgent.username,
+ agentName: user.name,
+ projectId: agentRun.projectId,
+ issueProjectKey: issueProject.key,
+ issueId: agentRun.issueId,
+ issueNumber: issue.sequenceNumber,
+ documentId: agentRun.documentId,
+ scheduleId: agentRun.scheduleId,
+ error: agentRun.lastError,
+ attempts: agentRun.attempts,
+ inputTokens: agentRun.inputTokens,
+ outputTokens: agentRun.outputTokens,
+ createdAt: agentRun.createdAt,
+ startedAt: agentRun.startedAt,
+ finishedAt: agentRun.finishedAt,
+ })
+ .from(agentRun)
+ .innerJoin(aiAgent, eq(aiAgent.id, agentRun.agentId))
+ .innerJoin(user, eq(user.id, aiAgent.userId))
+ .leftJoin(issue, eq(issue.id, agentRun.issueId))
+ .leftJoin(issueProject, eq(issueProject.id, issue.projectId))
+ .where(inArray(agentRun.id, runIds));
+}
+
+type EndedRun = Awaited<ReturnType<typeof selectRuns>>[number];
+
+function runPayload(row: EndedRun) {
+ return {
+ id: row.id,
+ status: row.status,
+ trigger: row.trigger,
+ agent: {
+ id: row.agentId,
+ userId: row.agentUserId,
+ username: row.agentUsername,
+ name: row.agentName,
+ },
+ projectId: row.projectId,
+ issueId: row.issueId,
+ issueIdentifier: row.issueNumber == null ? null : `${row.issueProjectKey}-${row.issueNumber}`,
+ documentId: row.documentId,
+ scheduleId: row.scheduleId,
+ error: row.error,
+ attempts: row.attempts,
+ inputTokens: row.inputTokens,
+ outputTokens: row.outputTokens,
+ createdAt: row.createdAt.toISOString(),
+ startedAt: row.startedAt?.toISOString() ?? null,
+ finishedAt: row.finishedAt?.toISOString() ?? null,
+ };
+}
diff --git a/apps/api/src/modules/agents/core/run-queue.ts b/apps/api/src/modules/agents/core/run-queue.ts
index 910a431f..c795f068 100644
--- a/apps/api/src/modules/agents/core/run-queue.ts
+++ b/apps/api/src/modules/agents/core/run-queue.ts
@@ -28,6 +28,7 @@ import { getAgentSettings } from '#modules/settings/service';
import { intEnv, iso } from '#shared/lib';
import type { AgentRunTrigger } from '../model';
import { equalJitterBackoffMs } from './helpers/backoff';
+import { emitRunsFinished } from './run-finished';
// The agent_run outbox: data access for triggered runs and run history. The api's
// run poller claims pending rows, runs them, and records the outcome.
@@ -417,7 +418,7 @@ export async function markRunSuccess(
output: string,
usage: { inputTokens: number; outputTokens: number } | null,
): Promise<void> {
- await db
+ const rows = await db
.update(agentRun)
.set({
status: 'success',
@@ -428,7 +429,9 @@ export async function markRunSuccess(
outputTokens: usage?.outputTokens ?? null,
finishedAt: new Date(),
})
- .where(and(eq(agentRun.id, id), eq(agentRun.status, 'pending')));
+ .where(and(eq(agentRun.id, id), eq(agentRun.status, 'pending')))
+ .returning({ id: agentRun.id });
+ await emitRunsFinished(rows.map((row) => row.id));
}
export async function scheduleRunRetry(id: number, delayMs: number, error: string): Promise<void> {
@@ -446,7 +449,7 @@ export async function scheduleRunRetry(id: number, delayMs: number, error: strin
}
export async function markRunFailed(id: number, error: string, output?: string): Promise<void> {
- await db
+ const rows = await db
.update(agentRun)
.set({
status: 'failed',
@@ -455,7 +458,9 @@ export async function markRunFailed(id: number, error: string, output?: string):
...(output ? { output } : {}),
finishedAt: new Date(),
})
- .where(and(eq(agentRun.id, id), eq(agentRun.status, 'pending')));
+ .where(and(eq(agentRun.id, id), eq(agentRun.status, 'pending')))
+ .returning({ id: agentRun.id });
+ await emitRunsFinished(rows.map((row) => row.id));
}
// Puts a claimed run back in the queue without spending the attempt, for a run the
diff --git a/apps/api/src/modules/agents/runner/service.ts b/apps/api/src/modules/agents/runner/service.ts
index 01c8892b..3cab6fe1 100644
--- a/apps/api/src/modules/agents/runner/service.ts
+++ b/apps/api/src/modules/agents/runner/service.ts
@@ -12,6 +12,7 @@ import {
scheduleRunRetry,
} from '../core/run-queue';
import { agentRunStarted, recordAgentRunFinished } from '../core/run-activity';
+import { emitRunsFinished } from '../core/run-finished';
import { runAdmissionDelay } from '../core/run-admission';
import type { AgentKind } from '../core/service';
import type { AgentRunTrigger } from '../model';
@@ -146,9 +147,10 @@ async function expireExhaustedRuns(agent: RunnerAgent): Promise<void> {
sql`${agentRun.nextAttemptAt} <= now()`,
),
)
- .returning({ issueId: agentRun.issueId });
+ .returning({ id: agentRun.id, issueId: agentRun.issueId });
for (const row of rows)
await recordAgentRunFinished({ ...row, agentUserId: agent.userId }, 'failed');
+ await emitRunsFinished(rows.map((row) => row.id));
}
// An agent with an invocation URL is sent its work, so a runner that claims as well
@@ -333,9 +335,10 @@ export async function finishRun(
result.attempt == null ? undefined : eq(agentRun.attempts, result.attempt),
),
)
- .returning({ issueId: agentRun.issueId });
+ .returning({ id: agentRun.id, issueId: agentRun.issueId });
const row = rows[0];
if (!row) return false;
await recordAgentRunFinished({ ...row, agentUserId: agent.userId }, result.status);
+ await emitRunsFinished([row.id]);
return true;
}
diff --git a/apps/api/src/modules/agents/schedules/issue-runs.ts b/apps/api/src/modules/agents/schedules/issue-runs.ts
index 986ceb8c..55bac138 100644
--- a/apps/api/src/modules/agents/schedules/issue-runs.ts
+++ b/apps/api/src/modules/agents/schedules/issue-runs.ts
@@ -1,5 +1,6 @@
import { db, agentRun, agentSchedule, aiAgent, issue, project, projectColumn } from '@repo/db';
import { and, eq, inArray, ne, notInArray, sql } from 'drizzle-orm';
+import { emitRunsCanceled } from '../core/run-finished';
import { filterScheduleIssues, isScheduleSupported, type ScheduleForExtension } from './extension';
// The runs schedules queue on issues: a 'status' schedule's when an issue enters its
@@ -41,7 +42,7 @@ export async function queueStatusRuns(
actorUserId: string | null | undefined,
): Promise<void> {
if (issueIds.length === 0) return;
- await db
+ const canceled = await db
.update(agentRun)
.set({ status: 'canceled', executionStartedAt: null, finishedAt: new Date() })
.where(
@@ -55,7 +56,12 @@ export async function queueStatusRuns(
where ${agentSchedule.columnId} <> ${columnId}
)`,
),
- );
+ )
+ .returning({ id: agentRun.id });
+ await emitRunsCanceled(
+ canceled.map((row) => row.id),
+ actorUserId,
+ );
const schedules = await db
.select({ ...scheduleFields, columnName: projectColumn.name })
diff --git a/apps/api/src/modules/agents/schedules/service.ts b/apps/api/src/modules/agents/schedules/service.ts
index a375836a..2637b24d 100644
--- a/apps/api/src/modules/agents/schedules/service.ts
+++ b/apps/api/src/modules/agents/schedules/service.ts
@@ -6,6 +6,7 @@ import { minCronIntervalSeconds, nextCronRun } from './cron';
import { isScheduleSupported, type ScheduleOptions } from './extension';
import { agentWorksInProject, canTriggerAgent, isTriggerableBy } from '../core/service';
import { contextTokensOf, executionState } from '../core/run-queue';
+import { emitRunsCanceled } from '../core/run-finished';
import { deleteThreadsWhere } from '../core/runtime/memory';
export type AgentScheduleStatus = 'active' | 'paused';
@@ -370,6 +371,10 @@ export async function cancelPendingScheduleRuns(
),
)
.returning({ id: agentRun.id });
+ await emitRunsCanceled(
+ rows.map((row) => row.id),
+ actorUserId,
+ );
return rows.length;
}
diff --git a/apps/api/src/modules/issues/move.ts b/apps/api/src/modules/issues/move.ts
index 8cd105ee..88d238d9 100644
--- a/apps/api/src/modules/issues/move.ts
+++ b/apps/api/src/modules/issues/move.ts
@@ -27,6 +27,7 @@ import { recordStatusChange } from './status-history';
import { recordCycleChange } from './cycle-history';
import { emitIssueEvent } from './webhook-payload';
import { queueStatusRuns } from '#modules/agents/schedules/issue-runs';
+import { emitRunsCanceled } from '#modules/agents/core/run-finished';
// Moves an issue, with its subtasks, to another project of the same team. Column,
// type, labels and custom fields belong to one project, so they are matched by name
@@ -116,7 +117,7 @@ export async function moveIssue(
const labels = await mapLabels(movedIds, target.id);
const fields = await mapFields(movedIds, target.id);
- await db.transaction(async (tx) => {
+ const canceledRuns = await db.transaction(async (tx) => {
// Everything above was read without a lock. A concurrent move of the same issue, or
// a subtask added since, would otherwise write over that state.
const [locked] = await tx
@@ -209,11 +210,16 @@ export async function moveIssue(
.where(
and(inArray(issueWatcher.issueId, movedIds), notInArray(issueWatcher.userId, [...members])),
);
- await tx
+ return tx
.update(agentRun)
.set({ status: 'canceled', executionStartedAt: null, finishedAt: sql`now()` })
- .where(and(inArray(agentRun.issueId, movedIds), eq(agentRun.status, 'pending')));
+ .where(and(inArray(agentRun.issueId, movedIds), eq(agentRun.status, 'pending')))
+ .returning({ id: agentRun.id });
});
+ await emitRunsCanceled(
+ canceledRuns.map((run) => run.id),
+ actorUserId,
+ );
for (const p of plans) {
await recordStatusChange([p.id], p.newColumnId);
diff --git a/apps/api/src/modules/webhooks/emit.ts b/apps/api/src/modules/webhooks/emit.ts
index 3d96eabc..b4511e03 100644
--- a/apps/api/src/modules/webhooks/emit.ts
+++ b/apps/api/src/modules/webhooks/emit.ts
@@ -20,6 +20,7 @@ const EVENT_SHAPE: Record<WebhookEventType, { action: string; type: string }> =
'comment.created': { action: 'create', type: 'Comment' },
'comment.updated': { action: 'update', type: 'Comment' },
'comment.deleted': { action: 'remove', type: 'Comment' },
+ 'agent_run.finished': { action: 'update', type: 'AgentRun' },
};
// Who caused the event. An agent acts through its own bot user, so a user id is an
@@ -47,7 +48,7 @@ export interface ProjectEvent {
projectId: number;
type: WebhookEventType;
actor: ActivityActor;
- // The event's webhook payloads (`data`), one per issue or comment it covers. Built on
+ // The event's webhook payloads (`data`), one per issue, comment or run it covers. Built on
// the first call and shared with the webhooks.
load: () => Promise<unknown[]>;
}
@@ -56,8 +57,8 @@ type ProjectEventListener = (event: ProjectEvent) => Promise<void>;
const listeners: ProjectEventListener[] = [];
-// Hands the events the webhooks get to an extension of the api, inside the request
-// that caused them. A listener that throws is logged and does not fail that request.
+// Hands the events the webhooks get to an extension of the api, inside the request or
+// the run that caused them. A listener that throws is logged and does not fail it.
// Returns the call that removes the listener.
export function onProjectEvent(listener: ProjectEventListener): () => void {
listeners.push(listener);
diff --git a/apps/api/src/modules/webhooks/service.ts b/apps/api/src/modules/webhooks/service.ts
index 9323c36a..bdff144c 100644
--- a/apps/api/src/modules/webhooks/service.ts
+++ b/apps/api/src/modules/webhooks/service.ts
@@ -9,8 +9,8 @@ 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
-// emitted through modules/issues/webhook-payload.ts and with the frontend list
-// (apps/web src/lib/api/endpoints/webhooks.ts).
+// emitted through modules/issues/webhook-payload.ts and modules/agents/core/run-finished.ts,
+// and with the frontend list (apps/web src/lib/api/endpoints/webhooks.ts).
//
// issue.updated fires on any field change, archiving and restoring included. The
// granular issue.assigned, issue.state_changed, and issue.label_changed fire in
@@ -32,6 +32,9 @@ export const WEBHOOK_EVENT_TYPES = [
// again for the replies a delete takes with it.
'comment.updated',
'comment.deleted',
+ // A run of an agent in the project ended: success, failed or canceled. Its payload is
+ // the run (modules/agents/core/run-finished.ts).
+ 'agent_run.finished',
] as const;
export type WebhookEventType = (typeof WEBHOOK_EVENT_TYPES)[number];
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 78ad8e10..847d9eed 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -27,12 +27,14 @@ Next.js App Router, SSR (not SPA). Tailwind v4 + shadcn/ui. See root `AGENTS.md`
group, each in the order given.
`/workspaces/:id` names no section and opens the first entry of the menu, so the order
also decides the page a workspace opens on.
- `useProjectSettingsSections(project, core)` returns the project settings sidebar: here the
- core's sections, while the hosted build adds its own at any position or drops some. The
- sidebar lists the groups in the order their first section comes, each named in
+ `useProjectSettingsSections(project, core)` returns the project's sections: here the
+ core's, while the hosted build adds its own at any position or drops some. Those of the
+ `ai-team` group are listed in the main sidebar's AI Team group, the others in the settings
+ sidebar, which lists the groups in the order their first section comes, each named in
`nav.groups.<group>`, so a section can open a group of its own. One the build adds
- carries in `Component` the page `/:team/:projectKey/settings/<slug>` opens, which answers
- 404 only once the project and every query in flight have loaded.
+ carries in `Component` the page `/:team/:projectKey/settings/<slug>` opens, or
+ `/:team/:projectKey/agents/<slug>` in the AI Team group, which answers 404 only once the
+ project and every query in flight have loaded.
`NoTeamStart` is the start page of an account with no team and no workspace it owns,
which happens while personal workspaces are off; here it says who adds them.
`WorkspaceRailActions` sits below the workspace tiles of a rail; here it says where more
diff --git a/apps/web/src/app/[teamRef]/(shell)/[projectKey]/agents/[section]/page.tsx b/apps/web/src/app/[teamRef]/(shell)/[projectKey]/agents/[section]/page.tsx
new file mode 100644
index 00000000..0a6e21e7
--- /dev/null
+++ b/apps/web/src/app/[teamRef]/(shell)/[projectKey]/agents/[section]/page.tsx
@@ -0,0 +1,9 @@
+'use client';
+
+import { useParams } from 'next/navigation';
+import SettingsExtraSectionPage from '@/features/settings/SettingsExtraSectionPage';
+
+export default function Page() {
+ const { section } = useParams<{ section: string }>();
+ return <SettingsExtraSectionPage slug={section} aiTeam />;
+}
diff --git a/apps/web/src/components/layout/ShellHeaderTitle.tsx b/apps/web/src/components/layout/ShellHeaderTitle.tsx
index e24ae708..06af4f83 100644
--- a/apps/web/src/components/layout/ShellHeaderTitle.tsx
+++ b/apps/web/src/components/layout/ShellHeaderTitle.tsx
@@ -1,9 +1,8 @@
import { useTranslations } from 'next-intl';
-import { AI_TEAM_SECTIONS } from '@/utils/settingsSections';
import type { IssueRef } from '@/lib/api/endpoints/issues';
import type { ShellRoute } from '@/hooks/useShellRoute';
import { useSettingsSectionText } from '@/hooks/useSectionLabels';
-import { useSettingsSections } from '@/hooks/useSettingsNavGroups';
+import { useProjectSections } from '@/hooks/useSettingsNavGroups';
import CycleBreadcrumb from '@/components/layout/CycleBreadcrumb';
import InitiativeBreadcrumb from '@/components/layout/InitiativeBreadcrumb';
import IssueBreadcrumb from '@/components/layout/IssueBreadcrumb';
@@ -23,7 +22,7 @@ export default function ShellHeaderTitle({
}) {
const t = useTranslations('nav');
const sectionText = useSettingsSectionText();
- const sections = [...useSettingsSections(), ...AI_TEAM_SECTIONS];
+ const sections = useProjectSections();
// The label on the pages that are not an issue, initiative or cycle detail. An
// /agents/:section route names its section.
diff --git a/apps/web/src/components/layout/SidebarAiTeamNav.tsx b/apps/web/src/components/layout/SidebarAiTeamNav.tsx
index 44ea1ef0..9249f38c 100644
--- a/apps/web/src/components/layout/SidebarAiTeamNav.tsx
+++ b/apps/web/src/components/layout/SidebarAiTeamNav.tsx
@@ -1,7 +1,8 @@
import { usePathname } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { aiAgentsPath, aiTeamPath } from '@/utils/paths';
-import { AI_AGENTS_SECTION, AI_TEAM_SECTIONS } from '@/utils/settingsSections';
+import { AI_AGENTS_SECTION } from '@/utils/settingsSections';
+import { useAiTeamSections } from '@/hooks/useSettingsNavGroups';
import { usePermissions } from '@/hooks/usePermissions';
import { useShellRoute } from '@/hooks/useShellRoute';
import { useSettingsSectionText } from '@/hooks/useSectionLabels';
@@ -24,7 +25,7 @@ export default function SidebarAiTeamNav({ projectKey }: { projectKey: string |
const disabled = !projectKey;
// The run list also opens to whoever runs the team, as its route does.
- const sections = AI_TEAM_SECTIONS.filter(
+ const sections = useAiTeamSections().filter(
(s) => can(s.resource, 'read') || (s.slug === 'queue' && isAdmin),
);
const showAgents = can(AI_AGENTS_SECTION.resource, 'read');
diff --git a/apps/web/src/features/settings/SettingsExtraSectionPage.tsx b/apps/web/src/features/settings/SettingsExtraSectionPage.tsx
index a049ec0f..958fa860 100644
--- a/apps/web/src/features/settings/SettingsExtraSectionPage.tsx
+++ b/apps/web/src/features/settings/SettingsExtraSectionPage.tsx
@@ -3,14 +3,23 @@
import { useIsFetching } from '@tanstack/react-query';
import { notFound } from 'next/navigation';
import { useShell } from '@/context/shellContext';
-import { useSettingsSections } from '@/hooks/useSettingsNavGroups';
+import { useProjectSections } from '@/hooks/useSettingsNavGroups';
-// A project settings section without a route of its own: one the hosted build adds. Its
-// sections can depend on queries of their own, so a link straight to one waits for those
-// to load before it calls the section unknown.
-export default function SettingsExtraSectionPage({ slug }: { slug: string }) {
+// A project section without a route of its own: one the hosted build adds, at
+// /settings/:section or, in the AI Team group, at /agents/:section. Its sections can depend
+// on queries of their own, so a link straight to one waits for those to load before it
+// calls the section unknown.
+export default function SettingsExtraSectionPage({
+ slug,
+ aiTeam = false,
+}: {
+ slug: string;
+ aiTeam?: boolean;
+}) {
const { project } = useShell();
- const Component = useSettingsSections().find((entry) => entry.slug === slug)?.Component;
+ const Component = useProjectSections().find(
+ (entry) => entry.slug === slug && (entry.group === 'ai-team') === aiTeam,
+ )?.Component;
const loading = useIsFetching() > 0;
if (!Component) {
if (!project || loading) return null;
diff --git a/apps/web/src/hooks/useNavigationCommands.tsx b/apps/web/src/hooks/useNavigationCommands.tsx
index 5e3106f3..79a8f143 100644
--- a/apps/web/src/hooks/useNavigationCommands.tsx
+++ b/apps/web/src/hooks/useNavigationCommands.tsx
@@ -29,7 +29,8 @@ import {
projectPath,
} from '@/utils/paths';
import { ACCOUNT_SECTIONS, accountPath } from '@/utils/accountSections';
-import { AI_AGENTS_SECTION, AI_TEAM_SECTIONS } from '@/utils/settingsSections';
+import { AI_AGENTS_SECTION } from '@/utils/settingsSections';
+import { useAiTeamSections } from '@/hooks/useSettingsNavGroups';
import { GOD_SECTIONS } from '@/utils/godSections';
import { usePermissions } from '@/hooks/usePermissions';
import { useProjectFeatures } from '@/hooks/useProjectFeatures';
@@ -54,6 +55,7 @@ export function useNavigationCommands(projectKey: string | null): CommandSection
const accountLabel = useAccountSectionLabel();
const router = useRouter();
const { can, isMember } = usePermissions();
+ const aiTeamSections = useAiTeamSections();
const features = useProjectFeatures();
const { data: session } = useSession();
const { groups } = useSettingsNavGroups(projectKey);
@@ -87,7 +89,7 @@ export function useNavigationCommands(projectKey: string | null): CommandSection
documentsPath(key),
'docs pages documentation',
);
- for (const s of AI_TEAM_SECTIONS) {
+ for (const s of aiTeamSections) {
if (can(s.resource, 'read'))
add(
`nav.ai-team.${s.slug}`,
diff --git a/apps/web/src/hooks/useSettingsNavGroups.ts b/apps/web/src/hooks/useSettingsNavGroups.ts
index 6c766f3b..04530d87 100644
--- a/apps/web/src/hooks/useSettingsNavGroups.ts
+++ b/apps/web/src/hooks/useSettingsNavGroups.ts
@@ -6,7 +6,7 @@ import { useProjectSettingsSections } from '@/cloud';
import { ShellCtx } from '@/context/shellContext';
import { settingsPath } from '@/utils/paths';
import { byKey } from '@/utils/messageKey';
-import { SETTINGS_MENU_SECTIONS, type SettingsSection } from '@/utils/settingsSections';
+import { SETTINGS_SECTIONS, type SettingsSection } from '@/utils/settingsSections';
import { usePermissions } from '@/hooks/usePermissions';
import { useSettingsSectionText } from '@/hooks/useSectionLabels';
import type { ProjectDetail } from '@/lib/api/endpoints/projects';
@@ -31,12 +31,17 @@ export type SettingsNavGroup = {
items: SettingsNavItem[];
};
-// The sections of the settings sidebar, the hosted build's included. `project` is
-// only passed by the Shell, which calls this above its own context provider;
-// everything else reads the project from the context.
-export function useSettingsSections(project?: ProjectDetail | null): SettingsSection[] {
+// Every section of the project, the hosted build's included: those of the settings
+// sidebar and those of the AI Team group. `project` is only passed by the Shell, which
+// calls this above its own context provider; everything else reads the project from the
+// context.
+export function useProjectSections(project?: ProjectDetail | null): SettingsSection[] {
const ctx = useContext(ShellCtx);
- return useProjectSettingsSections(project ?? ctx?.project ?? null, SETTINGS_MENU_SECTIONS);
+ return useProjectSettingsSections(project ?? ctx?.project ?? null, SETTINGS_SECTIONS);
+}
+
+export function useAiTeamSections(): SettingsSection[] {
+ return useProjectSections().filter((s) => s.group === 'ai-team');
}
export function useSettingsNavGroups(
@@ -50,8 +55,8 @@ export function useSettingsNavGroups(
const sectionText = useSettingsSectionText();
const pathname = usePathname();
const { can } = usePermissions(project);
- const sections = useSettingsSections(project).filter((s) =>
- can(s.resource, s.viewAction ?? 'read'),
+ const sections = useProjectSections(project).filter(
+ (s) => s.group !== 'ai-team' && can(s.resource, s.viewAction ?? 'read'),
);
const groups: SettingsNavGroup[] = [...new Set(sections.map((s) => s.group))].map((group) => ({
diff --git a/apps/web/src/hooks/useShellTitle.ts b/apps/web/src/hooks/useShellTitle.ts
index 126072ab..e2eafc55 100644
--- a/apps/web/src/hooks/useShellTitle.ts
+++ b/apps/web/src/hooks/useShellTitle.ts
@@ -1,10 +1,10 @@
import { useTranslations } from 'next-intl';
import type { ProjectDetail } from '@/lib/api/endpoints/projects';
import type { View } from '@/lib/api/endpoints/views';
-import { AI_AGENTS_SECTION, AI_TEAM_SECTIONS } from '@/utils/settingsSections';
+import { AI_AGENTS_SECTION } from '@/utils/settingsSections';
import type { ShellRoute } from '@/hooks/useShellRoute';
import { useSettingsSectionText } from '@/hooks/useSectionLabels';
-import { useSettingsSections } from '@/hooks/useSettingsNavGroups';
+import { useProjectSections } from '@/hooks/useSettingsNavGroups';
import { titlePath, useDocumentTitle } from '@/hooks/useDocumentTitle';
const SECTION_LABELS = {
@@ -32,7 +32,7 @@ export function useShellTitle(
const t = useTranslations('nav');
const tScreens = useTranslations('meta.screens');
const sectionText = useSettingsSectionText();
- const sections = [...useSettingsSections(project), ...AI_TEAM_SECTIONS];
+ const sections = useProjectSections(project);
const known = (slug: string | null): slug is string => sections.some((s) => s.slug === slug);
function sectionParts(): string[] {
diff --git a/apps/web/src/lib/api/endpoints/webhooks.ts b/apps/web/src/lib/api/endpoints/webhooks.ts
index 15c2fc70..7e117808 100644
--- a/apps/web/src/lib/api/endpoints/webhooks.ts
+++ b/apps/web/src/lib/api/endpoints/webhooks.ts
@@ -12,7 +12,8 @@ export type WebhookEventType =
| 'issue.link_changed'
| 'comment.created'
| 'comment.updated'
- | 'comment.deleted';
+ | 'comment.deleted'
+ | 'agent_run.finished';
export const WEBHOOK_EVENT_TYPES: WebhookEventType[] = [
'issue.created',
@@ -25,6 +26,7 @@ export const WEBHOOK_EVENT_TYPES: WebhookEventType[] = [
'comment.created',
'comment.updated',
'comment.deleted',
+ 'agent_run.finished',
];
export interface Webhook {
diff --git a/apps/web/src/utils/paths.ts b/apps/web/src/utils/paths.ts
index a9b29c00..81a1370c 100644
--- a/apps/web/src/utils/paths.ts
+++ b/apps/web/src/utils/paths.ts
@@ -48,7 +48,7 @@ export const documentPath = (ref: string, documentId: number) =>
export const settingsPath = (ref: string, section: string) =>
`${projectPath(ref)}/settings/${section}`;
-// The AI Team destinations listed in the main sidebar (see AI_TEAM_SECTIONS).
+// The AI Team destinations listed in the main sidebar (see useAiTeamSections).
export const aiTeamPath = (ref: string, section: string) => `${projectPath(ref)}/agents/${section}`;
export const runnerQueuePath = (ref: string) => aiTeamPath(ref, 'queue');
diff --git a/apps/web/src/utils/settingsSections.ts b/apps/web/src/utils/settingsSections.ts
index 08d7ee0a..5fc8a176 100644
--- a/apps/web/src/utils/settingsSections.ts
+++ b/apps/web/src/utils/settingsSections.ts
@@ -128,8 +128,7 @@ export const AI_AGENTS_SECTION: SettingsSection = {
group: 'ai',
};
-// The sections the project settings sidebar lists.
-export const SETTINGS_MENU_SECTIONS = SETTINGS_SECTIONS.filter((s) => s.group !== 'ai-team');
+// The core's AI Team sections; useAiTeamSections adds the hosted build's.
export const AI_TEAM_SECTIONS = SETTINGS_SECTIONS.filter((s) => s.group === 'ai-team');
const BY_SLUG = new Map(SETTINGS_SECTIONS.map((s) => [s.slug, s]));