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

@@ -1,668 +0,0 @@
import { useCallback, useRef, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { CalendarClock, Plus, Radar, Webhook } from "lucide-react";
import type { RoutineTrigger } from "@paperclipai/shared";
import { useSearchParams } from "@/lib/router";
import { routinesApi } from "@/api/routines";
import { queryKeys } from "@/lib/queryKeys";
import { describeCron } from "@/lib/cron-readable";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
} from "@/components/ui/dialog";
import { ScheduleEditor } from "@/components/ScheduleEditor";
import { useRoutineDetail } from "@/components/routine-sections/context";
import { RoutineTriggerCard } from "./TriggerCard";
import {
RoutineTriggerWizard,
defaultTriggerDraft,
webhookAgentInstructions,
type TriggerDraft,
} from "./TriggerWizard";
import { AgentInstructions, CopyField } from "./WebhookFields";
import { WebhookUrlWarning } from "./WebhookUrlWarning";
function readDraft(key: string): TriggerDraft | null {
try {
const draft = JSON.parse(sessionStorage.getItem(key) ?? "null");
return draft && ["choose", "schedule", "webhook"].includes(draft.kind)
? { ...defaultTriggerDraft, ...draft, sender: draft.sender === "github" ? "github" : "custom" }
: null;
} catch {
return null;
}
}
function saveDraft(key: string, draft: TriggerDraft) {
// Only setup choices are persisted. The one-time key stays in component memory.
try {
sessionStorage.setItem(key, JSON.stringify(draft));
} catch {
throw new Error(
"Couldn’t save your draft in this browser. Keep this page open and try again.",
);
}
}
function scheduleCron(draft: TriggerDraft) {
const [hour, minute] = draft.time.split(":").map(Number);
const day = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
].indexOf(draft.weekday);
return `${minute} ${hour} * * ${draft.frequency === "daily" ? "*" : draft.frequency === "weekly" ? day : "1-5"}`;
}
export function RoutineTriggers() {
const ctx = useRoutineDetail();
const [params, setParams] = useSearchParams();
const setupId = params.get("triggerSetup");
const client = useQueryClient();
const { data, error: statusError } = useQuery({
queryKey: queryKeys.routines.detail(ctx.routineId),
queryFn: () => routinesApi.get(ctx.routineId),
refetchInterval: 3000,
});
const routine = data ?? ctx.routine;
const [expanded, setExpanded] = useState<string | null>(null);
const [removed, setRemoved] = useState<RoutineTrigger[]>([]);
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const refresh = useCallback(async () => {
await client.invalidateQueries({ queryKey: ["routines"] });
}, [client]);
const change = async (action: () => Promise<void>) => {
if (busy) return;
setBusy(true);
setError("");
try {
await action();
await refresh();
} catch (cause) {
setError(
cause instanceof Error
? cause.message
: "Couldn’t save the trigger. Please try again.",
);
} finally {
setBusy(false);
}
};
const startSetup = (id: string) => setParams({ triggerSetup: id });
const closeSetup = useCallback(() => setParams({}), [setParams]);
if (setupId) {
const trigger = routine.triggers.find((item) => item.id === setupId);
if (setupId !== "new" && !trigger)
return (
<p role="alert">
This trigger is no longer available.{" "}
<Button variant="link" onClick={closeSetup}>
Back to triggers
</Button>
</p>
);
if (trigger && !trigger.setupPending)
return (
<p>
This trigger is ready.{" "}
<Button variant="link" onClick={closeSetup}>
Back to triggers
</Button>
</p>
);
return (
<div className="space-y-4">
{statusError && (
<p role="alert" className="text-sm text-destructive">
Connection status is unavailable. Retrying…
</p>
)}
<TriggerSetup
key={routine.id}
routineId={routine.id}
companyId={routine.companyId}
routineTitle={routine.title}
trigger={trigger}
onExit={closeSetup}
onRefresh={refresh}
/>
</div>
);
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">
{routine.triggers.length}{" "}
{routine.triggers.length === 1 ? "trigger" : "triggers"}
</p>
<Button size="sm" onClick={() => startSetup("new")}>
<Plus className="mr-1.5 h-3.5 w-3.5" />
Add trigger
</Button>
</div>
{(error || statusError) && (
<p role="alert" className="text-sm text-destructive">
{error || "Connection status is unavailable. Retrying…"}
</p>
)}
{removed.map((trigger) => (
<div
key={trigger.id}
role="status"
className="flex items-center gap-3 rounded-md bg-muted/40 px-4 py-3 text-sm"
>
<span className="flex-1">
{trigger.kind === "schedule"
? "Schedule"
: trigger.kind === "api"
? "API trigger"
: trigger.kind === "heartbeat"
? "Standing check"
: "Webhook"}{" "}
removed.
</span>
<Button
variant="ghost"
size="sm"
disabled={busy}
onClick={() =>
void change(async () => {
await routinesApi.updateTrigger(trigger.id, {
archived: false,
});
setRemoved((items) =>
items.filter((item) => item.id !== trigger.id),
);
})
}
>
Undo
</Button>
</div>
))}
{ctx.secretMessage && (
<div className="space-y-3 rounded-md border p-4">
<p className="text-sm font-medium">{ctx.secretMessage.title}</p>
{ctx.secretMessage.entries.map((entry) => (
<div key={entry.webhookUrl} className="space-y-3">
<CopyField label="Webhook URL" value={entry.webhookUrl} />
<CopyField label="Secret key" value={entry.webhookSecret} />
</div>
))}
<Button variant="outline" onClick={() => ctx.setSecretMessage(null)}>
Done
</Button>
</div>
)}
{routine.triggers.length === 0 && (
<p className="py-6 text-sm text-muted-foreground">
Run this routine on a schedule or when another app sends a webhook.
</p>
)}
<fieldset disabled={busy} className="min-w-0 space-y-3">
{routine.triggers.map((trigger) => (
<RoutineTriggerCard
key={trigger.id}
kind={
trigger.kind === "schedule"
? "schedule"
: trigger.kind === "api"
? "api"
: trigger.kind === "heartbeat"
? "heartbeat"
: "webhook"
}
icon={
trigger.kind === "schedule" ? (
<CalendarClock className="h-4 w-4" />
) : trigger.kind === "heartbeat" ? (
<Radar className="h-4 w-4" />
) : (
<Webhook className="h-4 w-4" />
)
}
title={
trigger.kind === "schedule"
? (describeCron(trigger.cronExpression) ?? "Schedule")
: trigger.kind === "api"
? "API trigger"
: trigger.kind === "heartbeat"
? "Standing check"
: trigger.signingMode === "github_hmac"
? "GitHub webhook"
: "Webhook"
}
summary={
trigger.setupPending
? "Setup unfinished · Events only test the connection"
: !trigger.enabled
? "Paused"
: trigger.kind === "schedule"
? (trigger.timezone ?? "UTC")
: trigger.kind === "api"
? "Run through the API"
: trigger.kind === "heartbeat"
? trigger.lastResult ? `On each wake-up · Last: ${trigger.lastResult}` : "On each wake-up · Not checked yet"
: trigger.lastWebhookDelivery?.status === "rejected"
? "Authentication failed · Check the key in your app"
: trigger.lastWebhookDelivery?.status === "received" &&
!trigger.lastWebhookDelivery.test
? "Receiving events"
: "Ready · Waiting for an event"
}
expanded={expanded === trigger.id}
editLabel={trigger.setupPending ? "Resume setup" : undefined}
onEdit={() =>
trigger.setupPending
? startSetup(trigger.id)
: setExpanded((id) => (id === trigger.id ? null : trigger.id))
}
onRemove={() =>
void change(async () => {
await routinesApi.updateTrigger(trigger.id, { archived: true });
setRemoved((items) => [...items, trigger]);
})
}
>
{trigger.setupPending ? (
<Button onClick={() => startSetup(trigger.id)}>
Resume setup
</Button>
) : trigger.kind === "schedule" ? (
<ScheduleSettings
trigger={trigger}
onSave={async (patch) => {
await routinesApi.updateTrigger(trigger.id, patch);
await refresh();
setExpanded(null);
}}
onCancel={() => setExpanded(null)}
/>
) : trigger.kind === "api" ? (
<p className="text-sm text-muted-foreground">
This trigger starts the routine through the API.
</p>
) : trigger.kind === "heartbeat" ? (
<p className="text-sm text-muted-foreground">
A standing check: the routine’s agent carries out these instructions each time its heartbeat wakes it, and reports what it found. It never creates a task by itself.
</p>
) : (
<WebhookSettings
trigger={trigger}
routineTitle={routine.title}
onRefresh={refresh}
/>
)}
{!trigger.setupPending && (
<Button
variant="ghost"
size="sm"
onClick={() =>
void change(async () => {
await routinesApi.updateTrigger(trigger.id, {
enabled: !trigger.enabled,
});
})
}
>
{trigger.enabled ? "Pause trigger" : "Enable trigger"}
</Button>
)}
</RoutineTriggerCard>
))}
</fieldset>
</div>
);
}
function TriggerSetup({
routineId,
companyId,
routineTitle,
trigger,
onExit,
onRefresh,
}: {
routineId: string;
companyId: string;
routineTitle: string;
trigger?: RoutineTrigger;
onExit: () => void;
onRefresh: () => Promise<void>;
}) {
const [, setParams] = useSearchParams();
const storagePrefix = `routine-trigger-draft:${companyId}:${routineId}:`;
const createdRef = useRef<RoutineTrigger | undefined>(trigger);
const [created, setCreated] = useState(trigger);
const [secret, setSecret] = useState("");
const currentTrigger = trigger ?? created;
const [initialDraft] = useState<TriggerDraft>(() => {
const saved = readDraft(storagePrefix + (trigger?.id ?? "new"));
if (trigger)
return {
...defaultTriggerDraft,
...saved,
kind: "webhook",
sender: trigger.signingMode === "github_hmac" ? "github" : "custom",
signingMode: trigger.signingMode === "bearer" ? "bearer" : trigger.signingMode === "fireflies_hmac" ? "fireflies_hmac" : "app_webhook",
created: true,
step: saved?.step ?? 1,
availableStep: Math.max(1, saved?.availableStep ?? 1),
};
return (
saved ?? {
...defaultTriggerDraft,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
created: false,
}
);
});
const createWebhook = useCallback(
async (draft: TriggerDraft) => {
if (createdRef.current) return;
const response = await routinesApi.createTrigger(routineId, {
kind: "webhook",
signingMode: draft.sender === "github" ? "github_hmac" : "app_webhook",
setupPending: true,
});
createdRef.current = response.trigger;
setCreated({
...response.trigger,
webhookUrl:
response.secretMaterial?.webhookUrl ?? response.trigger.webhookUrl,
});
setSecret(response.secretMaterial?.webhookSecret ?? "");
saveDraft(storagePrefix + response.trigger.id, {
...draft,
created: true,
step: 1,
availableStep: 1,
});
sessionStorage.removeItem(storagePrefix + "new");
await onRefresh();
setParams({ triggerSetup: response.trigger.id }, { replace: true });
},
[routineId, onRefresh, storagePrefix, setParams],
);
const saveExit = useCallback(
(draft: TriggerDraft) => {
saveDraft(storagePrefix + (createdRef.current?.id ?? "new"), draft);
onExit();
},
[onExit, storagePrefix],
);
const finish = useCallback(
async (draft: TriggerDraft) => {
if (draft.kind === "schedule")
await routinesApi.createTrigger(routineId, {
kind: "schedule",
cronExpression: scheduleCron(draft),
timezone: draft.timezone,
});
else {
if (!createdRef.current)
throw new Error("Create the webhook before finishing setup.");
await routinesApi.updateTrigger(createdRef.current.id, {
setupPending: false,
});
}
try {
sessionStorage.removeItem(
storagePrefix + (createdRef.current?.id ?? "new"),
);
} catch {
// The server mutation succeeded; draft cleanup must not cause a retry.
}
await onRefresh();
onExit();
},
[routineId, onRefresh, onExit, storagePrefix],
);
const { routine: currentRoutine } = useRoutineDetail();
return (
<RoutineTriggerWizard
initialDraft={initialDraft}
routineTitle={routineTitle}
routineId={routineId}
routineActive={currentRoutine.status === "active"}
webhookUrl={currentTrigger?.webhookUrl ?? ""}
webhookSecret={secret}
onCreateWebhook={createWebhook}
onSaveExit={saveExit}
onFinish={finish}
onRotateKey={async () => {
if (!createdRef.current) return;
const response = await routinesApi.rotateTriggerSecret(
createdRef.current.id,
);
setSecret(response.secretMaterial.webhookSecret);
await onRefresh();
}}
checkResult={currentTrigger?.lastWebhookDelivery?.status ?? "waiting"}
/>
);
}
function ScheduleSettings({
trigger,
onSave,
onCancel,
}: {
trigger: RoutineTrigger;
onSave: (patch: Record<string, unknown>) => Promise<void>;
onCancel: () => void;
}) {
const [cronExpression, setCron] = useState(
trigger.cronExpression ?? "0 9 * * *",
);
const [timezone, setTimezone] = useState(trigger.timezone ?? "UTC");
const [valid, setValid] = useState(true);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
return (
<fieldset disabled={busy} className="min-w-0 space-y-4">
<ScheduleEditor
value={cronExpression}
onChange={setCron}
onValidityChange={setValid}
/>
<Label>
Time zone
<Input
value={timezone}
onChange={(event) => setTimezone(event.target.value)}
/>
</Label>
{error && (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
)}
<div className="flex gap-2">
<Button
disabled={!valid}
onClick={async () => {
setBusy(true);
setError("");
try {
await onSave({ cronExpression, timezone });
} catch (cause) {
setError(
cause instanceof Error
? cause.message
: "Couldn’t save schedule.",
);
} finally {
setBusy(false);
}
}}
>
Save schedule
</Button>
<Button variant="outline" onClick={onCancel}>
Cancel
</Button>
</div>
</fieldset>
);
}
function WebhookSettings({
trigger,
routineTitle,
onRefresh,
}: {
trigger: RoutineTrigger;
routineTitle: string;
onRefresh: () => Promise<void>;
}) {
const [secret, setSecret] = useState("");
const [replace, setReplace] = useState(false);
const [checkBaseline, setCheckBaseline] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const github = trigger.signingMode === "github_hmac";
const delivery = trigger.lastWebhookDelivery;
const checked =
checkBaseline !== null && delivery && delivery.receivedAt !== checkBaseline;
return (
<div className="space-y-4">
<WebhookUrlWarning url={trigger.webhookUrl ?? ""} />
{secret && (github || trigger.signingMode === "bearer" || trigger.signingMode === "app_webhook" || trigger.signingMode === "fireflies_hmac") && (
<AgentInstructions
value={webhookAgentInstructions(
github ? "github" : "custom",
routineTitle,
trigger.webhookUrl ?? "",
secret,
false,
trigger.signingMode === "bearer" ? "bearer" : trigger.signingMode === "fireflies_hmac" ? "fireflies_hmac" : "app_webhook",
)}
/>
)}
<CopyField label="Webhook URL" value={trigger.webhookUrl ?? ""} />
{trigger.signingMode !== "none" && (
<div className="space-y-2">
{secret ? (
<CopyField
label={
trigger.signingMode === "bearer"
? "Authorization header value"
: "Secret key"
}
value={
trigger.signingMode === "bearer" ? `Bearer ${secret}` : secret
}
/>
) : (
<p className="text-sm text-muted-foreground">
The secret key is hidden.
</p>
)}
<Button variant="outline" size="sm" onClick={() => setReplace(true)}>
Replace key
</Button>
{secret && (
<Button variant="ghost" size="sm" onClick={() => setSecret("")}>
Hide key
</Button>
)}
</div>
)}
{trigger.signingMode === "none" && (
<p className="text-sm text-muted-foreground">
This webhook uses its URL as the shared secret.
</p>
)}
{trigger.signingMode === "hmac_sha256" && (
<p className="text-sm text-muted-foreground">
Sign the timestamp, a period, and the exact JSON body with
HMAC-SHA256. Send X-Paperclip-Timestamp and X-Paperclip-Signature:
sha256=&lt;signature&gt;.
</p>
)}
<Button
variant="outline"
onClick={() =>
setCheckBaseline(trigger.lastWebhookDelivery?.receivedAt ?? "")
}
>
Check connection
</Button>
<Dialog open={replace} onOpenChange={setReplace}>
<DialogContent>
<DialogHeader>
<DialogTitle>Replace the webhook key?</DialogTitle>
<DialogDescription>
The old key will stop working. Update your sending app with the
new key.
</DialogDescription>
</DialogHeader>
{error && (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
)}
<Button
disabled={busy}
onClick={async () => {
setBusy(true);
setError("");
try {
const response = await routinesApi.rotateTriggerSecret(
trigger.id,
);
setSecret(response.secretMaterial.webhookSecret);
setReplace(false);
await onRefresh();
} catch (cause) {
setError(
cause instanceof Error
? cause.message
: "Couldn’t replace the key.",
);
} finally {
setBusy(false);
}
}}
>
Replace key
</Button>
</DialogContent>
</Dialog>
<Dialog
open={checkBaseline !== null}
onOpenChange={(open) => {
if (!open) setCheckBaseline(null);
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>Check connection</DialogTitle>
<DialogDescription>
This webhook is already enabled. Events sent now can start the
routine. Send an event from your app to check delivery.
</DialogDescription>
</DialogHeader>
<p role="status" className="text-sm">
{checked
? delivery.status === "received"
? "Event received · Authentication passed"
: "Event arrived, but authentication failed. Check the key in your app."
: "Waiting for an event from your app…"}
</p>
</DialogContent>
</Dialog>
</div>
);
}
@@ -1,66 +0,0 @@
import { useId, type ReactNode } from "react";
import { Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
export function RoutineTriggerCard({
kind,
icon,
title,
summary,
expanded,
onEdit,
onRemove,
editLabel,
children,
}: {
kind: "schedule" | "webhook" | "api" | "heartbeat";
icon: ReactNode;
title: string;
summary: string;
expanded: boolean;
onEdit: () => void;
editLabel?: string;
onRemove: () => void;
children: ReactNode;
}) {
const editorId = useId();
return (
<section
aria-label={kind === "heartbeat" ? "Standing check" : `${kind === "schedule" ? "Schedule" : kind === "api" ? "API" : "Webhook"} trigger`}
className="rounded-md border border-border"
>
<div className="flex flex-wrap items-center gap-3 p-4">
<span className="shrink-0 text-muted-foreground">{icon}</span>
<div className="min-w-0 flex-1">
<h3 className="text-sm font-medium">{title}</h3>
<p className="text-xs text-muted-foreground">{summary}</p>
</div>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
aria-expanded={expanded}
aria-controls={editorId}
onClick={onEdit}
>
{editLabel ?? (expanded ? "Close" : `Edit ${kind}`)}
</Button>
<Button
variant="ghost"
size="icon"
aria-label={`Remove ${kind}`}
title={`Remove ${kind}`}
onClick={onRemove}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</div>
{expanded && (
<div id={editorId} className="space-y-5 border-t border-border p-4">
{children}
</div>
)}
</section>
);
}
@@ -1,46 +0,0 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { defaultTriggerDraft, RoutineTriggerWizard, webhookAgentInstructions } from "./TriggerWizard";
const { setBreadcrumbs } = vi.hoisted(() => ({ setBreadcrumbs: vi.fn() }));
vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs }) }));
vi.mock("@/context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: false, setSidebarOpen: () => {} }) }));
let root: Root;
let container: HTMLDivElement;
beforeEach(() => { vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); container = document.createElement("div"); document.body.append(container); root = createRoot(container); });
afterEach(async () => { await act(async () => root.unmount()); container.remove(); });
it("offers the shared app flow without a Fireflies-specific sender", async () => {
await act(async () => root.render(<RoutineTriggerWizard initialDraft={{ ...defaultTriggerDraft, kind: "webhook" }} routineTitle="Process meetings" routineId="routine-1" onSaveExit={() => {}} onFinish={() => {}} />));
expect(container.textContent).toContain("Another app or script");
expect(container.textContent).not.toContain("Fireflies");
expect(container.textContent).toContain("publicly reachable HTTPS");
});
it("resumes generic setup with a signing secret and preserves the draft", async () => {
const onSaveExit = vi.fn();
await act(async () => root.render(<RoutineTriggerWizard initialDraft={{ ...defaultTriggerDraft, kind: "webhook", created: true, step: 1, availableStep: 1 }} routineTitle="Process meetings" routineId="routine-1" webhookUrl="https://paperclip.example/api/routine-triggers/public/test/fire" webhookSecret="test-signing-secret" onSaveExit={onSaveExit} onFinish={() => {}} />));
expect(container.textContent).toContain("Secret key");
expect(container.textContent).toContain("signing secret field");
expect(container.textContent).not.toContain("Fireflies");
const save = [...container.querySelectorAll("button")].find((button) => button.textContent?.includes("Save & exit"))!;
await act(async () => save.click());
expect(onSaveExit).toHaveBeenCalledWith(expect.objectContaining({ sender: "custom", step: 1, created: true }));
});
it("explains both supported app authentication methods", () => {
const instructions = webhookAgentInstructions("custom", "Meetings", "https://paperclip.example/webhook", "signing-secret");
expect(instructions).toContain("Secret key: signing-secret");
expect(instructions).toContain("X-Hub-Signature");
expect(instructions).toContain("Authorization: Bearer signing-secret");
expect(instructions).toContain("They do not start the routine");
expect(instructions).not.toContain("Fireflies");
});
it("keeps legacy bearer setup instructions accurate", () => {
const instructions = webhookAgentInstructions("custom", "Meetings", "https://paperclip.example/webhook", "secret", true, "bearer");
expect(instructions).toContain("Authorization: Bearer secret");
expect(instructions).not.toContain("HMAC-SHA256");
});
@@ -1,597 +0,0 @@
import { useCallback, useEffect, useState } from "react";
import {
CalendarClock,
Check,
CheckCircle2,
AlertCircle,
Globe,
GitBranch,
Radio,
Webhook,
} from "lucide-react";
import {
SetupWizardNavigation,
SetupWizardFooter,
} from "@/components/SetupWizard";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { cn } from "@/lib/utils";
import { AgentInstructions, CopyField } from "./WebhookFields";
import { WebhookUrlWarning } from "./WebhookUrlWarning";
export type TriggerDraft = {
kind: "choose" | "schedule" | "webhook";
step: number;
availableStep: number;
sender: "custom" | "github";
/** Retained when resuming webhooks created before generic signed-app support. */
signingMode?: "bearer" | "app_webhook" | "fireflies_hmac";
frequency: string;
time: string;
weekday: string;
timezone: string;
created: boolean;
};
export const defaultTriggerDraft: TriggerDraft = {
kind: "choose",
step: 0,
availableStep: 0,
sender: "custom",
frequency: "weekdays",
time: "09:00",
weekday: "Monday",
timezone: "America/Chicago",
created: false,
};
export function webhookAgentInstructions(
sender: TriggerDraft["sender"],
routineTitle: string,
webhookUrl: string,
webhookSecret: string,
setupPending = true,
signingMode: TriggerDraft["signingMode"] = "app_webhook",
) {
const common = [
`Connect the sending app to the Paperclip routine ${JSON.stringify(routineTitle)}.`,
`Webhook URL: ${webhookUrl}`,
"Send an HTTP POST request with a JSON object as the body (not an array or string).",
"Content-Type: application/json",
];
const auth =
sender === "github"
? [
"In GitHub, open your repository → Settings → Webhooks → Add webhook.",
"Use the webhook URL above as Payload URL and select application/json as Content type.",
`Secret: ${webhookSecret}`,
"Paste this value into GitHub’s Secret field. GitHub signs requests with X-Hub-Signature-256; do not use Bearer authentication.",
"Select the events that should start this routine, enable the webhook, and save.",
"To check the connection, open Recent Deliveries and redeliver an event.",
]
: [
`Secret key: ${webhookSecret}`,
...(signingMode === "bearer" ? [] : [
`If the app asks for a signing secret, paste the secret key above. Paperclip accepts HMAC-SHA256 over the exact request body in ${signingMode === "fireflies_hmac" ? "X-Hub-Signature" : "X-Hub-Signature or X-Hub-Signature-256"}, formatted sha256=<hex digest>.`,
]),
...(signingMode === "fireflies_hmac" ? [] : [
`For apps with custom headers, use Authorization: Bearer ${webhookSecret}`,
]),
"Subscribe only to the events that should start this routine. Public services need a publicly reachable HTTPS URL.",
"In the sending app, add a webhook using this URL, POST method, JSON body, and headers, then save it.",
"Send a unique Idempotency-Key header for each event and reuse it on retries, so retrying a setup test after activation cannot start the routine.",
'Example JSON body: {"event":"deployment.completed","environment":"production"}',
"To check the connection, send a test event from the app or perform the action that triggers a delivery.",
];
return [
...common,
...auth,
"Open Check connection in Paperclip to see whether the event arrived and authentication passed.",
...(setupPending
? [
"During setup, deliveries only test the connection. They do not start the routine or create a task.",
"Finish setup in Paperclip to enable this webhook for future events. Test events are not replayed.",
]
: [
"This webhook is enabled. Deliveries can start the routine and create tasks.",
]),
"Store the key securely; do not put it in source control or logs.",
].join("\n");
}
export function describeSchedule(draft: TriggerDraft) {
return `${draft.frequency === "daily" ? "Every day" : draft.frequency === "weekly" ? `Every ${draft.weekday}` : "Every weekday"} at ${draft.time}`;
}
export function RoutineTriggerWizard({
initialDraft,
onSaveExit,
onFinish,
onCreateWebhook,
onRotateKey,
routineTitle,
routineId,
routineActive = true,
webhookUrl = "",
webhookSecret = "",
checkResult = "waiting",
}: {
initialDraft: TriggerDraft;
routineTitle: string;
routineId: string;
routineActive?: boolean;
webhookUrl?: string;
webhookSecret?: string;
onCreateWebhook?: (draft: TriggerDraft) => Promise<void>;
onRotateKey?: () => Promise<void>;
onSaveExit: (draft: TriggerDraft) => void | Promise<void>;
onFinish: (draft: TriggerDraft) => void | Promise<void>;
checkResult?: "waiting" | "received" | "rejected" | "no_event";
}) {
const [draft, setDraft] = useState(initialDraft);
const [busy, setBusy] = useState(false);
const [saveError, setSaveError] = useState("");
const { setBreadcrumbs } = useBreadcrumbs();
const perform = useCallback(
async (action: () => void | Promise<void>) => {
if (busy) return;
setBusy(true);
setSaveError("");
try {
await action();
} catch (error) {
setSaveError(
error instanceof Error
? error.message
: "Couldn’t save. Please try again.",
);
} finally {
setBusy(false);
}
},
[busy],
);
const saveAndExit = useCallback(() => {
void perform(() => onSaveExit(draft));
}, [draft, onSaveExit, perform]);
useEffect(() => {
setBreadcrumbs([
{
label: routineTitle,
href: `/routines/${routineId}/triggers`,
onClick: (event) => {
if (
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
)
return;
event.preventDefault();
saveAndExit();
},
},
{ label: "Add trigger" },
]);
}, [saveAndExit, setBreadcrumbs, routineTitle, routineId]);
const schedule = draft.kind === "schedule";
const github = draft.sender === "github";
const labels = schedule
? ["Choose trigger", "Set schedule", "Review schedule"]
: ["Choose trigger", "Connect your app", "Check connection"];
function patch(values: Partial<TriggerDraft>) {
setDraft((current) => ({ ...current, ...values }));
}
function advance() {
void perform(async () => {
if (draft.kind === "webhook" && draft.step === 0 && !draft.created)
await onCreateWebhook?.(draft);
const step = draft.step + 1;
patch({
step,
availableStep: Math.max(draft.availableStep, step),
created:
draft.created || (draft.kind === "webhook" && draft.step === 0),
});
});
}
const title =
draft.step === 0
? "When should this routine run?"
: schedule
? draft.step === 1
? "Set a schedule"
: "Review your schedule"
: draft.step === 1
? `Connect ${github ? "GitHub" : "your app"}`
: "Check your connection";
const subtitle =
draft.step === 0
? `Choose how to start “${routineTitle}”. You can add another trigger later.`
: schedule
? draft.step === 1
? "Choose when Paperclip should start this routine automatically."
: "This schedule starts the routine automatically. You can pause or change it later."
: draft.step === 1
? "Copy these details into the sending app, then save its webhook settings."
: "Test that events arrive and authentication works. This won’t start the routine.";
const selectClass =
"w-full rounded-md border border-input bg-background px-3 py-2 text-sm";
const goBack = (
<Button variant="outline" onClick={() => patch({ step: draft.step - 1 })}>
Back
</Button>
);
return (
<div className="min-w-0 w-full max-w-2xl space-y-6">
<SetupWizardNavigation
takeover
disabled={busy}
ariaLabel="Trigger setup progress"
labels={labels}
step={draft.step}
availableStep={draft.availableStep}
onSelect={(step) => patch({ step })}
/>
<fieldset disabled={busy} className="min-w-0 space-y-6">
<div className="space-y-1">
<h1 className="text-xl font-bold">{title}</h1>
<p className="text-sm text-muted-foreground">{subtitle}</p>
</div>
{!schedule && draft.step > 0 && <WebhookUrlWarning url={webhookUrl} />}
{draft.step === 0 && (
<fieldset className="space-y-3">
<legend className="sr-only">Trigger type</legend>
{(
[
{
kind: "schedule",
label: "On a schedule",
detail: "Every day, on weekdays, or once a week.",
Icon: CalendarClock,
},
{
kind: "webhook",
label: "When another app sends a webhook",
detail:
"When something happens in GitHub, another app, or a script.",
Icon: Webhook,
},
] as const
).map(({ kind, label, detail, Icon }) => (
<label
key={kind}
className={cn(
"flex cursor-pointer items-start gap-3 rounded-md border p-4 focus-within:ring-2 focus-within:ring-ring",
draft.kind === kind
? "border-primary bg-accent/30"
: "border-border hover:bg-accent/20",
)}
>
<input
type="radio"
name="trigger-kind"
checked={draft.kind === kind}
disabled={draft.created && kind !== draft.kind}
onChange={() =>
patch({
kind,
availableStep:
kind === draft.kind ? draft.availableStep : 0,
})
}
className="sr-only"
/>
<Icon className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
<span className="flex-1">
<span className="block text-sm font-medium">{label}</span>
<span className="block text-xs text-muted-foreground">
{detail}
</span>
</span>
{draft.kind === kind && <Check className="h-4 w-4" />}
</label>
))}
</fieldset>
)}
{schedule && draft.step === 1 && (
<div className="space-y-5">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="repeat">Repeat</Label>
<select
id="repeat"
className={selectClass}
value={draft.frequency}
onChange={(event) => patch({ frequency: event.target.value })}
>
<option value="daily">Every day</option>
<option value="weekdays">Weekdays (Monday–Friday)</option>
<option value="weekly">Every week</option>
</select>
</div>
<div className="space-y-2">
<Label htmlFor="run-time">Time</Label>
<Input
id="run-time"
type="time"
value={draft.time}
onChange={(event) => patch({ time: event.target.value })}
/>
</div>
</div>
{draft.frequency === "weekly" && (
<div className="space-y-2">
<Label htmlFor="run-day">Day</Label>
<select
id="run-day"
className={selectClass}
value={draft.weekday}
onChange={(event) => patch({ weekday: event.target.value })}
>
{[
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
].map((day) => (
<option key={day}>{day}</option>
))}
</select>
</div>
)}
<div className="space-y-2">
<Label htmlFor="timezone">Time zone</Label>
<select
id="timezone"
className={selectClass}
value={draft.timezone}
onChange={(event) => patch({ timezone: event.target.value })}
>
{Array.from(
new Set([
draft.timezone,
"America/Chicago",
"America/New_York",
"America/Los_Angeles",
"Europe/London",
"UTC",
]),
).map((zone) => (
<option key={zone}>{zone}</option>
))}
</select>
<p className="text-xs text-muted-foreground">
The time follows this zone, including daylight saving changes.
</p>
</div>
</div>
)}
{schedule && draft.step === 2 && (
<div className="space-y-5">
<div className="flex items-start gap-3 rounded-md bg-muted/40 p-4">
<CalendarClock className="h-5 w-5 text-muted-foreground" />
<div>
<p className="text-sm font-medium">{describeSchedule(draft)}</p>
<p className="text-xs text-muted-foreground">
{draft.timezone}
</p>
</div>
</div>
<p className="text-sm text-muted-foreground">
Each scheduled run creates a task for the routine’s assigned
agent. Any existing webhook triggers will continue to work.
</p>
</div>
)}
{draft.step === 0 && draft.kind === "webhook" && (
<fieldset className="space-y-2">
<legend className="mb-2 text-sm font-medium">
What’s sending the webhook?
</legend>
<div className="grid gap-2 sm:grid-cols-2">
{(
[
{
sender: "custom",
label: "Another app or script",
Icon: Globe,
},
{ sender: "github", label: "GitHub", Icon: GitBranch },
] as const
).map(({ sender, label, Icon }) => (
<label
key={sender}
className={cn(
"flex cursor-pointer items-center gap-3 rounded-md border p-3 focus-within:ring-2 focus-within:ring-ring",
draft.sender === sender
? "border-primary bg-accent/30"
: "border-border",
draft.created && "cursor-default",
)}
>
<input
className="sr-only"
type="radio"
name="sender"
checked={draft.sender === sender}
disabled={draft.created}
onChange={() => patch({ sender })}
/>
<Icon className="h-4 w-4" />
<span className="flex-1 text-sm">{label}</span>
{draft.sender === sender && <Check className="h-4 w-4" />}
</label>
))}
</div>
</fieldset>
)}
{draft.kind === "webhook" && draft.step === 0 && (
<p className="text-sm text-muted-foreground">
Public services need a publicly reachable HTTPS webhook URL.
</p>
)}
{!schedule && draft.step === 1 && (
<div className="space-y-5">
{webhookSecret && (
<AgentInstructions
value={webhookAgentInstructions(
draft.sender,
routineTitle,
webhookUrl,
webhookSecret,
true,
draft.signingMode,
)}
/>
)}
<CopyField
label={github ? "Payload URL" : "Webhook URL"}
value={webhookUrl}
/>
{!github && draft.signingMode !== "bearer" && (
<p className="text-sm text-muted-foreground">
Paste this key into your app’s signing secret field.
{draft.signingMode !== "fireflies_hmac" && <>
{" "}If your app uses custom headers instead, set Authorization to Bearer followed
by a space and this key.
</>}
</p>
)}
{webhookSecret ? (
<CopyField
label={github ? "Secret" : draft.signingMode === "bearer" ? "Authorization header value" : "Secret key"}
value={!github && draft.signingMode === "bearer" ? `Bearer ${webhookSecret}` : webhookSecret}
/>
) : (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
The key is hidden after leaving setup. If you haven’t saved it
in your app, generate a replacement.
</p>
<Button
variant="outline"
onClick={() => void perform(() => onRotateKey?.())}
>
Generate new key
</Button>
</div>
)}
</div>
)}
{!schedule && draft.step === 2 && (
<div className="space-y-5">
<div className="space-y-1 rounded-md border border-border p-4">
<p className="text-sm font-medium">Connection test only</p>
<p className="text-sm text-muted-foreground">
Events received during setup won’t start the routine or create
tasks.
</p>
</div>
<div className="space-y-2">
<p className="text-sm font-medium">
Send an event from {github ? "GitHub" : "your app"}
</p>
<p className="text-sm text-muted-foreground">
{github
? "Open this webhook in your repository settings. Under Recent Deliveries, choose Redeliver on an event."
: "Look for “Send test” in your app’s webhook settings. If it doesn’t have one, do the action that should trigger the webhook—for example, complete a deployment."}
</p>
<p className="text-xs text-muted-foreground">
Keep this page open to see the test result.
</p>
</div>
<div
role="status"
className="flex items-start gap-3 rounded-md bg-muted/40 p-4"
>
{checkResult === "received" ? (
<CheckCircle2 className="h-5 w-5 shrink-0 text-(--status-task-done)" />
) : checkResult === "rejected" ? (
<AlertCircle className="h-5 w-5 shrink-0 text-destructive" />
) : (
<Radio className="h-5 w-5 shrink-0 text-muted-foreground" />
)}
<div className="space-y-1">
<p className="text-sm font-medium">
{checkResult === "received"
? "Test event received · Connection working"
: checkResult === "rejected"
? "Event arrived, but the key was rejected"
: checkResult === "no_event"
? "No event received yet"
: "Waiting for an event from your app…"}
</p>
<p className="text-xs text-muted-foreground">
{checkResult === "received"
? "Authentication passed. No routine run or task was created."
: checkResult === "rejected"
? "Go back to Connect your app, update the key in your sending app, and resend. No task was created."
: "Waiting to verify delivery and authentication. The routine is not running."}
</p>
</div>
</div>
<details>
<summary className="cursor-pointer text-xs text-muted-foreground">
Troubleshoot delivery
</summary>
<div className="space-y-3 pt-3">
<p className="text-xs text-muted-foreground">
Check that the webhook is enabled in your sending app and that
its URL matches. Scripts must send POST with a JSON body.
</p>
<CopyField label="Webhook URL" value={webhookUrl} />
</div>
</details>
</div>
)}
{!schedule && draft.step === 2 && (
<p className="text-xs text-muted-foreground">
{routineActive
? "Finish setup to enable this webhook. Future events will start the routine; this test event won’t be replayed."
: "Finish setup to save this webhook. The routine is paused; enable its automatic triggers when you’re ready. This test event won’t be replayed."}
</p>
)}
{schedule && draft.step === 2 && !routineActive && (
<p className="text-sm text-muted-foreground">
The routine is paused. Enable its automatic triggers when you’re
ready to use this schedule.
</p>
)}
{saveError && (
<p role="alert" className="text-sm text-destructive">
{saveError}
</p>
)}
<SetupWizardFooter onSaveExit={saveAndExit}>
{draft.step > 0 && goBack}
{draft.step === 0 ? (
<Button disabled={draft.kind === "choose"} onClick={advance}>
Continue
</Button>
) : schedule ? (
draft.step === 1 ? (
<Button disabled={!draft.time} onClick={advance}>
Review schedule
</Button>
) : (
<Button onClick={() => void perform(() => onFinish(draft))}>
Add schedule
</Button>
)
) : draft.step === 1 ? (
<Button onClick={advance}>Check connection</Button>
) : (
<Button onClick={() => void perform(() => onFinish(draft))}>
{checkResult === "received"
? "Finish setup"
: "Finish without checking"}
</Button>
)}
</SetupWizardFooter>
</fieldset>
</div>
);
}
@@ -0,0 +1,41 @@
import { expect, it } from "vitest";
import { webhookAgentInstructions, webhookInstructionSigningMode } from "./webhook-instructions";
it("explains both supported app authentication methods", () => {
const instructions = webhookAgentInstructions("custom", "Meetings", "https://paperclip.example/webhook", "signing-secret");
expect(instructions).toContain("Secret key: signing-secret");
expect(instructions).toContain("X-Hub-Signature");
expect(instructions).toContain("Authorization: Bearer signing-secret");
expect(instructions).toContain("They do not start the routine");
expect(instructions).not.toContain("Fireflies");
});
it("keeps legacy bearer setup instructions accurate", () => {
const instructions = webhookAgentInstructions("custom", "Meetings", "https://paperclip.example/webhook", "secret", true, "bearer");
expect(instructions).toContain("Authorization: Bearer secret");
expect(instructions).not.toContain("HMAC-SHA256");
});
it("tells GitHub users to paste the secret instead of using a bearer header", () => {
const instructions = webhookAgentInstructions("github", "Deploys", "https://paperclip.example/webhook", "gh-secret", false);
expect(instructions).toContain("Secret: gh-secret");
expect(instructions).toContain("X-Hub-Signature-256");
expect(instructions).toContain("Deliveries can start the routine");
});
it("explains timestamp signing for hmac_sha256 webhooks instead of bearer or X-Hub-Signature", () => {
const instructions = webhookAgentInstructions("custom", "Deploys", "https://paperclip.example/webhook", "hmac-secret", false, webhookInstructionSigningMode("hmac_sha256"));
expect(instructions).toContain("X-Paperclip-Timestamp");
expect(instructions).toContain("X-Paperclip-Signature");
expect(instructions).not.toContain("Authorization: Bearer");
expect(instructions).not.toContain("X-Hub-Signature");
});
it("gives no key instructions for a webhook without a key", () => {
const instructions = webhookAgentInstructions("custom", "Deploys", "https://paperclip.example/webhook", "", false, webhookInstructionSigningMode("none"));
expect(instructions).toContain("Its URL is the shared secret");
expect(instructions).not.toContain("Secret key:");
expect(instructions).toContain("Store the URL securely");
expect(instructions).not.toContain("Store the key securely");
expect(webhookInstructionSigningMode("something-new")).toBe("app_webhook");
});
@@ -0,0 +1,80 @@
export type WebhookInstructionSender = "custom" | "github";
export type WebhookInstructionSigningMode = "app_webhook" | "bearer" | "fireflies_hmac" | "hmac_sha256" | "none";
const SIGNING_MODES: readonly WebhookInstructionSigningMode[] = ["app_webhook", "bearer", "fireflies_hmac", "hmac_sha256", "none"];
/** The instruction set for a saved webhook's signing mode; unknown modes read as the shared app flow. */
export function webhookInstructionSigningMode(mode: string | null | undefined): WebhookInstructionSigningMode {
return SIGNING_MODES.includes(mode as WebhookInstructionSigningMode) ? mode as WebhookInstructionSigningMode : "app_webhook";
}
/** Copyable setup instructions for whoever (or whichever agent) connects the sending app. */
export function webhookAgentInstructions(
sender: WebhookInstructionSender,
routineTitle: string,
webhookUrl: string,
webhookSecret: string,
setupPending = true,
signingMode: WebhookInstructionSigningMode = "app_webhook",
) {
const common = [
`Connect the sending app to the Paperclip routine ${JSON.stringify(routineTitle)}.`,
`Webhook URL: ${webhookUrl}`,
"Send an HTTP POST request with a JSON object as the body (not an array or string).",
"Content-Type: application/json",
];
const auth =
sender === "github"
? [
"In GitHub, open your repository → Settings → Webhooks → Add webhook.",
"Use the webhook URL above as Payload URL and select application/json as Content type.",
`Secret: ${webhookSecret}`,
"Paste this value into GitHub’s Secret field. GitHub signs requests with X-Hub-Signature-256; do not use Bearer authentication.",
"Select the events that should start this routine, enable the webhook, and save.",
"To check the connection, open Recent Deliveries and redeliver an event.",
]
: signingMode === "none"
? [
"This webhook has no key. Its URL is the shared secret, so keep it private.",
"In the sending app, add a webhook using this URL, POST method and JSON body, then save it.",
"Send a unique Idempotency-Key header for each event and reuse it on retries.",
]
: signingMode === "hmac_sha256"
? [
`Secret key: ${webhookSecret}`,
"Sign each request with HMAC-SHA256 using the secret key. The signed message is the Unix timestamp in seconds, a period, and the exact JSON body.",
"Send the timestamp in X-Paperclip-Timestamp and the signature in X-Paperclip-Signature, formatted sha256=<hex digest>.",
"Requests with an old timestamp are rejected, so sign each request when you send it. Do not use Bearer authentication.",
"Send a unique Idempotency-Key header for each event and reuse it on retries.",
]
: [
`Secret key: ${webhookSecret}`,
...(signingMode === "bearer" ? [] : [
`If the app asks for a signing secret, paste the secret key above. Paperclip accepts HMAC-SHA256 over the exact request body in ${signingMode === "fireflies_hmac" ? "X-Hub-Signature" : "X-Hub-Signature or X-Hub-Signature-256"}, formatted sha256=<hex digest>.`,
]),
...(signingMode === "fireflies_hmac" ? [] : [
`For apps with custom headers, use Authorization: Bearer ${webhookSecret}`,
]),
"Subscribe only to the events that should start this routine. Public services need a publicly reachable HTTPS URL.",
"In the sending app, add a webhook using this URL, POST method, JSON body, and headers, then save it.",
"Send a unique Idempotency-Key header for each event and reuse it on retries, so retrying a setup test after activation cannot start the routine.",
'Example JSON body: {"event":"deployment.completed","environment":"production"}',
"To check the connection, send a test event from the app or perform the action that triggers a delivery.",
];
return [
...common,
...auth,
"The webhook in Paperclip shows whether the event arrived and authentication passed.",
...(setupPending
? [
"During setup, deliveries only test the connection. They do not start the routine or create a task.",
"Finish in Paperclip to enable this webhook for future events. Test events are not replayed.",
]
: [
"This webhook is enabled. Deliveries can start the routine and create tasks.",
]),
signingMode === "none"
? "Store the URL securely; do not put it in source control or logs."
: "Store the key securely; do not put it in source control or logs.",
].join("\n");
}