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,94 @@
import { useMemo, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Routine } from "@paperclipai/shared";
import { describeError } from "@/api/errors";
import { routinesApi } from "@/api/routines";
import { useToastActions } from "@/context/ToastContext";
import { queryKeys } from "@/lib/queryKeys";
import { useNavigate } from "@/lib/router";
import { EMPTY_ROUTINE_FORM_DRAFT, RoutineEditDialog, type RoutineFormDraft } from "./RoutineEditDialog";
import { routineFieldsPayload, syncRoutineResponsibility } from "./routine-form";
import { routinePath } from "./routine-routes";
import { useRoutineFormOptions } from "./useRoutineFormOptions";
/**
* The routines list's "Create routine": the routine edit form in create mode.
* A new routine is filed in `folderId` (the folder the list is showing) and
* gets the default priority and delivery settings. Webhooks are added from the
* routine page once it exists.
*/
export function RoutineCreateDialog({
companyId,
open,
onOpenChange,
folderId = null,
}: {
companyId: string;
open: boolean;
onOpenChange: (open: boolean) => void;
folderId?: string | null;
}) {
const queryClient = useQueryClient();
const navigate = useNavigate();
const { pushToast } = useToastActions();
const options = useRoutineFormOptions(companyId, { active: open });
const [error, setError] = useState<string | null>(null);
const initial = useMemo<RoutineFormDraft>(() => ({ ...EMPTY_ROUTINE_FORM_DRAFT }), [open]);
const create = useMutation({
mutationFn: async (draft: RoutineFormDraft) => {
const routine: Routine = await routinesApi.create(companyId, {
...routineFieldsPayload(draft),
...(folderId ? { folderId } : {}),
});
// Anything after this point is best effort: the routine exists, so report what is missing instead of failing.
const missing: string[] = [];
if (draft.responsibleUserId && draft.responsibleUserId !== routine.responsibleUserId) {
await routinesApi.update(routine.id, { responsibleUserId: draft.responsibleUserId }).catch(() => missing.push("the responsible user"));
}
if (draft.schedule) {
await routinesApi
.createTrigger(routine.id, { kind: "schedule", cronExpression: draft.schedule.cronExpression, timezone: draft.schedule.timezone })
.catch(() => missing.push("the schedule"));
}
if (options.responsibilitiesOn && draft.responsibilityId) {
await syncRoutineResponsibility(routine.id, "", draft.responsibilityId).catch(() => missing.push("the responsibility"));
}
return { routine, missing };
},
onMutate: () => setError(null),
onSuccess: async ({ routine, missing }) => {
onOpenChange(false);
pushToast(
missing.length > 0
? { title: "Routine created", body: `Couldn’t save ${missing.join(" and ")}. Open Edit to try again.`, tone: "warn" }
: { title: "Routine created", tone: "success" },
);
await queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(companyId) });
navigate(routinePath(routine.id));
},
onError: (cause) => setError(describeError(cause, { action: "create the routine" }).body),
});
return (
<RoutineEditDialog
open={open}
onOpenChange={(next) => {
if (!next) setError(null);
onOpenChange(next);
}}
mode="create"
initial={initial}
agents={options.agents}
projects={options.projects}
people={options.people}
secrets={options.secrets}
responsibilities={options.responsibilities}
mentions={options.mentions}
saving={create.isPending}
error={error ?? (options.loadErrors.length > 0 ? "Some choices couldn’t be loaded. Close this and try again." : null)}
onSave={(draft) => create.mutate(draft)}
onCreateSecret={options.createSecret}
/>
);
}
@@ -0,0 +1,127 @@
// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EMPTY_ROUTINE_FORM_DRAFT, RoutineEditDialog, type RoutineFormDraft } from "./RoutineEditDialog";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
vi.mock("@/components/MarkdownEditor", () => ({ MarkdownEditor: () => <div data-testid="markdown-editor" /> }));
vi.mock("@/components/RoutineVariablesEditor", () => ({ RoutineVariablesEditor: () => null }));
async function act(callback: () => void | Promise<void>) {
let result: void | Promise<void> = undefined;
flushSync(() => {
result = callback();
});
await result;
}
async function flush() {
for (let index = 0; index < 3; index += 1) {
await Promise.resolve();
await new Promise((resolve) => window.setTimeout(resolve, 0));
}
}
function type(input: HTMLInputElement, value: string) {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
input.dispatchEvent(new Event("input", { bubbles: true }));
}
function button(name: string) {
return Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((element) => element.textContent?.trim() === name);
}
const initial: RoutineFormDraft = { ...EMPTY_ROUTINE_FORM_DRAFT, title: "Send the weekly digest", responsibleUserId: "user-1" };
const people = [
{ id: "user-1", name: "Riley Board" },
{ id: "user-2", name: "Sam Ops" },
];
describe("RoutineEditDialog", () => {
let container: HTMLDivElement;
let root: Root;
const onSave = vi.fn();
async function render(draft: RoutineFormDraft = initial) {
await act(async () => {
root.render(
<RoutineEditDialog
open
onOpenChange={() => {}}
initial={draft}
agents={[]}
projects={[]}
people={people}
secrets={[]}
onSave={onSave}
onCreateSecret={vi.fn()}
/>,
);
await flush();
});
}
beforeEach(() => {
onSave.mockReset();
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(async () => {
await act(() => root.unmount());
container.remove();
document.body.innerHTML = "";
});
it("saves a change made only to Secrets", async () => {
await render();
expect(button("Save changes")?.disabled).toBe(true);
await act(async () => { button("Add secret")!.click(); await flush(); });
const name = document.querySelector<HTMLInputElement>('input[aria-label="Variable name"]')!;
await act(async () => { type(name, "API_TOKEN"); await flush(); });
const value = document.querySelector<HTMLInputElement>('input[aria-label="Variable value"]')!;
await act(async () => { type(value, "plain-value"); await flush(); });
expect(button("Save changes")?.disabled).toBe(false);
await act(async () => { button("Save changes")!.click(); await flush(); });
expect(onSave).toHaveBeenCalledTimes(1);
expect(onSave.mock.calls[0]![0].env).toMatchObject({ API_TOKEN: expect.anything() });
});
it("asks before discarding a change made only to Secrets", async () => {
await render();
await act(async () => { button("Add secret")!.click(); await flush(); });
const name = document.querySelector<HTMLInputElement>('input[aria-label="Variable name"]')!;
await act(async () => { type(name, "API_TOKEN"); await flush(); });
await act(async () => { button("Cancel")!.click(); await flush(); });
expect(document.body.textContent).toContain("Discard your changes?");
});
it("keeps the draft open while saving, whatever closes it", async () => {
const onOpenChange = vi.fn();
await act(async () => {
root.render(
<RoutineEditDialog open onOpenChange={onOpenChange} initial={initial} agents={[]} projects={[]} people={people}
secrets={[]} saving onSave={onSave} onCreateSecret={vi.fn()} />,
);
await flush();
});
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
await act(async () => { await flush(); });
const close = document.querySelector<HTMLButtonElement>('[data-slot="dialog-close"], button[aria-label="Close"]');
if (close) await act(async () => { close.click(); await flush(); });
expect(onOpenChange).not.toHaveBeenCalled();
expect(document.querySelector('[role="dialog"]')).not.toBeNull();
});
it("does not offer clearing a responsible user, which the server cannot do", async () => {
await render();
const picker = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((element) => element.textContent?.includes("Riley Board"))!;
await act(async () => { picker.click(); await flush(); });
expect(document.body.textContent).toContain("Sam Ops");
expect(Array.from(document.querySelectorAll('[role="option"], button')).some((element) => element.textContent?.trim() === "No one")).toBe(false);
});
});
@@ -0,0 +1,543 @@
import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
import type { CompanySecret, EnvBinding, RoutineEnvConfig, RoutineTrigger, RoutineVariable } from "@paperclipai/shared";
import { GitBranch, Plus, Webhook, X } from "lucide-react";
import { AgentAvatar } from "@/components/AgentAvatar";
import { InlineEntitySelector } from "@/components/InlineEntitySelector";
import { MarkdownEditor, type MarkdownEditorRef, type MentionOption } from "@/components/MarkdownEditor";
import { RoutineVariablesEditor } from "@/components/RoutineVariablesEditor";
import { ScheduleEditor } from "@/components/ScheduleEditor";
import { EnvironmentVariablesEditor, type EnvironmentVariablesEditorHandle } from "@/components/environment-variables-editor";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { deriveInitials } from "@/components/Identity";
import { cn } from "@/lib/utils";
import type { RoutinePageAgent, RoutinePageProject, RoutinePerson } from "./RoutinePage";
import { WEBHOOK_HEALTH_LABELS, webhookHealth, webhookTitle } from "./routine-summary";
export type RoutineFormDraft = {
title: string;
description: string;
projectId: string;
assigneeAgentId: string;
responsibleUserId: string;
/** The responsibility this routine is filed under itself; empty for none. */
responsibilityId: string;
variables: RoutineVariable[];
env: RoutineEnvConfig | null;
schedule: { cronExpression: string; timezone: string } | null;
};
export const EMPTY_ROUTINE_FORM_DRAFT: RoutineFormDraft = {
title: "",
description: "",
projectId: "",
assigneeAgentId: "",
responsibleUserId: "",
responsibilityId: "",
variables: [],
env: null,
schedule: null,
};
export type RoutineResponsibilityOption = {
id: string;
title: string;
areaTitle?: string | null;
/** Projects filed under it. A routine in one of them is already under this responsibility. */
projectIds?: readonly string[];
};
export type RoutineEditDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
mode?: "edit" | "create";
initial: RoutineFormDraft;
agents: readonly RoutinePageAgent[];
projects: readonly RoutinePageProject[];
people: readonly RoutinePerson[];
secrets: readonly CompanySecret[];
/** Leave undefined while areas of responsibility are switched off; the field is then hidden. */
responsibilities?: readonly RoutineResponsibilityOption[];
mentions?: MentionOption[];
/** False when this person may not reassign responsibility. */
canChangeResponsibleUser?: boolean;
saving?: boolean;
/** Someone else saved this routine while the form was open. */
saveConflict?: boolean;
error?: string | null;
onSave: (draft: RoutineFormDraft) => void;
onReloadLatest?: () => void;
onCreateSecret: (name: string, value: string) => Promise<CompanySecret>;
/** Saved webhooks. They are created and changed right away, apart from the form's Save. */
webhooks?: readonly RoutineTrigger[];
/** Opens the webhook dialog; `null` starts a new webhook. Omit while creating a routine. */
onOpenWebhook?: (trigger: RoutineTrigger | null) => void;
onRemoveWebhook?: (trigger: RoutineTrigger) => void;
/** Webhooks removed while this form is open, offered back with Undo. */
removedWebhooks?: readonly RoutineTrigger[];
onRestoreWebhook?: (trigger: RoutineTrigger) => void;
/** The webhook dialog, rendered inside this one so both stay open together. */
children?: ReactNode;
};
const SCHEDULE_TIMEZONES = ["America/Los_Angeles", "America/Chicago", "America/New_York", "Europe/London", "UTC"];
function localTimezone(): string {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
} catch {
return "UTC";
}
}
export function RoutineEditDialog({
open,
onOpenChange,
mode = "edit",
initial,
agents,
projects,
people,
secrets,
responsibilities,
mentions,
canChangeResponsibleUser = true,
saving = false,
saveConflict = false,
error = null,
onSave,
onReloadLatest,
onCreateSecret,
webhooks = [],
onOpenWebhook,
onRemoveWebhook,
removedWebhooks = [],
onRestoreWebhook,
children,
}: RoutineEditDialogProps) {
const [draft, setDraft] = useState(initial);
const [secretsOpen, setSecretsOpen] = useState(() => Object.keys(initial.env ?? {}).length > 0);
const [scheduleValid, setScheduleValid] = useState(true);
const [confirmingDiscard, setConfirmingDiscard] = useState(false);
const editorRef = useRef<MarkdownEditorRef>(null);
const secretsRef = useRef<EnvironmentVariablesEditorHandle>(null);
/** Secrets rows being typed that the secrets editor has not promoted into the draft yet. */
const [secretsDirty, setSecretsDirty] = useState(false);
const titleId = useId();
useEffect(() => {
if (!open) return;
setDraft(initial);
setSecretsOpen(Object.keys(initial.env ?? {}).length > 0);
setConfirmingDiscard(false);
setSecretsDirty(false);
}, [initial, open]);
const dirty = useMemo(() => JSON.stringify(draft) !== JSON.stringify(initial), [draft, initial]) || secretsDirty;
const patch = (change: Partial<RoutineFormDraft>) => setDraft((current) => ({ ...current, ...change }));
const agentById = useMemo(() => new Map(agents.map((agent) => [agent.id, agent])), [agents]);
const projectById = useMemo(() => new Map(projects.map((project) => [project.id, project])), [projects]);
const personById = useMemo(() => new Map(people.map((person) => [person.id, person])), [people]);
const responsibilityById = useMemo(
() => new Map((responsibilities ?? []).map((responsibility) => [responsibility.id, responsibility])),
[responsibilities],
);
const throughProject = draft.projectId
? (responsibilities ?? []).find(
(responsibility) => responsibility.id !== draft.responsibilityId && responsibility.projectIds?.includes(draft.projectId),
) ?? null
: null;
const canSave = draft.title.trim().length > 0 && scheduleValid && !saving && !saveConflict && (mode === "create" || dirty);
/** Saves the draft, including secrets rows still being typed. */
const submit = () => {
if (!canSave) return;
const flushed = secretsRef.current?.flushPendingDraft() ?? null;
onSave(flushed ? { ...draft, env: Object.keys(flushed).length > 0 ? flushed : null } : draft);
};
/** Escape, the close button and Cancel all come here. Nothing closes while a save is running, so a failed save keeps the draft and its error. */
const requestClose = () => {
if (saving) return;
if (dirty) setConfirmingDiscard(true);
else onOpenChange(false);
};
const personOption = (id: string) => {
const person = personById.get(id);
if (!person) return null;
return (
<>
<Avatar size="xs" aria-hidden="true">
{person.avatarUrl ? <AvatarImage src={person.avatarUrl} alt="" /> : null}
<AvatarFallback>{deriveInitials(person.name)}</AvatarFallback>
</Avatar>
<span className="truncate">{person.name}</span>
</>
);
};
return (
<Dialog open={open} onOpenChange={(next) => (next ? onOpenChange(true) : requestClose())}>
<DialogContent className="flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 sm:max-w-3xl">
<DialogHeader className="px-6 pb-4 pt-6">
<DialogTitle>{mode === "create" ? "New routine" : "Edit routine"}</DialogTitle>
<DialogDescription className="sr-only">
{mode === "create" ? "Describe the work, then choose who does it and when." : "Change what this routine does, who does it, and when."}
</DialogDescription>
</DialogHeader>
<form
id={`${titleId}-form`}
className="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto px-6 pb-6 [&>*]:shrink-0"
onSubmit={(event) => {
event.preventDefault();
submit();
}}
>
<div className="flex flex-col gap-2">
<Label htmlFor={titleId}>Title</Label>
<Input
id={titleId}
value={draft.title}
autoFocus={mode === "create"}
placeholder="Send the weekly digest"
onChange={(event) => patch({ title: event.target.value })}
/>
</div>
<div className="flex flex-col gap-2">
<Label>Instructions</Label>
{/* The frame owns the border and the drag handle; the editor scrolls inside it. */}
<div
className="h-48 min-h-32 resize-y overflow-y-auto rounded-md border border-border px-3 py-2 focus-within:border-ring"
onClick={(event) => {
if (event.target === event.currentTarget) editorRef.current?.focus();
}}
>
<MarkdownEditor
ref={editorRef}
bordered={false}
ariaLabel="Instructions"
value={draft.description}
onChange={(description) => patch({ description })}
placeholder="What should the agent do each time? Type / for skills and routines, @ to mention, {{name}} to ask for a value."
contentClassName="text-sm leading-6"
mentions={mentions}
submitKey="mod-enter"
onSubmit={submit}
/>
</div>
</div>
<RoutineVariablesEditor
title={draft.title}
description={draft.description}
value={draft.variables}
onChange={(variables) => patch({ variables })}
variant="compact"
/>
<div className="flex flex-col gap-2">
<Label>Repeats</Label>
{draft.schedule ? (
<div className="flex flex-col gap-3">
<ScheduleEditor
inline
value={draft.schedule.cronExpression}
onChange={(cronExpression) =>
setDraft((current) => (current.schedule ? { ...current, schedule: { ...current.schedule, cronExpression } } : current))
}
onValidityChange={setScheduleValid}
trailing={(
<Select
value={draft.schedule.timezone}
onValueChange={(timezone) =>
setDraft((current) => (current.schedule ? { ...current, schedule: { ...current.schedule, timezone } } : current))
}
>
<SelectTrigger className="w-48" aria-label="Time zone">
<SelectValue />
</SelectTrigger>
<SelectContent>
{Array.from(new Set([draft.schedule.timezone, localTimezone(), ...SCHEDULE_TIMEZONES])).map((zone) => (
<SelectItem key={zone} value={zone}>{zone}</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
<Button
type="button"
variant="ghost"
size="sm"
className="-mx-2 w-fit text-muted-foreground"
onClick={() => {
setScheduleValid(true);
patch({ schedule: null });
}}
>
Remove schedule
</Button>
</div>
) : (
<Button
type="button"
variant="outline"
size="sm"
className="w-fit"
onClick={() => patch({ schedule: { cronExpression: "0 9 * * 1-5", timezone: localTimezone() } })}
>
<Plus className="h-3.5 w-3.5" />
Add schedule
</Button>
)}
</div>
{onOpenWebhook ? (
<div className="flex flex-col gap-2">
<Label>Webhooks</Label>
{removedWebhooks.map((trigger) => (
<p key={trigger.id} role="status" className="flex max-w-md items-center gap-2 text-sm text-muted-foreground">
<span className="min-w-0 flex-1 truncate">{webhookTitle(trigger)} removed.</span>
<Button type="button" variant="ghost" size="xs" onClick={() => onRestoreWebhook?.(trigger)}>Undo</Button>
</p>
))}
{webhooks.length > 0 ? (
<ul className="flex max-w-md flex-col">
{webhooks.map((trigger) => {
const health = webhookHealth(trigger);
const Icon = trigger.signingMode === "github_hmac" ? GitBranch : Webhook;
return (
<li key={trigger.id} className="group/webhook -mx-2 flex items-center rounded-md hover:bg-accent/50 focus-within:bg-accent/50">
<button
type="button"
aria-label={`Configure ${webhookTitle(trigger)}`}
className="flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => onOpenWebhook(trigger)}
>
<Icon className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
<span className="min-w-0 flex-1 truncate font-medium">{webhookTitle(trigger)}</span>
<span className={cn("shrink-0 text-xs", health === "rejected" ? "text-destructive" : "text-muted-foreground")}>
{WEBHOOK_HEALTH_LABELS[health]}
</span>
</button>
{onRemoveWebhook ? (
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-label={`Remove ${webhookTitle(trigger)}`}
className="mr-1 text-muted-foreground opacity-0 hover:text-destructive focus-visible:opacity-100 group-hover/webhook:opacity-100 group-focus-within/webhook:opacity-100"
onClick={() => onRemoveWebhook(trigger)}
>
<X />
</Button>
) : null}
</li>
);
})}
</ul>
) : null}
<Button type="button" variant="outline" size="sm" className="w-fit" onClick={() => onOpenWebhook(null)}>
<Plus className="h-3.5 w-3.5" />
Add webhook
</Button>
</div>
) : null}
<div className="flex max-w-xs flex-col gap-6">
<div className="flex min-w-0 flex-col gap-2">
<Label>Default agent</Label>
<InlineEntitySelector
value={draft.assigneeAgentId}
options={agents.map((agent) => ({ id: agent.id, label: agent.name }))}
placeholder="Choose an agent"
noneLabel="No default agent"
searchPlaceholder="Search agents…"
emptyMessage="No agents found."
disablePortal
className="h-9 w-full justify-start"
onChange={(assigneeAgentId) => patch({ assigneeAgentId })}
renderTriggerValue={(option) => {
const agent = option ? agentById.get(option.id) : null;
return agent ? (
<>
<AgentAvatar agent={agent} size={20} className="shrink-0" />
<span className="truncate">{agent.name}</span>
</>
) : (
<span className="text-muted-foreground">Choose an agent</span>
);
}}
renderOption={(option) => {
const agent = agentById.get(option.id);
return (
<>
{agent ? <AgentAvatar agent={agent} size={20} className="shrink-0" /> : null}
<span className="truncate">{option.label}</span>
</>
);
}}
/>
</div>
<div className="flex min-w-0 flex-col gap-2">
<Label>Project</Label>
<InlineEntitySelector
value={draft.projectId}
options={projects.map((project) => ({ id: project.id, label: project.name }))}
placeholder="No project"
noneLabel="No project"
searchPlaceholder="Search projects…"
emptyMessage="No projects found."
disablePortal
className="h-9 w-full justify-start"
onChange={(projectId) => patch({ projectId })}
renderTriggerValue={(option) => {
const project = option ? projectById.get(option.id) : null;
return project ? (
<>
<span className="h-3.5 w-3.5 shrink-0 rounded-sm" style={{ backgroundColor: project.color ?? "var(--project-none)" }} />
<span className="truncate">{project.name}</span>
</>
) : (
<span className="text-muted-foreground">No project</span>
);
}}
renderOption={(option) => {
const project = projectById.get(option.id);
return (
<>
{project ? (
<span className="h-3.5 w-3.5 shrink-0 rounded-sm" style={{ backgroundColor: project.color ?? "var(--project-none)" }} />
) : null}
<span className="truncate">{option.label}</span>
</>
);
}}
/>
</div>
{responsibilities ? (
<div className="flex min-w-0 flex-col gap-2">
<Label>Responsibility</Label>
<InlineEntitySelector
value={draft.responsibilityId}
options={responsibilities.map((responsibility) => ({
id: responsibility.id,
label: responsibility.title,
searchText: responsibility.areaTitle ?? "",
}))}
placeholder="No responsibility"
noneLabel="No responsibility"
searchPlaceholder="Search responsibilities…"
emptyMessage="No responsibilities found."
disablePortal
className="h-9 w-full justify-start"
onChange={(responsibilityId) => patch({ responsibilityId })}
renderTriggerValue={(option) =>
option?.id ? <span className="truncate">{option.label}</span> : <span className="text-muted-foreground">No responsibility</span>
}
renderOption={(option) => {
const areaTitle = responsibilityById.get(option.id)?.areaTitle;
return (
<>
<span className="min-w-0 flex-1 truncate">{option.label}</span>
{areaTitle ? <span className="shrink-0 text-xs text-muted-foreground">{areaTitle}</span> : null}
</>
);
}}
/>
{throughProject ? (
<p className="text-xs text-muted-foreground">
Already under {throughProject.title} through {projectById.get(draft.projectId)?.name ?? "its project"}.
</p>
) : null}
</div>
) : null}
<div className="flex min-w-0 flex-col gap-2">
<Label>Default responsible user</Label>
<InlineEntitySelector
value={draft.responsibleUserId}
options={people.map((person) => ({ id: person.id, label: person.name }))}
placeholder="Choose a person"
noneLabel="No one"
// A responsible user can be changed but not cleared; "No one" only shows while there is none.
hideNone={Boolean(initial.responsibleUserId)}
searchPlaceholder="Find a person…"
emptyMessage="No people found."
disablePortal
disabled={!canChangeResponsibleUser}
className="h-9 w-full justify-start"
onChange={(responsibleUserId) => patch({ responsibleUserId })}
renderTriggerValue={(option) =>
(option && personOption(option.id)) || <span className="text-muted-foreground">Choose a person</span>
}
renderOption={(option) => personOption(option.id) ?? <span className="truncate">{option.label}</span>}
/>
</div>
</div>
<div className="flex flex-col gap-2">
<Label>Secrets</Label>
{secretsOpen ? (
<EnvironmentVariablesEditor
ref={secretsRef}
onDirtyChange={setSecretsDirty}
value={(draft.env ?? {}) as Record<string, EnvBinding>}
secrets={secrets}
onCreateSecret={onCreateSecret}
onChange={(env) => patch({ env: env && Object.keys(env).length > 0 ? env : null })}
footerHint={null}
hideDraftActions
startWithEmptyRow
addLabel="Add secret"
/>
) : (
<Button type="button" variant="outline" size="sm" className="w-fit" onClick={() => setSecretsOpen(true)}>
<Plus className="h-3.5 w-3.5" />
Add secret
</Button>
)}
</div>
</form>
<footer className="flex flex-wrap items-center justify-between gap-3 border-t border-border px-6 py-4">
{confirmingDiscard ? (
<>
<p className="text-sm" role="alert">Discard your changes?</p>
<div className="flex items-center gap-2">
<Button variant="ghost" onClick={() => setConfirmingDiscard(false)}>Keep editing</Button>
<Button variant="destructive" onClick={() => onOpenChange(false)}>Discard</Button>
</div>
</>
) : saveConflict ? (
<>
<p className="min-w-0 flex-1 text-sm" role="alert">
This routine changed while you were editing. Reload to see the latest version.
</p>
<Button variant="outline" onClick={onReloadLatest}>Reload latest</Button>
</>
) : (
<>
<Button variant="ghost" onClick={requestClose} disabled={saving}>Cancel</Button>
<div className="flex min-w-0 items-center gap-3">
{error ? <p className="min-w-0 text-sm text-destructive" role="alert">{error}</p> : null}
<Button type="submit" form={`${titleId}-form`} disabled={!canSave}>
{saving ? "Saving…" : mode === "create" ? "Create routine" : "Save changes"}
</Button>
</div>
</>
)}
</footer>
{children}
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,795 @@
import { useId, useState, type ReactNode } from "react";
import type { Issue, RoutineDetail, RoutineTrigger } from "@paperclipai/shared";
import {
ArrowLeft,
CalendarClock,
Check,
ChevronDown,
Copy,
GitBranch,
History,
KeyRound,
MessageSquare,
MoreHorizontal,
Pencil,
Radar,
ScrollText,
Sparkles,
Terminal,
Trash2,
Webhook,
} from "lucide-react";
import { AgentAvatar, type AvatarAgent } from "@/components/AgentAvatar";
import { RunButton } from "@/components/AgentActionButtons";
import { MarkdownBody } from "@/components/MarkdownBody";
import { ScheduleEditor } from "@/components/ScheduleEditor";
import { TaskSummaryList } from "@/components/TaskSummaryList";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { ToggleSwitch } from "@/components/ui/toggle-switch";
import { deriveInitials } from "@/components/Identity";
import { copyTextToClipboard } from "@/lib/clipboard";
import { Link } from "@/lib/router";
import { cn } from "@/lib/utils";
import {
ROUTINE_STATE_LABELS,
WEBHOOK_HEALTH_LABELS,
customRunRules,
describeScheduleTrigger,
formatNextRun,
instructionsPreview,
nextScheduledRun,
routineAutomationState,
routinePausedNotice,
routineStatusDetail,
webhookHealth,
webhookTitle,
} from "./routine-summary";
export type RoutinePerson = { id: string; name: string; avatarUrl?: string | null };
export type RoutinePageAgent = AvatarAgent & { id: string; name: string; urlKey?: string | null };
export type RoutinePageProject = { id: string; name: string; color?: string | null; urlKey?: string | null };
/** A responsibility this routine is under: linked itself, or through its project. */
export type RoutineResponsibility = {
id: string;
title: string;
areaTitle?: string | null;
via: "direct" | "project";
};
export type RoutineScheduleChange = { cronExpression: string; timezone: string };
export type RoutinePageProps = {
routine: RoutineDetail;
agent: RoutinePageAgent | null;
project: RoutinePageProject | null;
responsibleUser: RoutinePerson | null;
/** Leave undefined while areas of responsibility are switched off; the field is then hidden. */
responsibilities?: readonly RoutineResponsibility[];
/** Tasks this routine created, newest first. Pass the pages loaded so far. */
history: readonly Issue[];
historyLoading?: boolean;
/** Shown in place of the task list when History could not be loaded. */
historyError?: ReactNode;
/** More tasks exist beyond the loaded pages. */
hasMoreHistory?: boolean;
loadingMoreHistory?: boolean;
onLoadMoreHistory?: () => void;
/** Recent runs that made no task because an earlier run was still working. */
skippedRunCount?: number;
/** Open comments on the instructions. */
instructionCommentCount?: number;
statusPending?: boolean;
onToggleActive: (active: boolean) => void;
onEdit: () => void;
onSaveSchedule: (triggerId: string, change: RoutineScheduleChange) => void;
onRemoveSchedule: (triggerId: string) => void;
onOpenWebhook: (trigger: RoutineTrigger) => void;
/** Pauses or resumes one schedule, standing check or API trigger. Omit to hide Pause/Resume. */
onSetTriggerPaused?: (triggerId: string, paused: boolean) => void;
/** Removes a standing check or API trigger. Omit to keep those rows read-only. */
onRemoveTrigger?: (trigger: RoutineTrigger) => void;
/** Triggers removed from this page, offered back with Undo under Repeats. */
removedTriggers?: readonly RoutineTrigger[];
onRestoreTrigger?: (trigger: RoutineTrigger) => void;
onOpenInstructionComments?: () => void;
/** Show the whole instructions, e.g. while their comments are open. */
instructionsExpanded?: boolean;
/** Wraps the rendered instructions, e.g. with the comment layer that anchors to them. */
renderInstructionsBody?: (body: ReactNode) => ReactNode;
/** Router state for task links in History, so a task can lead back here. */
historyLinkState?: unknown;
};
function Field({ label, children, action }: { label: string; children: ReactNode; action?: ReactNode }) {
const headingId = useId();
return (
<section className="flex min-w-0 flex-col gap-2" aria-labelledby={headingId}>
<div className="flex items-center justify-between gap-2">
<h2 id={headingId} className="text-sm text-muted-foreground">{label}</h2>
{action}
</div>
{children}
</section>
);
}
function PersonAvatar({ person }: { person: RoutinePerson }) {
return (
<Avatar size="xs" aria-hidden="true">
{person.avatarUrl ? <AvatarImage src={person.avatarUrl} alt="" /> : null}
<AvatarFallback>{deriveInitials(person.name)}</AvatarFallback>
</Avatar>
);
}
function localTimezone(): string {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
} catch {
return "UTC";
}
}
const rowButtonClass =
"group -mx-2 flex min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-accent/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
function ScheduleRow({
trigger,
routineActive,
onSave,
onRemove,
onSetPaused,
}: {
trigger: RoutineTrigger;
routineActive: boolean;
onSave: (change: RoutineScheduleChange) => void;
onRemove: () => void;
onSetPaused?: (paused: boolean) => void;
}) {
const [open, setOpen] = useState(false);
const [cron, setCron] = useState(trigger.cronExpression ?? "0 9 * * 1-5");
const [valid, setValid] = useState(true);
const timezone = trigger.timezone ?? localTimezone();
const dimmed = !trigger.enabled || !routineActive;
return (
<Popover
open={open}
onOpenChange={(next) => {
setOpen(next);
if (next) setCron(trigger.cronExpression ?? "0 9 * * 1-5");
}}
>
<PopoverTrigger asChild>
<button type="button" className={rowButtonClass} aria-label={`Change schedule: ${describeScheduleTrigger(trigger)}`}>
<CalendarClock className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
<span className={cn("min-w-0 flex-1 truncate font-medium", dimmed && "text-muted-foreground")}>
{describeScheduleTrigger(trigger)}
</span>
<span className="shrink-0 text-xs text-muted-foreground">{trigger.enabled ? timezone : "Paused"}</span>
</button>
</PopoverTrigger>
{/* Wider when Pause/Resume joins Remove and Save, so the footer stays on one row. */}
<PopoverContent align="start" className={cn("flex flex-col gap-4", onSetPaused ? "w-96" : "w-80")}>
<ScheduleEditor value={cron} onChange={setCron} onValidityChange={setValid} />
<p className="text-xs text-muted-foreground">Times are in {timezone}.</p>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
className="text-muted-foreground"
onClick={() => {
setOpen(false);
onRemove();
}}
>
Remove schedule
</Button>
{onSetPaused ? (
<Button
variant="ghost"
size="sm"
className="text-muted-foreground"
onClick={() => {
setOpen(false);
onSetPaused(trigger.enabled);
}}
>
{trigger.enabled ? "Pause" : "Resume"}
</Button>
) : null}
</div>
<Button
size="sm"
disabled={!valid}
onClick={() => {
setOpen(false);
onSave({ cronExpression: cron, timezone });
}}
>
Save schedule
</Button>
</div>
</PopoverContent>
</Popover>
);
}
function WebhookRow({
trigger,
routineActive,
onOpen,
}: {
trigger: RoutineTrigger;
routineActive: boolean;
onOpen: () => void;
}) {
const health = webhookHealth(trigger);
const ignored = !routineActive && health !== "setup" && health !== "testing";
const Icon = trigger.signingMode === "github_hmac" ? GitBranch : Webhook;
return (
<button type="button" className={rowButtonClass} onClick={onOpen} aria-label={`Open ${webhookTitle(trigger)}`}>
<Icon className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
<span className={cn("min-w-0 flex-1 truncate font-medium", (ignored || health === "paused") && "text-muted-foreground")}>
{webhookTitle(trigger)}
</span>
<span className={cn("shrink-0 text-xs", health === "rejected" && !ignored ? "text-destructive" : "text-muted-foreground")}>
{ignored ? "Ignoring events" : WEBHOOK_HEALTH_LABELS[health]}
</span>
</button>
);
}
/** A standing check or API trigger: nothing to configure, but it can be paused or removed. */
function StaticTriggerRow({
icon: Icon,
title,
detail,
description,
trigger,
routineActive,
onSetPaused,
onRemove,
}: {
icon: typeof Radar;
title: string;
detail: string;
description: string;
trigger: RoutineTrigger;
routineActive: boolean;
onSetPaused?: (paused: boolean) => void;
onRemove?: () => void;
}) {
const [open, setOpen] = useState(false);
const dimmed = !trigger.enabled || !routineActive;
const content = (
<>
<Icon className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
<span className={cn("min-w-0 flex-1 truncate font-medium", dimmed && "text-muted-foreground")}>{title}</span>
<span className="shrink-0 text-xs text-muted-foreground">{trigger.enabled ? detail : "Paused"}</span>
</>
);
if (!onSetPaused && !onRemove) {
return <div className="flex min-w-0 items-center gap-2 py-1.5 text-sm">{content}</div>;
}
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button type="button" className={rowButtonClass} aria-label={`Change ${title}`}>
{content}
</button>
</PopoverTrigger>
<PopoverContent align="start" className="flex w-80 flex-col gap-4">
<p className="text-sm text-muted-foreground">{description}</p>
<div className="flex items-center justify-between gap-2">
{onRemove ? (
<Button
variant="ghost"
size="sm"
className="text-muted-foreground"
onClick={() => {
setOpen(false);
onRemove();
}}
>
Remove
</Button>
) : <span />}
{onSetPaused ? (
<Button
variant="outline"
size="sm"
onClick={() => {
setOpen(false);
onSetPaused(trigger.enabled);
}}
>
{trigger.enabled ? "Pause" : "Resume"}
</Button>
) : null}
</div>
</PopoverContent>
</Popover>
);
}
/** How a removed trigger is named in its "removed. Undo" line. */
export function triggerTitle(trigger: RoutineTrigger): string {
if (trigger.kind === "schedule") return describeScheduleTrigger(trigger);
if (trigger.kind === "webhook") return webhookTitle(trigger);
if (trigger.kind === "heartbeat") return "Standing check";
return "API trigger";
}
function Instructions({
markdown,
commentCount = 0,
onOpenComments,
onEdit,
forceExpanded = false,
renderBody = (body) => body,
}: {
markdown: string;
commentCount?: number;
onOpenComments?: () => void;
onEdit: () => void;
forceExpanded?: boolean;
renderBody?: (body: ReactNode) => ReactNode;
}) {
const [expandedState, setExpanded] = useState(false);
const expanded = expandedState || forceExpanded;
const [copied, setCopied] = useState(false);
const { preview, truncated } = instructionsPreview(markdown);
const empty = markdown.trim().length === 0;
return (
<Field
label="Instructions"
action={empty ? null : (
<div className="flex items-center gap-1">
{commentCount > 0 ? (
<Button variant="ghost" size="xs" className="text-muted-foreground" onClick={onOpenComments}>
<MessageSquare />
{commentCount} {commentCount === 1 ? "comment" : "comments"}
</Button>
) : null}
<Button
variant="ghost"
size="icon-xs"
className="text-muted-foreground"
aria-label={copied ? "Instructions copied" : "Copy instructions"}
onClick={async () => {
await copyTextToClipboard(markdown);
setCopied(true);
window.setTimeout(() => setCopied(false), 1500);
}}
>
{copied ? <Check /> : <Copy />}
</Button>
</div>
)}
>
{empty ? (
<div className="flex flex-col items-start gap-2">
<p className="text-sm text-muted-foreground">No instructions yet. The agent only gets the title.</p>
<Button variant="outline" size="sm" onClick={onEdit}>Add instructions</Button>
</div>
) : (
<>
{/* Comments anchor to the full text, so the comment layer only wraps it when the whole text shows. */}
{expanded || !truncated
? renderBody(
<MarkdownBody className="text-sm text-foreground" linkIssueReferences>
{markdown}
</MarkdownBody>,
)
: (
<MarkdownBody className="text-sm text-foreground" linkIssueReferences>
{preview}
</MarkdownBody>
)}
{truncated && !forceExpanded ? (
<Button
variant="ghost"
size="sm"
className="-mx-2 w-fit"
aria-expanded={expanded}
onClick={() => setExpanded((value) => !value)}
>
{expanded ? "Show less" : "Show all"}
<ChevronDown className={cn("h-3.5 w-3.5 transition-transform", expanded && "rotate-180")} />
</Button>
) : null}
</>
)}
</Field>
);
}
export function RoutinePage({
routine,
agent,
project,
responsibleUser,
responsibilities,
history,
historyLoading = false,
historyError,
hasMoreHistory = false,
loadingMoreHistory = false,
onLoadMoreHistory,
skippedRunCount = 0,
instructionCommentCount,
statusPending = false,
onToggleActive,
onEdit,
onSaveSchedule,
onRemoveSchedule,
onSetTriggerPaused,
onRemoveTrigger,
removedTriggers = [],
onRestoreTrigger,
onOpenWebhook,
onOpenInstructionComments,
instructionsExpanded = false,
renderInstructionsBody,
historyLinkState,
}: RoutinePageProps) {
const state = routineAutomationState(routine);
const schedules = routine.triggers.filter((trigger) => trigger.kind === "schedule");
const webhooks = routine.triggers.filter((trigger) => trigger.kind === "webhook");
const standingCheck = routine.triggers.find((trigger) => trigger.kind === "heartbeat");
const apiTrigger = routine.triggers.find((trigger) => trigger.kind === "api");
const nextRun = state === "active" ? nextScheduledRun(routine.triggers) : null;
const hasEnabledWebhook = webhooks.some((trigger) => trigger.enabled && !trigger.setupPending);
const runRules = customRunRules(routine);
const secretNames = Object.keys(routine.env ?? {});
const archived = state === "archived";
const active = state === "active";
const hasSchedule = schedules.some((trigger) => trigger.enabled);
const pausedNotice = routinePausedNotice({ state, hasWebhooks: webhooks.length > 0, hasSchedule });
const statusDetail = routineStatusDetail({ state, nextRun, hasEnabledWebhook, hasStandingCheck: Boolean(standingCheck) });
return (
<div className="mx-auto grid w-full max-w-6xl grid-cols-1 gap-x-12 gap-y-10 px-4 py-8 md:px-8 lg:grid-cols-5">
<div className="flex min-w-0 flex-col gap-6 lg:col-span-2">
<div className="flex min-w-0 flex-col gap-1.5">
<h1 className="text-xl font-semibold text-balance">{routine.title}</h1>
{routine.managedByPlugin ? (
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Sparkles className="h-3.5 w-3.5" aria-hidden="true" />
Managed by {routine.managedByPlugin.pluginDisplayName}
</p>
) : null}
</div>
<Field label="Status">
<div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
<ToggleSwitch
checked={state === "active"}
onCheckedChange={onToggleActive}
disabled={statusPending || archived || state === "draft"}
aria-label={state === "active" ? "Pause this routine" : "Turn this routine on"}
/>
<span className={cn("text-sm font-medium", state !== "active" && "text-muted-foreground")}>
{ROUTINE_STATE_LABELS[state]}
</span>
{statusDetail ? <span className="text-sm text-muted-foreground">{statusDetail}</span> : null}
</div>
{pausedNotice ? <p className="text-sm text-muted-foreground" role="note">{pausedNotice}</p> : null}
{state === "draft" ? (
<p className="text-sm text-muted-foreground">
<button type="button" className="font-medium text-foreground underline-offset-4 hover:underline" onClick={onEdit}>
Choose a default agent
</button>{" "}
to turn this routine on.
</p>
) : null}
</Field>
<Field label="Repeats">
<div className="flex min-w-0 flex-col">
{schedules.map((trigger) => (
<ScheduleRow
key={trigger.id}
trigger={trigger}
routineActive={active}
onSave={(change) => onSaveSchedule(trigger.id, change)}
onRemove={() => onRemoveSchedule(trigger.id)}
onSetPaused={onSetTriggerPaused ? (paused) => onSetTriggerPaused(trigger.id, paused) : undefined}
/>
))}
{webhooks.map((trigger) => (
<WebhookRow key={trigger.id} trigger={trigger} routineActive={active} onOpen={() => onOpenWebhook(trigger)} />
))}
{standingCheck ? (
<StaticTriggerRow
icon={Radar}
title="Standing check"
detail="Each time the agent wakes up"
description="The agent carries out these instructions each time it wakes up and reports what it found. It never creates a task by itself."
trigger={standingCheck}
routineActive={active}
onSetPaused={onSetTriggerPaused ? (paused) => onSetTriggerPaused(standingCheck.id, paused) : undefined}
onRemove={onRemoveTrigger ? () => onRemoveTrigger(standingCheck) : undefined}
/>
) : null}
{apiTrigger ? (
<StaticTriggerRow
icon={Terminal}
title="API"
detail="Started by an API call"
description="Starts this routine when an app or agent calls the routine API."
trigger={apiTrigger}
routineActive={active}
onSetPaused={onSetTriggerPaused ? (paused) => onSetTriggerPaused(apiTrigger.id, paused) : undefined}
onRemove={onRemoveTrigger ? () => onRemoveTrigger(apiTrigger) : undefined}
/>
) : null}
{removedTriggers.map((trigger) => (
<p key={trigger.id} role="status" className="flex min-w-0 items-center gap-2 py-1.5 text-sm text-muted-foreground">
<span className="min-w-0 flex-1 truncate">{triggerTitle(trigger)} removed.</span>
{onRestoreTrigger ? (
<Button type="button" variant="ghost" size="xs" onClick={() => onRestoreTrigger(trigger)}>Undo</Button>
) : null}
</p>
))}
{routine.triggers.length === 0 && removedTriggers.length === 0 ? (
<p className="py-1.5 text-sm text-muted-foreground">Doesn’t repeat. Runs only when you start it.</p>
) : null}
</div>
</Field>
<Field label="Default agent">
{agent ? (
<Link
to={`/agents/${agent.urlKey ?? agent.id}`}
className="flex w-fit max-w-full items-center gap-2 py-1.5 text-sm font-medium hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<AgentAvatar agent={agent} size={20} className="shrink-0" />
<span className="truncate">{agent.name}</span>
</Link>
) : (
<Button variant="outline" size="sm" className="w-fit" onClick={onEdit}>Choose an agent</Button>
)}
</Field>
<Field label="Default responsible user">
{responsibleUser ? (
<p className="flex min-w-0 items-center gap-2 py-1.5 text-sm font-medium">
<PersonAvatar person={responsibleUser} />
<span className="truncate">{responsibleUser.name}</span>
</p>
) : (
<p className="py-1.5 text-sm text-muted-foreground">No one yet</p>
)}
</Field>
<Field label="Project">
{project ? (
<Link
to={`/projects/${project.urlKey ?? project.id}`}
className="flex w-fit max-w-full items-center gap-2 py-1.5 text-sm font-medium hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<span className="h-3.5 w-3.5 shrink-0 rounded-sm" style={{ backgroundColor: project.color ?? "var(--project-none)" }} aria-hidden="true" />
<span className="truncate">{project.name}</span>
</Link>
) : (
<p className="py-1.5 text-sm text-muted-foreground">No project</p>
)}
</Field>
{responsibilities ? (
<Field label="Responsibility">
{responsibilities.length === 0 ? (
<p className="py-1.5 text-sm text-muted-foreground">None</p>
) : (
<ul className="flex min-w-0 flex-col">
{responsibilities.map((responsibility) => (
<li key={responsibility.id} className="flex min-w-0 items-baseline gap-2 py-1.5 text-sm">
<Link
to={`/responsibilities/${responsibility.id}`}
className="min-w-0 truncate font-medium hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
{responsibility.title}
</Link>
<span className="shrink-0 text-xs text-muted-foreground">
{responsibility.via === "project" && project
? `Through ${project.name}`
: responsibility.areaTitle ?? ""}
</span>
</li>
))}
</ul>
)}
</Field>
) : null}
{routine.variables.length > 0 ? (
<Field label="Asks for">
<ul className="flex min-w-0 flex-col gap-1.5 py-1.5">
{routine.variables.map((variable) => (
<li key={variable.name} className="flex min-w-0 items-baseline gap-2 text-sm">
<span className="truncate font-medium">{variable.label || variable.name}</span>
<span className="shrink-0 text-xs text-muted-foreground">
{variable.defaultValue != null && variable.defaultValue !== ""
? `Usually ${String(variable.defaultValue)}`
: variable.required
? "Required"
: "Optional"}
</span>
</li>
))}
</ul>
</Field>
) : null}
{secretNames.length > 0 ? (
<Field label="Secrets">
<ul className="flex min-w-0 flex-wrap gap-x-4 gap-y-1.5 py-1.5">
{secretNames.map((name) => (
<li key={name} className="flex min-w-0 items-center gap-1.5 font-mono text-xs">
<KeyRound className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
<span className="truncate">{name}</span>
</li>
))}
</ul>
</Field>
) : null}
{runRules.length > 0 ? (
<Field label="Run rules">
<ul className="flex flex-col gap-1 py-1.5 text-sm">
{runRules.map((rule) => <li key={rule}>{rule}</li>)}
</ul>
</Field>
) : null}
</div>
<div className="flex min-w-0 flex-col gap-8 lg:col-span-3">
<Instructions
markdown={routine.description ?? ""}
commentCount={instructionCommentCount}
onOpenComments={onOpenInstructionComments}
onEdit={onEdit}
forceExpanded={instructionsExpanded}
renderBody={renderInstructionsBody}
/>
<Field label="History">
{historyError && history.length === 0 ? (
historyError
) : historyLoading ? (
<p className="py-1.5 text-sm text-muted-foreground" role="status">Loading tasks…</p>
) : history.length === 0 ? (
<p className="py-1.5 text-sm text-muted-foreground">
{state === "active" && nextRun
? `No tasks yet. The first one starts ${formatNextRun(nextRun)}.`
: "No tasks yet. Each run creates a task here."}
</p>
) : (
<TaskSummaryList issues={history} label="Tasks created by this routine" issueLinkState={historyLinkState} />
)}
{historyError && history.length > 0 ? historyError : null}
{hasMoreHistory && history.length > 0 ? (
<Button
variant="ghost"
size="sm"
className="-mx-2 w-fit text-muted-foreground"
disabled={loadingMoreHistory}
onClick={onLoadMoreHistory}
>
{loadingMoreHistory ? "Loading…" : "Load more"}
</Button>
) : null}
{skippedRunCount > 0 ? (
<p className="text-xs text-muted-foreground">
{skippedRunCount === 1 ? "1 run was" : `${skippedRunCount} runs were`} folded into a task that was still in
progress.
</p>
) : null}
</Field>
</div>
</div>
);
}
/** Version history and the audit log open as their own view, with a way back to the routine. */
export function RoutineSubpage({
routineTitle,
title,
onBack,
children,
}: {
routineTitle: string;
title: string;
onBack: () => void;
children: ReactNode;
}) {
return (
<div className="mx-auto flex w-full max-w-5xl flex-col gap-6 px-4 py-8 md:px-8">
<div className="flex flex-col items-start gap-2">
<Button variant="ghost" size="sm" className="-mx-2 text-muted-foreground" onClick={onBack}>
<ArrowLeft className="h-3.5 w-3.5" />
{routineTitle}
</Button>
<h1 className="text-xl font-semibold">{title}</h1>
</div>
{children}
</div>
);
}
export type RoutinePageActionsProps = {
archived?: boolean;
runPending?: boolean;
/** Start with the menu open, for review. */
defaultMenuOpen?: boolean;
onEdit: () => void;
onRunNow: () => void;
onOpenVersionHistory: () => void;
onOpenAuditLog: () => void;
onArchive: () => void;
onRestore?: () => void;
};
/** Header controls for the routine page: edit, a short overflow menu, and Run now. */
export function RoutinePageActions({
archived = false,
runPending = false,
defaultMenuOpen = false,
onEdit,
onRunNow,
onOpenVersionHistory,
onOpenAuditLog,
onArchive,
onRestore,
}: RoutinePageActionsProps) {
return (
<div className="flex items-center gap-1">
{archived ? null : (
<Button variant="ghost" size="icon-sm" aria-label="Edit routine" onClick={onEdit}>
<Pencil />
</Button>
)}
<DropdownMenu defaultOpen={defaultMenuOpen}>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm" aria-label="More routine actions">
<MoreHorizontal />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onSelect={onOpenVersionHistory}>
<History />
Version history
</DropdownMenuItem>
<DropdownMenuItem onSelect={onOpenAuditLog}>
<ScrollText />
Audit log
</DropdownMenuItem>
<DropdownMenuSeparator />
{archived && onRestore ? (
<DropdownMenuItem onSelect={onRestore}>Restore routine</DropdownMenuItem>
) : (
<DropdownMenuItem variant="destructive" onSelect={onArchive}>
<Trash2 />
Archive routine
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
{archived ? null : <RunButton onClick={onRunNow} disabled={runPending} />}
</div>
);
}
@@ -0,0 +1,130 @@
// @vitest-environment jsdom
import { useEffect } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import type { RoutineDetail, RoutineTrigger } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { RoutinePage } from "./RoutinePage";
import { RoutineWebhookDialog } from "./RoutineWebhookDialog";
import { useRoutineWebhookDialog } from "./useRoutineWebhookDialog";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
vi.mock("@/api/routines", () => ({ routinesApi: { updateTrigger: vi.fn(), createTrigger: vi.fn(), rotateTriggerSecret: vi.fn() } }));
vi.mock("@/components/MarkdownBody", () => ({ MarkdownBody: ({ children }: { children: string }) => <div>{children}</div> }));
vi.mock("@/components/TaskSummaryList", () => ({ TaskSummaryList: () => null }));
vi.mock("@/lib/router", () => ({ Link: ({ children }: { children: unknown }) => <a>{children as never}</a> }));
async function act(callback: () => void | Promise<void>) {
let result: void | Promise<void> = undefined;
flushSync(() => {
result = callback();
});
await result;
}
const flush = () => new Promise((resolve) => window.setTimeout(resolve, 0));
const keyless = {
id: "webhook-1",
kind: "webhook",
label: null,
enabled: true,
signingMode: "none",
setupPending: false,
webhookUrl: "https://paperclip.example/api/routine-triggers/public/abc/fire",
lastWebhookDelivery: null,
} as RoutineTrigger;
describe("routine webhook dialog", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(async () => {
await act(() => root.unmount());
container.remove();
document.body.innerHTML = "";
});
it("gives a keyless webhook its request instructions without a key", async () => {
await act(async () => {
root.render(
<RoutineWebhookDialog open onOpenChange={() => {}} routineTitle="Digest" trigger={keyless}
onCreate={() => {}} onReplaceKey={() => {}} onSetPaused={() => {}} onRemove={() => {}} />,
);
await flush();
});
expect(document.body.textContent).toContain("Its URL is the shared secret");
// The copyable agent instructions show even though there is no key (their text is covered in webhook-instructions.test.ts).
expect(document.querySelector('section[aria-label="Agent instructions"]')).not.toBeNull();
expect(document.body.textContent).not.toContain("Replace key");
});
async function renderRestored(signingMode: string | null) {
function Harness() {
const webhook = useRoutineWebhookDialog({ routineId: "routine-1", triggers: [], onChanged: () => {} });
const { showKeys } = webhook;
useEffect(() => {
showKeys([{ triggerId: "webhook-9", webhookUrl: "https://paperclip.example/hook/9", webhookSecret: "restored-secret", signingMode }]);
}, [showKeys]);
return <RoutineWebhookDialog {...webhook.dialogProps} routineTitle="Digest" />;
}
await act(async () => { root.render(<Harness />); await flush(); });
}
it("shows a restored webhook's new key, with instructions for its real signing mode, before the refresh lists it", async () => {
await renderRestored("hmac_sha256");
expect(document.body.textContent).not.toContain("Add webhook");
expect(document.body.textContent).toContain("https://paperclip.example/hook/9");
expect(document.body.textContent).toContain("Copy it now");
expect(document.body.textContent).toContain("X-Paperclip-Timestamp");
expect(document.querySelector('section[aria-label="Agent instructions"]')).not.toBeNull();
});
it("withholds signing instructions for a restored webhook whose signing mode is unknown", async () => {
await renderRestored(null);
expect(document.body.textContent).toContain("Copy it now");
expect(document.querySelector('section[aria-label="Agent instructions"]')).toBeNull();
});
});
describe("routine page instructions", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(async () => {
await act(() => root.unmount());
container.remove();
});
it("only lets comments anchor to the instructions once the whole text shows", async () => {
const wrap = vi.fn((body: unknown) => <div data-testid="comment-layer">{body as never}</div>);
const routine = {
id: "routine-1", title: "Digest", description: "First paragraph.\n\nSecond paragraph.", status: "active",
assigneeAgentId: null, triggers: [], variables: [], env: null, concurrencyPolicy: "coalesce_if_active",
catchUpPolicy: "skip_missed", activityGatePolicy: "always", activityGateScope: "company", managedByPlugin: null,
} as unknown as RoutineDetail;
const render = (expanded: boolean) => act(async () => {
root.render(
<RoutinePage routine={routine} agent={null} project={null} responsibleUser={null} history={[]}
onToggleActive={() => {}} onEdit={() => {}} onSaveSchedule={() => {}} onRemoveSchedule={() => {}} onOpenWebhook={() => {}}
renderInstructionsBody={wrap} instructionsExpanded={expanded} />,
);
await flush();
});
await render(false);
expect(container.querySelector('[data-testid="comment-layer"]')).toBeNull();
expect(container.textContent).not.toContain("Second paragraph.");
await render(true);
expect(container.querySelector('[data-testid="comment-layer"]')?.textContent).toContain("Second paragraph.");
});
});
@@ -0,0 +1,208 @@
import { useEffect, useState } from "react";
import type { RoutineTrigger } from "@paperclipai/shared";
import { AlertCircle, Check, CheckCircle2, GitBranch, Globe, PauseCircle, Radio } from "lucide-react";
import { webhookAgentInstructions, webhookInstructionSigningMode } from "@/components/routine-triggers/webhook-instructions";
import { AgentInstructions, CopyField } from "@/components/routine-triggers/WebhookFields";
import { WebhookUrlWarning } from "@/components/routine-triggers/WebhookUrlWarning";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import { WEBHOOK_STATUS_COPY, webhookStatusKey, webhookTitle, type WebhookStatusKey } from "./routine-summary";
export type WebhookSender = "custom" | "github";
export type RoutineWebhookDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
routineTitle: string;
/** False while the routine is paused or has no default agent: real events are rejected. */
routineActive?: boolean;
/** `null` while choosing what to connect; the saved webhook afterwards. */
trigger: RoutineTrigger | null;
/** The key, available only right after the webhook is created or its key is replaced. */
secret?: string | null;
busy?: boolean;
error?: string | null;
onCreate: (sender: WebhookSender) => void;
onReplaceKey: () => void;
onSetPaused: (paused: boolean) => void;
onRemove: () => void;
/** A finished webhook put back into test mode: events are checked but never start the routine. */
testing?: boolean;
/** Omit to hide "Test webhook". */
onStartTest?: () => void;
onFinishTest?: () => void;
};
const SENDERS = [
{ sender: "custom", label: "Another app or script", Icon: Globe },
{ sender: "github", label: "GitHub", Icon: GitBranch },
] as const;
const STATUS_LOOK: Record<WebhookStatusKey, { icon: typeof Radio; tone: string }> = {
setup: { icon: Radio, tone: "text-muted-foreground" },
setup_testing: { icon: Radio, tone: "text-muted-foreground" },
testing: { icon: Radio, tone: "text-muted-foreground" },
waiting: { icon: Radio, tone: "text-muted-foreground" },
receiving: { icon: CheckCircle2, tone: "text-(--status-task-done)" },
rejected: { icon: AlertCircle, tone: "text-destructive" },
test_rejected: { icon: AlertCircle, tone: "text-destructive" },
test_received: { icon: CheckCircle2, tone: "text-(--status-task-done)" },
ignored_while_paused: { icon: PauseCircle, tone: "text-muted-foreground" },
paused: { icon: PauseCircle, tone: "text-muted-foreground" },
};
export function RoutineWebhookDialog({
open,
onOpenChange,
routineTitle,
routineActive = true,
trigger,
secret = null,
busy = false,
error = null,
onCreate,
onReplaceKey,
onSetPaused,
onRemove,
testing = false,
onStartTest,
onFinishTest,
}: RoutineWebhookDialogProps) {
const [sender, setSender] = useState<WebhookSender>("custom");
useEffect(() => {
if (open && !trigger) setSender("custom");
}, [open, trigger]);
const github = trigger?.signingMode === "github_hmac";
const bearer = trigger?.signingMode === "bearer";
const inTest = testing && Boolean(trigger?.setupPending);
const statusKey = trigger ? webhookStatusKey(trigger, { routineActive, testing: inTest }) : null;
const status = statusKey ? { ...STATUS_LOOK[statusKey], ...WEBHOOK_STATUS_COPY[statusKey] } : null;
const testReceived = statusKey === "test_received";
const StatusIcon = status?.icon;
const statusDetail = status?.detail;
const canTest = Boolean(onStartTest) && trigger != null && !trigger.setupPending && trigger.enabled;
const url = trigger?.webhookUrl ?? "";
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 sm:max-w-lg">
<DialogHeader className="px-6 pb-4 pt-6">
<DialogTitle>{trigger ? webhookTitle(trigger) : "Add webhook"}</DialogTitle>
<DialogDescription>
{trigger
? `Starts “${routineTitle}” when ${github ? "GitHub" : "another app"} sends an event.`
: "Start this routine when something happens in another app."}
</DialogDescription>
</DialogHeader>
<fieldset disabled={busy} className="flex min-h-0 min-w-0 flex-1 flex-col gap-5 overflow-y-auto px-6 pb-6">
{!trigger ? (
<div role="radiogroup" aria-label="What’s sending the webhook?" className="flex flex-col gap-2">
{SENDERS.map(({ sender: value, label, Icon }) => (
<label
key={value}
className={cn(
"flex cursor-pointer items-center gap-3 rounded-md border p-3 text-sm focus-within:ring-2 focus-within:ring-ring",
sender === value ? "border-primary bg-accent/30" : "border-border hover:bg-accent/20",
)}
>
<input
className="sr-only"
type="radio"
name="webhook-sender"
checked={sender === value}
onChange={() => setSender(value)}
/>
<Icon className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
<span className="flex-1">{label}</span>
{sender === value ? <Check className="h-4 w-4" aria-hidden="true" /> : null}
</label>
))}
</div>
) : (
<>
{status && StatusIcon ? (
<div role="status" className="flex items-start gap-3 rounded-md bg-muted/40 p-3">
<StatusIcon className={cn("mt-0.5 h-4 w-4 shrink-0", status.tone)} aria-hidden="true" />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<p className="text-sm font-medium">{status.title}</p>
<p className="text-xs text-muted-foreground">{statusDetail}</p>
</div>
{canTest ? (
<Button variant="outline" size="sm" className="shrink-0" onClick={onStartTest}>Test webhook</Button>
) : null}
</div>
) : null}
<WebhookUrlWarning url={url} />
<CopyField label={github ? "Payload URL" : "Webhook URL"} value={url} />
{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>
) : null}
{trigger.signingMode === "none" ? (
<p className="text-sm text-muted-foreground">This webhook has no key. Its URL is the shared secret, so keep it private.</p>
) : secret ? (
<CopyField
label={github ? "Secret" : bearer ? "Authorization header value" : "Secret key"}
value={!github && bearer ? `Bearer ${secret}` : secret}
help="Copy it now. It’s hidden after you close this."
/>
) : (
<div className="flex items-center justify-between gap-3">
<p className="text-sm text-muted-foreground">The secret key is hidden.</p>
<Button variant="outline" size="sm" onClick={onReplaceKey}>Replace key</Button>
</div>
)}
{/* Instructions follow the signing mode; with no known mode (a restored webhook before its refresh) none are shown. */}
{trigger.signingMode && (secret || trigger.signingMode === "none") ? (
<AgentInstructions
value={webhookAgentInstructions(
github ? "github" : "custom",
routineTitle,
url,
secret ?? "",
Boolean(trigger.setupPending),
webhookInstructionSigningMode(trigger.signingMode),
)}
/>
) : null}
</>
)}
{error ? <p role="alert" className="text-sm text-destructive">{error}</p> : null}
</fieldset>
<footer className="flex flex-wrap items-center justify-between gap-3 border-t border-border px-6 py-4">
{!trigger ? (
<>
<Button variant="ghost" onClick={() => onOpenChange(false)}>Cancel</Button>
<Button disabled={busy} onClick={() => onCreate(sender)}>{busy ? "Creating…" : "Create webhook"}</Button>
</>
) : inTest ? (
<>
<p className="text-sm text-muted-foreground">Testing. No tasks are created.</p>
<Button disabled={busy} onClick={onFinishTest}>Finish testing</Button>
</>
) : (
<>
<div className="flex items-center gap-1">
<Button variant="ghost" className="text-muted-foreground" disabled={busy} onClick={onRemove}>Remove</Button>
{trigger.setupPending ? null : (
<Button variant="ghost" className="text-muted-foreground" disabled={busy} onClick={() => onSetPaused(trigger.enabled)}>
{trigger.enabled ? "Pause" : "Resume"}
</Button>
)}
</div>
<Button onClick={() => onOpenChange(false)}>
{trigger.setupPending && !testReceived ? "Finish without testing" : "Done"}
</Button>
</>
)}
</footer>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,137 @@
import type { RoutineTrigger } from "@paperclipai/shared";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { routinesApi } from "@/api/routines";
import { responsibilitiesApi } from "@/api/responsibilities";
import { EMPTY_ROUTINE_FORM_DRAFT } from "./RoutineEditDialog";
import { PartialRoutineSaveError, buildRoutineResponsibilityChoices, routineFieldsChanged, routineFieldsPayload, syncRoutineResponsibility, syncRoutineSchedule } from "./routine-form";
import { resolveRoutineAddress, routinePath } from "./routine-routes";
import { routinePausedNotice, routineStatusDetail, webhookHealth, webhookStatusKey } from "./routine-summary";
vi.mock("@/api/routines", () => ({ routinesApi: { createTrigger: vi.fn(), updateTrigger: vi.fn() } }));
vi.mock("@/api/responsibilities", () => ({ responsibilitiesApi: { link: vi.fn(), unlink: vi.fn(), get: vi.fn() } }));
const schedule = { id: "schedule-1", kind: "schedule", cronExpression: "0 9 * * 1-5", timezone: "UTC" } as RoutineTrigger;
describe("routine form saving", () => {
beforeEach(() => vi.clearAllMocks());
it("only sends the fields the form edits", () => {
const payload = routineFieldsPayload({ ...EMPTY_ROUTINE_FORM_DRAFT, title: " Digest ", env: {} });
expect(payload).toEqual({ title: "Digest", description: null, projectId: null, assigneeAgentId: null, variables: [], env: null });
expect(routineFieldsChanged({ ...EMPTY_ROUTINE_FORM_DRAFT, title: "A" }, { ...EMPTY_ROUTINE_FORM_DRAFT, title: "A", schedule: null })).toBe(false);
});
it("creates, changes and removes the schedule the form opened with", async () => {
vi.mocked(routinesApi.createTrigger).mockResolvedValue({ trigger: { id: "schedule-new" } } as never);
expect(await syncRoutineSchedule("routine-1", [], null, null)).toEqual({ changed: false, scheduleId: null });
expect(await syncRoutineSchedule("routine-1", [], null, { cronExpression: "0 8 * * *", timezone: "UTC" })).toEqual({ changed: true, scheduleId: "schedule-new" });
expect(routinesApi.createTrigger).toHaveBeenCalledWith("routine-1", { kind: "schedule", cronExpression: "0 8 * * *", timezone: "UTC" });
expect(await syncRoutineSchedule("routine-1", [schedule], "schedule-1", { cronExpression: "0 9 * * 1-5", timezone: "UTC" })).toEqual({ changed: false, scheduleId: "schedule-1" });
await syncRoutineSchedule("routine-1", [schedule], "schedule-1", { cronExpression: "0 10 * * 1-5", timezone: "UTC" });
expect(routinesApi.updateTrigger).toHaveBeenCalledWith("schedule-1", { cronExpression: "0 10 * * 1-5", timezone: "UTC" });
expect(await syncRoutineSchedule("routine-1", [schedule], "schedule-1", null)).toEqual({ changed: true, scheduleId: null });
expect(routinesApi.updateTrigger).toHaveBeenLastCalledWith("schedule-1", { archived: true });
});
it("never touches another schedule when a removal is retried", async () => {
const second = { ...schedule, id: "schedule-2", cronExpression: "0 18 * * *" } as RoutineTrigger;
// The first save removed schedule-1; the form now stands for no schedule, and schedule-2 is left alone.
expect(await syncRoutineSchedule("routine-1", [second], null, null)).toEqual({ changed: false, scheduleId: null });
// Even when the form still points at the removed schedule.
expect(await syncRoutineSchedule("routine-1", [second], "schedule-1", null)).toEqual({ changed: false, scheduleId: null });
expect(routinesApi.updateTrigger).not.toHaveBeenCalled();
});
it("says what a partly finished save saved and what it did not", () => {
expect(new PartialRoutineSaveError(["details", "schedule"], "responsibility", new Error("Not allowed")).message)
.toBe("Saved the routine’s details and the schedule, but the responsibility couldn’t be updated (Not allowed). Save again to finish.");
});
it("moves the direct responsibility link", async () => {
vi.mocked(responsibilitiesApi.get).mockResolvedValue({ routines: [{ id: "routine-1", linkId: "link-1" }] } as never);
expect(await syncRoutineResponsibility("routine-1", "a", "a")).toBe(false);
await syncRoutineResponsibility("routine-1", "old", "new");
expect(responsibilitiesApi.link).toHaveBeenCalledWith("new", { routineId: "routine-1" });
expect(responsibilitiesApi.unlink).toHaveBeenCalledWith("old", "link-1");
});
});
describe("routine addresses", () => {
it("sends old section links to the page and keeps the two sub-views", () => {
expect(routinePath("r")).toBe("/routines/r");
for (const section of ["overview", "triggers", "variables", "secrets", "delivery", "runs"]) {
expect(resolveRoutineAddress({ routineId: "r", section })).toEqual({ view: "routine", redirectTo: "/routines/r" });
}
expect(resolveRoutineAddress({ routineId: "r" })).toEqual({ view: "routine", redirectTo: null });
expect(resolveRoutineAddress({ routineId: "r", section: "history" })).toEqual({ view: "history", redirectTo: null });
expect(resolveRoutineAddress({ routineId: "r", section: "activity" })).toEqual({ view: "activity", redirectTo: null });
expect(resolveRoutineAddress({ routineId: "r", legacyTab: "history" })).toEqual({ view: "history", redirectTo: "/routines/r/history" });
});
});
describe("webhook health", () => {
const base = { kind: "webhook", enabled: true } as RoutineTrigger;
it("tells a webhook put back into test mode from one still in first setup", () => {
expect(webhookHealth({ ...base, setupPending: true, lastWebhookDelivery: null })).toBe("setup");
expect(webhookHealth({ ...base, setupPending: true, lastWebhookDelivery: { status: "received", receivedAt: "x", test: false } })).toBe("testing");
expect(webhookHealth({
...base,
setupPending: true,
lastWebhookDelivery: { status: "received", receivedAt: "y", test: true, previous: { status: "received", receivedAt: "x", test: false } },
})).toBe("testing");
expect(webhookHealth({ ...base, lastWebhookDelivery: { status: "received", receivedAt: "x", test: false } })).toBe("receiving");
});
});
describe("responsibility choices", () => {
it("indexes links and options once, staying fast for large lists", () => {
const count = 5000;
const options = Array.from({ length: count }, (_, index) => ({ id: `resp-${index}`, title: `Responsibility ${index}` }));
const links = [
...Array.from({ length: count }, (_, index) => ({ id: `resp-${index}`, title: `Responsibility ${index}`, areaId: "area-1", ownerUserId: "u", via: "project" as const })),
{ id: "other-owner", title: "Someone else's", areaId: null, ownerUserId: "v", via: "direct" as const },
];
const started = performance.now();
const result = buildRoutineResponsibilityChoices({ links, options, areaTitles: new Map([["area-1", "Customers"]]), projectId: "project-1" });
expect(performance.now() - started).toBeLessThan(200);
expect(result.onPage).toHaveLength(count + 1);
expect(result.onPage[0]).toMatchObject({ areaTitle: "Customers", via: "project" });
expect(result.choices).toHaveLength(count + 1);
expect(result.choices[0]!.projectIds).toEqual(["project-1"]);
expect(result.choices.at(-1)).toMatchObject({ id: "other-owner", projectIds: [] });
});
});
describe("routine status copy", () => {
it("names what a paused or draft routine skips", () => {
expect(routinePausedNotice({ state: "active", hasWebhooks: true, hasSchedule: true })).toBeNull();
expect(routinePausedNotice({ state: "paused", hasWebhooks: true, hasSchedule: true })).toBe("Scheduled runs are skipped and webhook events are ignored until this routine is on.");
expect(routinePausedNotice({ state: "draft", hasWebhooks: true, hasSchedule: false })).toBe("Webhook events are ignored until this routine is on. The sending app gets an error.");
expect(routinePausedNotice({ state: "paused", hasWebhooks: false, hasSchedule: true })).toBe("Scheduled runs are skipped until this routine is on.");
expect(routinePausedNotice({ state: "paused", hasWebhooks: false, hasSchedule: false })).toBeNull();
});
it("explains when the routine runs next", () => {
const base = { nextRun: null, hasEnabledWebhook: false, hasStandingCheck: false };
expect(routineStatusDetail({ ...base, state: "draft" })).toBeNull();
expect(routineStatusDetail({ ...base, state: "archived" })).toBe("No longer runs");
expect(routineStatusDetail({ ...base, state: "paused" })).toBe("Run now still works");
const now = new Date(2026, 10, 18, 8, 0);
expect(routineStatusDetail({ ...base, state: "active", nextRun: new Date(2026, 10, 18, 9, 0), now })).toMatch(/^Next run today at /);
expect(routineStatusDetail({ ...base, state: "active", hasEnabledWebhook: true })).toBe("Runs when a webhook arrives");
expect(routineStatusDetail({ ...base, state: "active", hasStandingCheck: true })).toBe("Checked each time the agent wakes up");
expect(routineStatusDetail({ ...base, state: "active" })).toBe("Only runs when you start it");
});
it("picks one webhook dialog status", () => {
const hook = { kind: "webhook", enabled: true } as RoutineTrigger;
const active = { routineActive: true, testing: false };
expect(webhookStatusKey({ ...hook, setupPending: true, lastWebhookDelivery: null }, active)).toBe("setup");
expect(webhookStatusKey({ ...hook, setupPending: true, lastWebhookDelivery: null }, { routineActive: true, testing: true })).toBe("setup_testing");
expect(webhookStatusKey({ ...hook, setupPending: true, lastWebhookDelivery: { status: "received", receivedAt: "x", test: true } }, active)).toBe("test_received");
expect(webhookStatusKey({ ...hook, setupPending: true, lastWebhookDelivery: { status: "rejected", receivedAt: "x", test: true } }, active)).toBe("test_rejected");
// A real delivery from before a re-test is not a test result.
expect(webhookStatusKey({ ...hook, setupPending: true, lastWebhookDelivery: { status: "received", receivedAt: "x", test: false } }, active)).toBe("testing");
expect(webhookStatusKey({ ...hook, lastWebhookDelivery: { status: "received", receivedAt: "x", test: false } }, { routineActive: false, testing: false })).toBe("ignored_while_paused");
});
});
@@ -0,0 +1,156 @@
import type { ResponsibilityLinkLookupEntry, RoutineDetail, RoutineEnvConfig, RoutineTrigger } from "@paperclipai/shared";
import { routinesApi } from "@/api/routines";
import { responsibilitiesApi } from "@/api/responsibilities";
import { EMPTY_ROUTINE_FORM_DRAFT, type RoutineFormDraft, type RoutineResponsibilityOption } from "./RoutineEditDialog";
import type { RoutineResponsibility } from "./RoutinePage";
export function localTimezone(): string {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
} catch {
return "UTC";
}
}
/** The schedule the edit form shows: the routine's first schedule. Further schedules are left as they are. */
export function primarySchedule(triggers: readonly RoutineTrigger[]): RoutineTrigger | null {
return triggers.find((trigger) => trigger.kind === "schedule") ?? null;
}
export function routineToDraft(
routine: Pick<RoutineDetail, "title" | "description" | "projectId" | "assigneeAgentId" | "responsibleUserId" | "variables" | "env" | "triggers">,
responsibilityId = "",
): RoutineFormDraft {
const schedule = primarySchedule(routine.triggers);
return {
...EMPTY_ROUTINE_FORM_DRAFT,
title: routine.title,
description: routine.description ?? "",
projectId: routine.projectId ?? "",
assigneeAgentId: routine.assigneeAgentId ?? "",
responsibleUserId: routine.responsibleUserId ?? "",
responsibilityId,
variables: routine.variables,
env: routine.env ?? null,
schedule: schedule?.cronExpression
? { cronExpression: schedule.cronExpression, timezone: schedule.timezone ?? "UTC" }
: null,
};
}
function cleanEnv(env: RoutineEnvConfig | null): RoutineEnvConfig | null {
return env && Object.keys(env).length > 0 ? env : null;
}
/**
* Fields the form owns. Priority and delivery settings (concurrency, catch-up,
* activity gate) have no editor: they are never sent, so saved values stay and
* new routines get the server defaults.
*/
export function routineFieldsPayload(draft: RoutineFormDraft) {
return {
title: draft.title.trim(),
description: draft.description.trim() || null,
projectId: draft.projectId || null,
assigneeAgentId: draft.assigneeAgentId || null,
variables: draft.variables,
env: cleanEnv(draft.env),
};
}
export function routineFieldsChanged(draft: RoutineFormDraft, saved: RoutineFormDraft): boolean {
return JSON.stringify(routineFieldsPayload(draft)) !== JSON.stringify(routineFieldsPayload(saved));
}
type ScheduleDraft = RoutineFormDraft["schedule"];
/**
* Creates, changes or removes the schedule the form opened with (by id, never
* "whichever schedule is first now"), so retrying a partly saved form cannot
* touch another schedule. Removal is undoable server-side (archived).
* Returns the schedule the form now stands for.
*/
export async function syncRoutineSchedule(
routineId: string,
triggers: readonly RoutineTrigger[],
scheduleId: string | null,
schedule: ScheduleDraft,
): Promise<{ changed: boolean; scheduleId: string | null }> {
const existing = scheduleId ? triggers.find((trigger) => trigger.id === scheduleId) ?? null : null;
if (!schedule) {
if (!existing) return { changed: false, scheduleId: null };
await routinesApi.updateTrigger(existing.id, { archived: true });
return { changed: true, scheduleId: null };
}
if (!existing) {
const created = await routinesApi.createTrigger(routineId, { kind: "schedule", cronExpression: schedule.cronExpression, timezone: schedule.timezone });
return { changed: true, scheduleId: created.trigger.id };
}
if (existing.cronExpression === schedule.cronExpression && (existing.timezone ?? "UTC") === schedule.timezone) {
return { changed: false, scheduleId: existing.id };
}
await routinesApi.updateTrigger(existing.id, { cronExpression: schedule.cronExpression, timezone: schedule.timezone });
return { changed: true, scheduleId: existing.id };
}
/** Moves the routine's direct responsibility link from `from` to `to` (either may be empty). */
export async function syncRoutineResponsibility(routineId: string, from: string, to: string) {
if (from === to) return false;
if (to) await responsibilitiesApi.link(to, { routineId });
if (from) {
const previous = await responsibilitiesApi.get(from);
const link = previous.routines.find((routine) => routine.id === routineId && routine.linkId);
if (link?.linkId) await responsibilitiesApi.unlink(from, link.linkId);
}
return true;
}
export type RoutineSavePart = "details" | "schedule" | "responsibility";
const SAVE_PART_LABELS: Record<RoutineSavePart, string> = {
details: "the routine’s details",
schedule: "the schedule",
responsibility: "the responsibility",
};
/** A save that partly went through: says what was saved, what was not, and that saving again finishes it. */
export class PartialRoutineSaveError extends Error {
constructor(saved: readonly RoutineSavePart[], failed: RoutineSavePart, cause: unknown) {
const detail = cause instanceof Error && cause.message ? ` (${cause.message})` : "";
const savedText = saved.map((part) => SAVE_PART_LABELS[part]).join(" and ");
super(`Saved ${savedText}, but ${SAVE_PART_LABELS[failed]} couldn’t be updated${detail}. Save again to finish.`);
this.name = "PartialRoutineSaveError";
}
}
/**
* What the page shows under Responsibility and what the form offers, from the
* routine's link lookup and the person's responsibilities. Indexes each list
* once, so the work stays linear in the number of responsibilities.
*/
export function buildRoutineResponsibilityChoices({
links,
options,
areaTitles,
projectId,
}: {
links: readonly ResponsibilityLinkLookupEntry[];
options: readonly RoutineResponsibilityOption[];
areaTitles: ReadonlyMap<string, string>;
projectId: string | null;
}): { onPage: RoutineResponsibility[]; choices: RoutineResponsibilityOption[] } {
const areaTitle = (areaId: string | null) => (areaId ? areaTitles.get(areaId) ?? null : null);
const throughProject = new Set(links.filter((entry) => entry.via === "project").map((entry) => entry.id));
const offered = new Set(options.map((option) => option.id));
const projectIdsFor = (id: string) => (projectId && throughProject.has(id) ? [projectId] : []);
return {
onPage: links.map((entry) => ({ id: entry.id, title: entry.title, areaTitle: areaTitle(entry.areaId), via: entry.via })),
choices: [
...options.map((option) => ({ ...option, projectIds: projectIdsFor(option.id) })),
// Responsibilities the routine is already under but that are not this person's still show by name.
...links
.filter((entry) => !offered.has(entry.id))
.map((entry) => ({ id: entry.id, title: entry.title, areaTitle: areaTitle(entry.areaId), projectIds: projectIdsFor(entry.id) })),
],
};
}
@@ -0,0 +1,24 @@
/** The routine page lives at `/routines/:id`. Version history and the audit log are its only sub-views. */
export type RoutineView = "routine" | "history" | "activity";
export function routinePath(routineId: string, view: RoutineView = "routine"): string {
return view === "routine" ? `/routines/${routineId}` : `/routines/${routineId}/${view}`;
}
/**
* Where an address for the routine page should lead. Old section links
* (`/overview`, `/triggers`, `/runs`, …, and the legacy `?tab=`) all land on the
* single page; `/history` and `/activity` keep their views. Returns `null` when
* the address is already canonical.
*/
export function resolveRoutineAddress(input: {
routineId: string;
section?: string | null;
legacyTab?: string | null;
}): { view: RoutineView; redirectTo: string | null } {
const requested = input.legacyTab ?? input.section ?? null;
const view: RoutineView = requested === "history" ? "history" : requested === "activity" ? "activity" : "routine";
const canonical = routinePath(input.routineId, view);
const current = input.section ? `/routines/${input.routineId}/${input.section}` : `/routines/${input.routineId}`;
return { view, redirectTo: input.legacyTab || current !== canonical ? canonical : null };
}
@@ -0,0 +1,188 @@
import type { RoutineDetail, RoutineTrigger } from "@paperclipai/shared";
import { describeSchedule } from "@/components/ScheduleEditor";
export type RoutineAutomationState = "active" | "paused" | "draft" | "archived";
/** A routine without a default agent cannot run automatically, whatever its saved status. */
export function routineAutomationState(routine: Pick<RoutineDetail, "status" | "assigneeAgentId">): RoutineAutomationState {
if (routine.status === "archived") return "archived";
if (!routine.assigneeAgentId) return "draft";
return routine.status === "active" ? "active" : "paused";
}
export const ROUTINE_STATE_LABELS: Record<RoutineAutomationState, string> = {
active: "Active",
paused: "Paused",
draft: "Draft",
archived: "Archived",
};
/** What a paused or draft routine skips; null when it would not run on its own anyway. */
export function routinePausedNotice({
state,
hasWebhooks,
hasSchedule,
}: {
state: RoutineAutomationState;
hasWebhooks: boolean;
hasSchedule: boolean;
}): string | null {
if (state !== "paused" && state !== "draft") return null;
if (hasWebhooks && hasSchedule) return "Scheduled runs are skipped and webhook events are ignored until this routine is on.";
if (hasWebhooks) return "Webhook events are ignored until this routine is on. The sending app gets an error.";
if (hasSchedule) return "Scheduled runs are skipped until this routine is on.";
return null;
}
/** The line beside the status switch: when the routine runs next, or why it does not. */
export function routineStatusDetail({
state,
nextRun,
hasEnabledWebhook,
hasStandingCheck,
now,
}: {
state: RoutineAutomationState;
nextRun: Date | null;
hasEnabledWebhook: boolean;
hasStandingCheck: boolean;
now?: Date;
}): string | null {
if (state === "draft") return null;
if (state === "archived") return "No longer runs";
if (state === "paused") return "Run now still works";
if (nextRun) return `Next run ${formatNextRun(nextRun, now)}`;
if (hasEnabledWebhook) return "Runs when a webhook arrives";
if (hasStandingCheck) return "Checked each time the agent wakes up";
return "Only runs when you start it";
}
export function nextScheduledRun(triggers: readonly RoutineTrigger[]): Date | null {
return triggers
.filter((trigger) => trigger.kind === "schedule" && trigger.enabled && trigger.nextRunAt)
.map((trigger) => new Date(trigger.nextRunAt as Date))
.filter((date) => Number.isFinite(date.getTime()))
.sort((left, right) => left.getTime() - right.getTime())[0] ?? null;
}
/** "today at 9:36 AM", "tomorrow at 2:00 PM", otherwise a short dated form. */
export function formatNextRun(date: Date, now: Date = new Date()): string {
const time = date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
const startOfDay = (value: Date) => new Date(value.getFullYear(), value.getMonth(), value.getDate()).getTime();
const days = Math.round((startOfDay(date) - startOfDay(now)) / 86_400_000);
if (days === 0) return `today at ${time}`;
if (days === 1) return `tomorrow at ${time}`;
const day = date.toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric" });
return `${day} at ${time}`;
}
export function describeScheduleTrigger(trigger: Pick<RoutineTrigger, "cronExpression">): string {
return trigger.cronExpression ? describeSchedule(trigger.cronExpression) : "Schedule";
}
export function webhookTitle(trigger: Pick<RoutineTrigger, "signingMode" | "label">): string {
const kind = trigger.signingMode === "github_hmac" ? "GitHub webhook" : "Webhook";
return trigger.label ? `${kind} · ${trigger.label}` : kind;
}
export type WebhookHealth = "setup" | "testing" | "paused" | "rejected" | "receiving" | "waiting";
/** A webhook that went live before and was put back into test mode (it has a real delivery on record). */
export function webhookRetesting(trigger: Pick<RoutineTrigger, "setupPending" | "lastWebhookDelivery">): boolean {
const delivery = trigger.lastWebhookDelivery;
if (!trigger.setupPending || !delivery) return false;
return delivery.test ? delivery.previous != null : true;
}
export function webhookHealth(trigger: RoutineTrigger): WebhookHealth {
if (trigger.setupPending) return webhookRetesting(trigger) ? "testing" : "setup";
if (!trigger.enabled) return "paused";
if (trigger.lastWebhookDelivery?.status === "rejected") return "rejected";
if (trigger.lastWebhookDelivery?.status === "received" && !trigger.lastWebhookDelivery.test) return "receiving";
return "waiting";
}
export const WEBHOOK_HEALTH_LABELS: Record<WebhookHealth, string> = {
setup: "Setup unfinished",
testing: "Testing · events don’t run",
paused: "Paused",
rejected: "Key rejected",
receiving: "Receiving events",
waiting: "Waiting for the first event",
};
/** Which status the webhook dialog shows; each key has one entry in WEBHOOK_STATUS_COPY. */
export type WebhookStatusKey =
| WebhookHealth
| "setup_testing"
| "test_received"
| "test_rejected"
| "ignored_while_paused";
export function webhookStatusKey(
trigger: RoutineTrigger,
{ routineActive, testing }: { routineActive: boolean; testing: boolean },
): WebhookStatusKey {
const health = webhookHealth(trigger);
// Only test deliveries count: a webhook put back into test mode still carries its last real delivery.
const testDelivery = trigger.setupPending && trigger.lastWebhookDelivery?.test ? trigger.lastWebhookDelivery : null;
if (testDelivery?.status === "received") return "test_received";
if (testDelivery?.status === "rejected") return "test_rejected";
if (!routineActive && health !== "setup" && health !== "testing") return "ignored_while_paused";
if (health === "setup" && testing) return "setup_testing";
return health;
}
export const WEBHOOK_STATUS_COPY: Record<WebhookStatusKey, { title: string; detail: string }> = {
setup: { title: "Waiting for a test event", detail: "Send one from your app. Test events never start the routine." },
setup_testing: {
title: "Waiting for a test event",
detail: "Send one from your app. It won’t start the routine. Real events are ignored until you finish testing.",
},
testing: {
title: "Testing",
detail: "Send an event from your app. It won’t start the routine. Real events are ignored until you finish testing.",
},
waiting: { title: "Ready", detail: "The next event starts this routine." },
receiving: { title: "Receiving events", detail: "Each event starts this routine." },
rejected: {
title: "The last event was rejected",
detail: "The key didn’t match. Replace the key, then paste the new one into your app.",
},
test_rejected: {
title: "The last event was rejected",
detail: "The key didn’t match. Replace the key, then paste the new one into your app.",
},
test_received: { title: "Test event received", detail: "The connection works. No task was created." },
ignored_while_paused: {
title: "Ignoring events while the routine is paused",
detail: "Turn the routine on to start it from this webhook. Until then the sending app gets an error.",
},
paused: { title: "Paused", detail: "Events are ignored until you resume this webhook." },
};
/** Plain-language lines for saved run rules that differ from the defaults. Empty for most routines. */
export function customRunRules(
routine: Pick<RoutineDetail, "concurrencyPolicy" | "catchUpPolicy" | "activityGatePolicy" | "activityGateScope">,
): string[] {
const rules: string[] = [];
if (routine.concurrencyPolicy === "always_enqueue") rules.push("Queues every run, even while one is still working");
if (routine.concurrencyPolicy === "skip_if_active") rules.push("Skips a run while one is still working");
if (routine.catchUpPolicy === "enqueue_missed_with_cap") rules.push("Catches up on runs missed while paused");
if (routine.activityGatePolicy === "require_external_activity") {
rules.push(
routine.activityGateScope === "project"
? "Skips scheduled runs when nothing changed in its project"
: "Skips scheduled runs when nothing changed",
);
}
return rules;
}
/** First paragraph of the instructions; a leading heading keeps the paragraph under it. */
export function instructionsPreview(markdown: string): { preview: string; truncated: boolean } {
const blocks = markdown.trim().split(/\n\s*\n/);
if (blocks.length <= 1) return { preview: markdown.trim(), truncated: false };
const take = /^#{1,6}\s/.test(blocks[0] ?? "") ? 2 : 1;
return { preview: blocks.slice(0, take).join("\n\n"), truncated: blocks.length > take };
}
@@ -0,0 +1,144 @@
import { useCallback, useMemo } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { Agent, CompanySecret, Project } from "@paperclipai/shared";
import { accessApi } from "@/api/access";
import { agentsApi } from "@/api/agents";
import { responsibilitiesApi } from "@/api/responsibilities";
import { secretsApi } from "@/api/secrets";
import type { MentionOption } from "@/components/MarkdownEditor";
import { useQueryView } from "@/components/QueryView";
import { useResponsibilitiesEnabled } from "@/hooks/useResponsibilitiesEnabled";
import { companyProjectsQuery } from "@/lib/company-projects-query";
import { buildCompanyUserProfileMap, buildMarkdownMentionOptions } from "@/lib/company-members";
import { queryKeys } from "@/lib/queryKeys";
import type { RoutineResponsibilityOption } from "./RoutineEditDialog";
import type { RoutinePerson } from "./RoutinePage";
// Stable empty lists, so memoized consumers do not rebuild while reads are pending.
const NO_AGENTS: Agent[] = [];
const NO_PROJECTS: Project[] = [];
const NO_SECRETS: CompanySecret[] = [];
/**
* Everything the routine page and the edit/create form choose from: agents,
* projects, people, secrets, mention options and (only while the experimental
* flag is on) responsibilities. Shared by the routine page and the routines
* list so both open the same form with the same choices.
*/
export function useRoutineFormOptions(
companyId: string | null | undefined,
{ active = true }: { active?: boolean } = {},
) {
const queryClient = useQueryClient();
// Nothing is fetched until the form (or page) that needs these choices is shown.
const enabled = Boolean(companyId) && active;
const { enabled: responsibilitiesOn } = useResponsibilitiesEnabled();
const agentsQuery = useQuery({
queryKey: queryKeys.agents.list(companyId ?? ""),
queryFn: () => agentsApi.list(companyId!),
enabled,
});
const projectsQuery = useQuery({ ...companyProjectsQuery(companyId ?? "", { includeArchived: true }), enabled });
const directoryQuery = useQuery({
queryKey: queryKeys.access.companyUserDirectory(companyId ?? ""),
queryFn: () => accessApi.listUserDirectory(companyId!),
enabled,
});
const secretsQuery = useQuery({
queryKey: queryKeys.secrets.list(companyId ?? ""),
queryFn: () => secretsApi.list(companyId!),
enabled,
});
const responsibilitiesQuery = useQuery({
queryKey: queryKeys.responsibilities.overview(companyId ?? ""),
queryFn: () => responsibilitiesApi.overview(companyId!),
enabled: enabled && responsibilitiesOn,
});
// Failed reads are reported, never shown as empty choices.
const agentsView = useQueryView(agentsQuery);
const projectsView = useQueryView(projectsQuery);
const peopleView = useQueryView(directoryQuery);
const secretsView = useQueryView(secretsQuery);
const responsibilitiesView = useQueryView(responsibilitiesQuery);
const loadErrors = [
{ action: "load agents", view: agentsView },
{ action: "load projects", view: projectsView },
{ action: "load people", view: peopleView },
{ action: "load secrets", view: secretsView },
{ action: "load responsibilities", view: responsibilitiesView },
]
.filter(({ view }) => view.kind === "error")
.map(({ action, view }) => ({ action, error: view.error, retry: view.retry, retrying: view.isFetching }));
const allAgents = agentsQuery.data;
const agents = useMemo(
() => (allAgents ?? []).filter((agent) => agent.status !== "terminated"),
[allAgents],
);
const allProjects = projectsQuery.data;
const projects = useMemo(
() => (allProjects ?? []).filter((project) => !project.archivedAt),
[allProjects],
);
const members = directoryQuery.data?.users;
const people = useMemo<RoutinePerson[]>(() => {
const profiles = buildCompanyUserProfileMap(members);
const seen = new Set<string>();
const result: RoutinePerson[] = [];
for (const member of members ?? []) {
if (member.status !== "active" || seen.has(member.principalId)) continue;
seen.add(member.principalId);
const profile = profiles.get(member.principalId);
result.push({ id: member.principalId, name: profile?.label ?? "Unnamed person", avatarUrl: profile?.image ?? null });
}
return result.sort((left, right) => left.name.localeCompare(right.name));
}, [members]);
const mentions = useMemo<MentionOption[]>(
() => buildMarkdownMentionOptions({ agents: allAgents, projects, members }),
[allAgents, members, projects],
);
const overview = responsibilitiesQuery.data;
const responsibilities = useMemo<RoutineResponsibilityOption[] | undefined>(() => {
if (!responsibilitiesOn) return undefined;
const areaTitles = new Map((overview?.areas ?? []).map((area) => [area.id, area.title]));
return [...(overview?.responsibilities ?? []), ...(overview?.proposed ?? [])].map((responsibility) => ({
id: responsibility.id,
title: responsibility.title,
areaTitle: responsibility.areaId ? areaTitles.get(responsibility.areaId) ?? null : null,
}));
}, [overview, responsibilitiesOn]);
const areaTitles = useMemo(() => new Map((overview?.areas ?? []).map((area) => [area.id, area.title])), [overview]);
const createSecretMutation = useMutation({
mutationFn: (input: { name: string; value: string }) => secretsApi.create(companyId!, input),
onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.secrets.list(companyId!) }),
});
const { mutateAsync: createSecretAsync } = createSecretMutation;
const createSecret = useCallback(
(name: string, value: string): Promise<CompanySecret> => createSecretAsync({ name, value }),
[createSecretAsync],
);
return {
agents,
/** Includes terminated agents, so a routine's saved agent still shows by name. */
allAgents: allAgents ?? NO_AGENTS,
projects,
/** Includes archived projects, so a routine's saved project still shows by name. */
allProjects: allProjects ?? NO_PROJECTS,
people,
secrets: secretsQuery.data ?? NO_SECRETS,
mentions,
responsibilitiesOn,
responsibilities,
areaTitles,
createSecret,
/** Reads that failed, each with a retry. */
loadErrors,
/** People could not be loaded, so a saved responsible user cannot be named. */
peopleFailed: peopleView.kind === "error" && !members,
};
}
@@ -0,0 +1,207 @@
import { useCallback, useRef, useState } from "react";
import type { RoutineTrigger } from "@paperclipai/shared";
import { describeError } from "@/api/errors";
import { routinesApi } from "@/api/routines";
import type { RoutineWebhookDialogProps, WebhookSender } from "./RoutineWebhookDialog";
/** A webhook key to show once, e.g. after a version restore recreated the webhook. */
export type PendingWebhookKey = {
triggerId: string;
webhookUrl: string;
webhookSecret: string;
/** From the restored revision; null when unknown, and then no signing instructions are shown until the routine refresh lists the webhook. */
signingMode?: string | null;
};
/** Enough of a restored webhook to show its URL and new key before the routine refresh lists it. */
function restoredPlaceholder(key: PendingWebhookKey): RoutineTrigger {
const now = new Date();
return {
id: key.triggerId,
companyId: "",
routineId: "",
kind: "webhook",
label: null,
enabled: true,
cronExpression: null,
timezone: null,
nextRunAt: null,
lastFiredAt: null,
publicId: null,
webhookUrl: key.webhookUrl,
setupPending: false,
lastWebhookDelivery: null,
secretId: null,
signingMode: key.signingMode ?? null,
replayWindowSec: null,
lastRotatedAt: null,
lastResult: null,
createdByAgentId: null,
createdByUserId: null,
updatedByAgentId: null,
updatedByUserId: null,
createdAt: now,
updatedAt: now,
};
}
/**
* Wires the webhook dialog to the trigger API: create (setup mode), replace
* key, pause/resume, remove, and test mode. Every change is saved right away;
* `onChanged` refreshes the routine. Closing the dialog while a webhook is in
* setup or test mode ends it, so nothing is left silently ignoring events.
*/
export function useRoutineWebhookDialog({
routineId,
triggers,
onChanged,
onRemoved,
}: {
routineId: string;
triggers: readonly RoutineTrigger[];
onChanged: () => Promise<unknown> | void;
onRemoved?: (trigger: RoutineTrigger) => void;
}) {
const [open, setOpen] = useState(false);
const [triggerId, setTriggerId] = useState<string | null>(null);
const [created, setCreated] = useState<RoutineTrigger | null>(null);
/** A restored webhook's URL, shown with its new key until the refreshed routine lists it. */
const [restored, setRestored] = useState<PendingWebhookKey | null>(null);
const [secret, setSecret] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const queue = useRef<PendingWebhookKey[]>([]);
/** A change is being saved; closing waits for it so a half-started test is never left behind. */
const busyRef = useRef(false);
const saved = triggerId ? triggers.find((trigger) => trigger.id === triggerId) ?? null : null;
const trigger = saved
?? (created && created.id === triggerId ? created : null)
?? (restored && restored.triggerId === triggerId ? restoredPlaceholder(restored) : null);
// A webhook created in this dialog is in first setup; any other webhook in
// setup mode was put back into test mode (or left mid-setup) and offers Finish testing.
const testing = Boolean(trigger?.setupPending) && created?.id !== trigger?.id;
const run = useCallback(
async (action: () => Promise<void>, failure: string) => {
busyRef.current = true;
setBusy(true);
setError(null);
try {
await action();
await onChanged();
return true;
} catch (cause) {
setError(describeError(cause, { action: failure }).body);
return false;
} finally {
busyRef.current = false;
setBusy(false);
}
},
[onChanged],
);
const show = useCallback((next: RoutineTrigger | null, key: string | null = null) => {
setTriggerId(next?.id ?? null);
setCreated(null);
setRestored(null);
setSecret(key);
setError(null);
setOpen(true);
}, []);
const showNextPendingKey = useCallback(() => {
const next = queue.current.shift();
if (!next) return false;
setTriggerId(next.triggerId);
setCreated(null);
setRestored(next);
setSecret(next.webhookSecret);
setError(null);
setOpen(true);
return true;
}, []);
/** Shows each restored webhook's new key once, one after another. */
const showKeys = useCallback(
(keys: PendingWebhookKey[]) => {
queue.current = [...keys];
showNextPendingKey();
},
[showNextPendingKey],
);
/** Closes the dialog, ending setup or test mode first. Ignored while a change is saving. */
const close = useCallback(async () => {
if (busyRef.current) return;
const current = trigger;
if (current?.setupPending) {
// Stay open if this fails, so the error is seen and the webhook is not left in test mode unnoticed.
const finished = await run(
() => routinesApi.updateTrigger(current.id, { setupPending: false }).then(() => undefined),
current.id === created?.id ? "finish setting up the webhook" : "finish testing the webhook",
);
if (!finished) return;
}
setOpen(false);
setSecret(null);
showNextPendingKey();
}, [created?.id, run, showNextPendingKey, trigger]);
const dialogProps: Omit<RoutineWebhookDialogProps, "routineTitle" | "routineActive"> = {
open,
onOpenChange: (next) => {
if (next) setOpen(true);
else void close();
},
trigger,
secret,
busy,
error,
testing,
onCreate: (sender: WebhookSender) => {
void run(async () => {
const response = await routinesApi.createTrigger(routineId, {
kind: "webhook",
signingMode: sender === "github" ? "github_hmac" : "app_webhook",
setupPending: true,
});
setCreated({ ...response.trigger, webhookUrl: response.secretMaterial?.webhookUrl ?? response.trigger.webhookUrl });
setTriggerId(response.trigger.id);
setSecret(response.secretMaterial?.webhookSecret ?? null);
}, "create the webhook");
},
onReplaceKey: () => {
if (!trigger) return;
void run(async () => {
const response = await routinesApi.rotateTriggerSecret(trigger.id);
setSecret(response.secretMaterial.webhookSecret);
}, "replace the key");
},
onSetPaused: (paused) => {
if (!trigger) return;
void run(() => routinesApi.updateTrigger(trigger.id, { enabled: !paused }).then(() => undefined), paused ? "pause the webhook" : "resume the webhook");
},
onRemove: () => {
if (!trigger) return;
const removed = trigger;
void run(async () => {
await routinesApi.updateTrigger(removed.id, { archived: true });
setOpen(false);
setSecret(null);
onRemoved?.(removed);
}, "remove the webhook");
},
onStartTest: () => {
if (!trigger) return;
void run(() => routinesApi.updateTrigger(trigger.id, { setupPending: true }).then(() => undefined), "start testing the webhook");
},
onFinishTest: () => {
if (!trigger) return;
void run(() => routinesApi.updateTrigger(trigger.id, { setupPending: false }).then(() => undefined), "finish testing the webhook");
},
};
return { open, show, showKeys, close, dialogProps };
}