feat(routines): ship the redesigned routine page and let live webhooks be tested again (#22205)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Routines start agent work on a schedule, from a webhook, or on
demand
> - The routine detail page split one routine across eight sections
behind a section sidebar (overview, triggers, variables, secrets,
delivery, runs, activity, history)
> - People had to hunt through sections to see what a routine does and
to change it, and a finished webhook could not be tested again without
starting the routine
> - This pull request makes the approved two-column routine page, one
Edit dialog and one Webhook dialog the real routed page, and lets a live
webhook go back into test mode
> - The benefit is one page that answers what the routine does, when it
runs, who runs it and what it made, with every change in one dialog

## Linked Issues or Issue Description

**Problem**
The routine detail page spreads one routine over eight sections and a
section sidebar. Changing a routine means visiting several sections,
each with its own save bar. A webhook that is already live cannot be
tested again: the API only accepts `setupPending: false`, so testing a
live webhook starts the routine.

**Proposed solution**
Ship the reviewed design (stories `routine-page-design`,
`routine-edit-dialog-design`, `routine-webhook-dialog-design`) as the
routed page in both UI shells, wired to the real API. Let `PATCH
/api/routine-triggers/:id` accept `setupPending: true` for a live
webhook so the next events are checked but never start the routine.

**Alternatives considered**
Keep the sections and restyle them. The owner rejected this: the section
sidebar should go.

## What Changed

- `/routines/:id` renders `RoutinePage` in both shells
(`RoutineDetail.production.tsx` is removed). Status switch, Repeats
rows, default agent, responsible user, project, Asks for, Secrets, Run
rules, Managed by plugin, Instructions with Show all, copy and the
comment count, and History.
- History is paged: 20 tasks per page from `GET
/companies/:id/issues?originKind=routine_execution&originId=…&sortField=created&sortDir=desc&limit=21&offset=…`,
with a real Load more. Coalesced runs show as "folded into a task".
- A failed refetch keeps the loaded page on screen (`useQueryView`); a
History failure shows `QueryErrorState` in place.
- Header: Edit, "…" (Version history, Audit log, Archive / Restore) and
Run now. In the streamlined desktop shell they sit in the breadcrumb
toolbar; elsewhere above the page.
- Version history (`/routines/:id/history`, restore and restored-webhook
keys kept) and Audit log (`/routines/:id/activity`,
`RoutineAuditActivity`) open as sub-views with a way back. Old section
addresses and `?tab=` redirect to `/routines/:id`.
- Edit dialog saves title, instructions, variables, secrets, agent,
project and responsible user in one request against the revision the
dialog opened with (save conflict shows "changed while you were
editing"). The first schedule is created, changed or removed after that.
Priority and delivery settings are never sent, so saved values stay.
- Webhooks are created, changed, tested and removed (with Undo) right
away from the Edit dialog, with the Webhook dialog nested inside it.
Closing the Webhook dialog ends setup or test mode. A webhook left in
test mode shows "Testing · events don’t run" on the page and offers
Finish testing.
- Responsibility (only with `enableResponsibilities`): the page shows
direct and through-project responsibilities from the link lookup; the
dialog links or unlinks the direct one. With the flag off nothing is
fetched or shown.
- The routines list creates routines with the same dialog in create
mode, filed in the open folder, and opens the new routine page.
- Server: `setupPending: true` on a live webhook enters test mode
(planned by a pure `planTriggerUpdate`, which also gives the activity
action) (422 for other trigger kinds; 409 for a disabled or removed
webhook or an archived routine). Test deliveries keep the last real
delivery as `lastWebhookDelivery.previous`, and finishing testing
restores it. Activity `routine.trigger_test_started`.
- Additions to the reviewed design, from review, so no capability is
lost: the schedule popover has Pause/Resume; standing-check and API rows
open a small popover with Pause/Resume and Remove; removing a trigger
from the page leaves a "… removed. Undo" line under Repeats. Stories:
`StandingCheckOpened`, `ScheduleTriggerPaused(Opened)`,
`RemovedWithUndo`.
- Save is several requests (routine, schedule, responsibility). It
changes only the schedule the form opened with, records each finished
step, and a partial failure says what was saved and that saving again
finishes it. The dialog cannot be dismissed while saving. Failed reads
show a Retry state, never empty choices.
- Removed: the routine section sidebar and contextual sidebar, the
trigger wizard, trigger cards, save bar, section components and their
tests.
- Storybook: the three routine stories moved to `stories/routines` as
current production stories, a new story mounts the routed page against a
fixture API, and stories that used the old page were updated or removed.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/routines-e2e.test.ts` (17/17) and
`src/__tests__/routines-service.test.ts` (105/105).
- `pnpm exec vitest run` on the routine page, routines list, routine
form, webhook instructions, Layout, shell navigation, audit and editor
tests: 275 tests pass.
- `cd ui && npx tsc -p tsconfig.json --noEmit`, `node
scripts/check-token-gates.mjs`, `node scripts/check-maps.mjs`, `node
scripts/storybook-catalog.mjs --check`: pass.
- `pnpm verify` exits 2 (global CI input changed); required CI supplies
the broad coverage.
- Manual: an isolated worktree instance (`pnpm paperclipai worktree init
--empty`, `pnpm dev`) with a seeded routine. Headless Playwright: an old
`/triggers` address redirects, no section sidebar, History shows 20 then
23 after Load more, the schedule popover opens, pause and resume, Edit →
Add webhook → created key → Finish, title save, Test webhook → Finish
testing, Version history, Audit log shows "Started testing a webhook",
phone width has no horizontal overflow, and Create routine from the list
opens the new page. No console errors or failed API calls.

## Risks

- Behaviour change: the section pages are gone. Old links redirect to
the single page.
- The delivery-setting editors (concurrency, catch-up, activity gate)
and priority are removed from the UI. Saved values stay, and the API
still accepts them.
- The create dialog no longer offers a folder picker or delivery
settings. A new routine goes into the folder the list is showing and
takes the default settings.
- Replace key in the Webhook dialog acts at once, as in the reviewed
design. The old confirmation is gone.
- No migration. `lastWebhookDelivery.previous` is an optional field
inside the existing jsonb column.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with
tool use (shell, file edits, headless browser) and subagents for the
server change and the Storybook move.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Fable 5.2 authored and GitHub committed 2026-11-18 13:13:15 -06:00
1 parent f4d44ac13e
commit 33fac97cad
94 files changed
+6116 -9212

No files matched your search

@@ -0,0 +1,44 @@
import { describe, expect, it } from "vitest";
import { planTriggerUpdate, triggerUpdateActivityAction } from "../services/routine-trigger-update-plan.js";
const real = { status: "received" as const, receivedAt: "2026-11-17T10:00:00Z", test: false };
describe("planTriggerUpdate", () => {
it("starts testing without touching the delivery", () => {
const plan = planTriggerUpdate({ setupPending: true }, { kind: "webhook", setupPending: false, lastWebhookDelivery: real });
expect(plan).toMatchObject({ startsTesting: true, finishesTesting: false, restoredDelivery: null, changeSummary: "Started testing webhook", activityAction: "routine.trigger_test_started" });
});
it("restores the last real delivery when a test ends", () => {
const plan = planTriggerUpdate({ setupPending: false }, {
kind: "webhook",
setupPending: true,
lastWebhookDelivery: { status: "received", receivedAt: "2026-11-18T10:00:00Z", test: true, previous: real },
});
expect(plan.restoredDelivery).toEqual({ value: real });
expect(plan.changeSummary).toBe("Finished testing webhook");
expect(plan.activityAction).toBe("routine.trigger_setup_finished");
});
it("clears a test result that had no real delivery before it", () => {
const plan = planTriggerUpdate({ setupPending: false }, {
kind: "webhook",
setupPending: true,
lastWebhookDelivery: { status: "received", receivedAt: "2026-11-18T10:00:00Z", test: true, previous: null },
});
expect(plan.restoredDelivery).toEqual({ value: null });
expect(plan.changeSummary).toBe("Finished webhook setup or test");
});
it("leaves deliveries recorded before test bookkeeping alone", () => {
const legacy = { status: "received" as const, receivedAt: "2026-11-18T10:00:00Z", test: true };
expect(planTriggerUpdate({ setupPending: false }, { kind: "webhook", setupPending: true, lastWebhookDelivery: legacy }).restoredDelivery).toBeNull();
});
it("names other updates by trigger kind and maps every activity action", () => {
expect(planTriggerUpdate({}, { kind: "schedule", setupPending: false, lastWebhookDelivery: null }).changeSummary).toBe("Updated schedule trigger");
expect(triggerUpdateActivityAction({ archived: true, setupPending: true })).toBe("routine.trigger_removed");
expect(triggerUpdateActivityAction({ archived: false })).toBe("routine.trigger_restored");
expect(triggerUpdateActivityAction({})).toBe("routine.trigger_updated");
});
});
+134 -1
View File
@@ -567,7 +567,6 @@ describeEmbeddedPostgres("routine routes end-to-end", () => {
expect((await deliver("live-event")).body.id).toBe(live.body.id);
expect(await db.select().from(activityLog).where(eq(activityLog.action, "routine.run_triggered"))).toHaveLength(1);
expect(await db.select().from(issues)).toHaveLength(1);
expect((await request(board).patch(`/api/routine-triggers/${trigger.id}`).send({ setupPending: true })).status).toBe(400);
expect((await request(board).patch(`/api/routine-triggers/${trigger.id}`).send({ archived: true })).status).toBe(200);
expect((await deliver("removed-event")).status).toBe(404);
expect((await request(board).get(`/api/routines/${routineId}`)).body.triggers).toHaveLength(0);
@@ -583,6 +582,140 @@ describeEmbeddedPostgres("routine routes end-to-end", () => {
expect((await request(board).get(`/api/routines/${routineId}`)).body.triggers).toHaveLength(2);
});
it("puts a live webhook back into test mode without starting runs and restores its last real delivery", async () => {
vi.stubEnv("PAPERCLIP_API_URL", "http://localhost:3100");
vi.stubEnv("PAPERCLIP_IN_WORKTREE", "false");
const { companyId, agentId, projectId, userId } = await seedFixture();
const board = await createApp({ type: "board", source: "local_implicit", userId, isInstanceAdmin: true });
const created = await request(board).post(`/api/companies/${companyId}/routines`).send({
projectId, assigneeAgentId: agentId, title: "Triage alerts", description: "Look at the alert", concurrencyPolicy: "always_enqueue",
});
expect(created.status).toBe(201);
const routineId = created.body.id;
const configured = await request(board).post(`/api/routines/${routineId}/triggers`).send({ kind: "webhook", signingMode: "bearer" });
expect(configured.status).toBe(201);
const { trigger, secretMaterial } = configured.body;
const path = new URL(secretMaterial.webhookUrl).pathname;
const publicApp = await createApp({ type: "none" });
const deliver = (key: string) => request(publicApp).post(path)
.set("Authorization", `Bearer ${secretMaterial.webhookSecret}`).set("Idempotency-Key", key).send({ event: "alert.fired" });
const triggerRow = async () => (await db.select().from(routineTriggers).where(eq(routineTriggers.id, trigger.id)))[0]!;
const live = await deliver("live-1");
expect(live.body.status, JSON.stringify(live.body)).toBe("issue_created");
expect(await db.select().from(issues)).toHaveLength(1);
const realDelivery = (await triggerRow()).lastWebhookDelivery!;
expect(realDelivery).toMatchObject({ status: "received", test: false });
expect(realDelivery.previous).toBeUndefined();
const outsider = await createApp({ type: "board", userId: randomUUID(), source: "session", companyIds: [randomUUID()] });
expect((await request(outsider).patch(`/api/routine-triggers/${trigger.id}`).send({ setupPending: true })).status).toBe(404);
expect((await triggerRow()).setupPending).toBe(false);
const started = await request(board).patch(`/api/routine-triggers/${trigger.id}`).send({ setupPending: true });
expect(started.status, JSON.stringify(started.body)).toBe(200);
expect(started.body).toMatchObject({ setupPending: true, lastWebhookDelivery: realDelivery });
expect(await db.select().from(activityLog).where(eq(activityLog.action, "routine.trigger_test_started"))).toHaveLength(1);
const revisions = await request(board).get(`/api/routines/${routineId}/revisions`);
expect(revisions.body.map((revision: { changeSummary: string }) => revision.changeSummary)).toContain("Started testing webhook");
for (const key of ["test-1", "test-2"]) {
const tested = await deliver(key);
expect(tested.status, JSON.stringify(tested.body)).toBe(202);
expect(tested.body).toMatchObject({ status: "test_received", routineStarted: false, linkedIssueId: null });
}
expect(await db.select().from(issues)).toHaveLength(1);
expect(await db.select().from(routineRuns)).toHaveLength(1);
expect((await triggerRow()).lastWebhookDelivery).toMatchObject({
status: "received", test: true, previous: { ...realDelivery, test: false },
});
const finished = await request(board).patch(`/api/routine-triggers/${trigger.id}`).send({ setupPending: false });
expect(finished.status).toBe(200);
expect(finished.body).toMatchObject({ setupPending: false, lastWebhookDelivery: realDelivery });
expect((await triggerRow()).lastWebhookDelivery).toEqual(realDelivery);
expect(await db.select().from(activityLog).where(eq(activityLog.action, "routine.trigger_setup_finished"))).toHaveLength(1);
expect((await request(board).get(`/api/routines/${routineId}/revisions`)).body
.map((revision: { changeSummary: string }) => revision.changeSummary)).toContain("Finished testing webhook");
// A sender retry of an event received during testing stays a test receipt.
expect((await deliver("test-1")).body.status).toBe("test_received");
expect(await db.select().from(issues)).toHaveLength(1);
const next = await deliver("live-2");
expect(next.body.status, JSON.stringify(next.body)).toBe("issue_created");
expect(await db.select().from(issues)).toHaveLength(2);
expect((await triggerRow()).lastWebhookDelivery).toMatchObject({ status: "received", test: false });
expect((await triggerRow()).lastWebhookDelivery?.previous).toBeUndefined();
});
it("starts each test of a never-used webhook without the last test's result", async () => {
vi.stubEnv("PAPERCLIP_API_URL", "http://localhost:3100");
vi.stubEnv("PAPERCLIP_IN_WORKTREE", "false");
const { companyId, agentId, projectId, userId } = await seedFixture();
const board = await createApp({ type: "board", source: "local_implicit", userId, isInstanceAdmin: true });
const created = await request(board).post(`/api/companies/${companyId}/routines`).send({ projectId, assigneeAgentId: agentId, title: "Quiet hook" });
const routineId = created.body.id;
const configured = await request(board).post(`/api/routines/${routineId}/triggers`).send({ kind: "webhook", signingMode: "bearer" });
const { trigger, secretMaterial } = configured.body;
const path = new URL(secretMaterial.webhookUrl).pathname;
const publicApp = await createApp({ type: "none" });
const triggerRow = async () => (await db.select().from(routineTriggers).where(eq(routineTriggers.id, trigger.id)))[0]!;
expect((await request(board).patch(`/api/routine-triggers/${trigger.id}`).send({ setupPending: true })).status).toBe(200);
const tested = await request(publicApp).post(path).set("Authorization", `Bearer ${secretMaterial.webhookSecret}`)
.set("Idempotency-Key", "test-1").send({ event: "ping" });
expect(tested.body.status).toBe("test_received");
expect((await triggerRow()).lastWebhookDelivery).toMatchObject({ status: "received", test: true, previous: null });
expect((await request(board).patch(`/api/routine-triggers/${trigger.id}`).send({ setupPending: false })).status).toBe(200);
expect((await triggerRow()).lastWebhookDelivery).toBeNull();
expect((await request(board).patch(`/api/routine-triggers/${trigger.id}`).send({ setupPending: true })).status).toBe(200);
// A new test starts clean: nothing reads as "Test event received" before an event arrives.
expect((await triggerRow()).lastWebhookDelivery).toBeNull();
expect(await db.select().from(issues)).toHaveLength(0);
});
it("only starts testing on an active, enabled webhook", async () => {
vi.stubEnv("PAPERCLIP_API_URL", "http://localhost:3100");
const { companyId, agentId, projectId, userId } = await seedFixture();
const board = await createApp({ type: "board", source: "local_implicit", userId, isInstanceAdmin: true });
const created = await request(board).post(`/api/companies/${companyId}/routines`).send({
projectId, assigneeAgentId: agentId, title: "Triage alerts", description: "Look at the alert",
});
const routineId = created.body.id;
const webhook = (await request(board).post(`/api/routines/${routineId}/triggers`).send({ kind: "webhook", signingMode: "bearer" })).body.trigger;
const schedule = (await request(board).post(`/api/routines/${routineId}/triggers`)
.send({ kind: "schedule", cronExpression: "0 9 * * 1-5", timezone: "UTC" })).body.trigger;
const startTesting = (id: string, extra: Record<string, unknown> = {}) =>
request(board).patch(`/api/routine-triggers/${id}`).send({ setupPending: true, ...extra });
const scheduleAttempt = await startTesting(schedule.id);
expect(scheduleAttempt.status).toBe(422);
expect(scheduleAttempt.body.error).toBe("Only webhooks can be tested");
const disablingAttempt = await startTesting(webhook.id, { enabled: false });
expect(disablingAttempt.status).toBe(409);
expect((await request(board).patch(`/api/routine-triggers/${webhook.id}`).send({ enabled: false })).status).toBe(200);
const disabledAttempt = await startTesting(webhook.id);
expect(disabledAttempt.status).toBe(409);
expect(disabledAttempt.body.error).toBe("Turn the webhook on before testing it");
await request(board).patch(`/api/routine-triggers/${webhook.id}`).send({ enabled: true });
await request(board).patch(`/api/routine-triggers/${webhook.id}`).send({ archived: true });
const archivedAttempt = await startTesting(webhook.id);
expect(archivedAttempt.status).toBe(409);
expect(archivedAttempt.body.error).toBe("This webhook was removed");
await request(board).patch(`/api/routine-triggers/${webhook.id}`).send({ archived: false });
await db.update(routines).set({ status: "archived" }).where(eq(routines.id, routineId));
const archivedRoutineAttempt = await startTesting(webhook.id);
expect(archivedRoutineAttempt.status).toBe(409);
expect(archivedRoutineAttempt.body.error).toBe("This routine is archived");
expect((await db.select().from(routineTriggers).where(eq(routineTriggers.id, webhook.id)))[0]?.setupPending).toBe(false);
expect(await db.select().from(activityLog).where(eq(activityLog.action, "routine.trigger_test_started"))).toHaveLength(0);
});
it("supports creating, scheduling, and manually running a routine through the API", async () => {
const { companyId, agentId, projectId, userId } = await seedFixture();
const app = await createApp({
+2 -1
View File
@@ -1,4 +1,5 @@
import { Router, type Request } from "express";
import { triggerUpdateActivityAction } from "../services/routine-trigger-update-plan.js";
import { listProtectedEnvironmentKeyHolders, protectedEnvironmentKeyWarnings } from "../services/protected-environment-keys.js";
import type { Db } from "@paperclipai/db";
import {
@@ -561,7 +562,7 @@ export function routineRoutes(
agentId: actor.agentId,
runId: actor.runId,
agentApiKeyId: actor.agentApiKeyId,
action: req.body.archived === true ? "routine.trigger_removed" : req.body.archived === false ? "routine.trigger_restored" : req.body.setupPending === false ? "routine.trigger_setup_finished" : "routine.trigger_updated",
action: triggerUpdateActivityAction(req.body),
entityType: "routine",
entityId: routine.id,
details: { triggerId: trigger.id, kind: updated?.trigger.kind ?? trigger.kind },
@@ -0,0 +1,45 @@
import type { RoutineWebhookDelivery, UpdateRoutineTrigger } from "@paperclipai/shared";
/** The trigger fields a plan reads, as stored. */
export interface TriggerUpdatePlanState {
kind: string;
setupPending: boolean;
lastWebhookDelivery: RoutineWebhookDelivery | null;
}
/** What one `PATCH /routine-triggers/:id` does to test mode, delivery status, the revision and the activity log. */
export interface TriggerUpdatePlan {
startsTesting: boolean;
finishesTesting: boolean;
/** Ending a test puts back the last real delivery (or null), so no stale test result stays behind. */
restoredDelivery: { value: RoutineWebhookDelivery | null } | null;
changeSummary: string;
activityAction: string;
}
/** The activity action for a trigger update body; also used when the service is not reached. */
export function triggerUpdateActivityAction(patch: Pick<UpdateRoutineTrigger, "archived" | "setupPending">): string {
if (patch.archived === true) return "routine.trigger_removed";
if (patch.archived === false) return "routine.trigger_restored";
if (patch.setupPending === true) return "routine.trigger_test_started";
if (patch.setupPending === false) return "routine.trigger_setup_finished";
return "routine.trigger_updated";
}
/** Pure plan for a trigger update, so the service and the route's activity entry cannot drift. */
export function planTriggerUpdate(
patch: Pick<UpdateRoutineTrigger, "archived" | "setupPending">,
current: TriggerUpdatePlanState,
): TriggerUpdatePlan {
const startsTesting = patch.setupPending === true && !current.setupPending;
const finishesTesting = patch.setupPending === false && current.setupPending;
const last = current.lastWebhookDelivery;
// A test delivery always records `previous` (null when there was no real delivery).
const restoredDelivery = finishesTesting && last?.test && "previous" in last ? { value: last.previous ?? null } : null;
const changeSummary = startsTesting
? "Started testing webhook"
: finishesTesting
? restoredDelivery?.value ? "Finished testing webhook" : "Finished webhook setup or test"
: `Updated ${current.kind} trigger`;
return { startsTesting, finishesTesting, restoredDelivery, changeSummary, activityAction: triggerUpdateActivityAction(patch) };
}
+37 -6
View File
@@ -49,6 +49,7 @@ import type {
RoutineTrigger,
RoutineTriggerSecretMaterial,
RoutineVariable,
RoutineWebhookDelivery,
RunRoutine,
UpdateRoutine,
UpdateRoutineTrigger,
@@ -89,6 +90,7 @@ import { queueIssueAssignmentWakeup, type IssueAssignmentWakeupDeps } from "./is
import { logActivity } from "./activity-log.js";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
import { runtimePublicOrigin } from "./cloud-runtime-identity.js";
import { planTriggerUpdate } from "./routine-trigger-update-plan.js";
const OPEN_ISSUE_STATUSES = ["backlog", "todo", "in_progress", "in_review", "blocked"];
const LIVE_HEARTBEAT_RUN_STATUSES = ["queued", "running", "scheduled_retry"];
@@ -2794,11 +2796,21 @@ export function routineService(
}
}
if (patch.setupPending === true && existing.kind !== "webhook") {
throw unprocessable("Only webhooks can be tested");
}
const result = await db.transaction(async (tx) => {
const txDb = tx as unknown as Db;
await tx.execute(sql`select id from ${routines} where ${routines.id} = ${existing.routineId} for update`);
const current = await txDb
.select({ signingMode: routineTriggers.signingMode })
.select({
signingMode: routineTriggers.signingMode,
enabled: routineTriggers.enabled,
archived: routineTriggers.archived,
setupPending: routineTriggers.setupPending,
lastWebhookDelivery: routineTriggers.lastWebhookDelivery,
})
.from(routineTriggers)
.where(eq(routineTriggers.id, id))
.then((rows) => rows[0] ?? null);
@@ -2806,13 +2818,29 @@ export function routineService(
if (existing.kind === "webhook" && current.signingMode !== "none") {
assertAgentWebhookAuthenticated(actor, patch.signingMode);
}
const plan = planTriggerUpdate(patch, {
kind: existing.kind,
setupPending: current.setupPending,
lastWebhookDelivery: current.lastWebhookDelivery ?? null,
});
if (patch.setupPending === true) {
if (patch.archived ?? current.archived) throw conflict("This webhook was removed");
if (!(patch.enabled ?? current.enabled)) throw conflict("Turn the webhook on before testing it");
const [lockedRoutine] = await txDb
.select({ status: routines.status })
.from(routines)
.where(eq(routines.id, existing.routineId));
if (!lockedRoutine) throw notFound("Routine not found");
if (lockedRoutine.status === "archived") throw conflict("This routine is archived");
}
await notifyDeliveryWork(txDb, DELIVERY_QUEUES.routineSchedules);
const [updated] = await txDb
.update(routineTriggers)
.set({
label: patch.label === undefined ? existing.label : patch.label,
enabled: patch.enabled ?? existing.enabled,
...(patch.setupPending === false ? { setupPending: false } : {}),
...(patch.setupPending !== undefined ? { setupPending: patch.setupPending } : {}),
...(plan.restoredDelivery ? { lastWebhookDelivery: plan.restoredDelivery.value } : {}),
...(patch.archived !== undefined ? { archived: patch.archived } : {}),
cronExpression,
timezone,
@@ -2832,9 +2860,7 @@ export function routineService(
.where(eq(routines.id, existing.routineId))
.then((rows) => rows[0] ?? null);
if (!routine) throw notFound("Routine not found");
const appended = await appendRoutineRevision(txDb, routine, actor, {
changeSummary: `Updated ${existing.kind} trigger`,
});
const appended = await appendRoutineRevision(txDb, routine, actor, { changeSummary: plan.changeSummary });
return { trigger: updated as RoutineTrigger, revision: appended.revision };
});
return result;
@@ -3172,7 +3198,12 @@ export function routineService(
if (!trigger.enabled || (!trigger.setupPending && routine.status !== "active")) throw conflict("Routine trigger is not active");
const recordDelivery = async (status: "received" | "rejected") => {
const receivedAt = new Date().toISOString();
await txDb.update(routineTriggers).set({ lastWebhookDelivery: { status, receivedAt, test: trigger.setupPending } }).where(eq(routineTriggers.id, trigger.id));
const last = trigger.lastWebhookDelivery;
// While testing, carry the last real delivery so finishing the test can restore it.
const delivery: RoutineWebhookDelivery = trigger.setupPending
? { status, receivedAt, test: true, previous: last ? (last.test ? last.previous ?? null : last) : null }
: { status, receivedAt, test: false };
await txDb.update(routineTriggers).set({ lastWebhookDelivery: delivery }).where(eq(routineTriggers.id, trigger.id));
await logActivity(txDb, {
companyId: routine.companyId, actorType: "system", actorId: "routine-webhook",
action: trigger.setupPending ? `routine.webhook_test_${status}` : `routine.webhook_${status}`,