Files
PaperClipAI/ui/src/components/RoutineVariablesEditor.tsx
T
DottaandClaude Fable 5.2 33fac97cad 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>
2026-11-18 13:13:15 -06:00

509 lines
22 KiB
TypeScript

import { useEffect, useMemo, useState } from "react";
import { ChevronDown, ChevronRight, HelpCircle } from "lucide-react";
import { isValidRoutineDateString, syncRoutineVariablesWithTemplate, type RoutineVariable } from "@paperclipai/shared";
import { Badge } from "@/components/ui/badge";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
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 { Textarea } from "@/components/ui/textarea";
const variableTypes: RoutineVariable["type"][] = ["text", "textarea", "number", "boolean", "select", "date"];
function serializeVariables(value: RoutineVariable[]) {
return JSON.stringify(value);
}
function parseSelectOptions(value: string) {
return value
.split(",")
.map((entry) => entry.trim())
.filter(Boolean);
}
function updateVariableList(
variables: RoutineVariable[],
name: string,
mutate: (variable: RoutineVariable) => RoutineVariable,
) {
return variables.map((variable) => (variable.name === name ? mutate(variable) : variable));
}
function defaultValueForType(type: RoutineVariable["type"], current: RoutineVariable["defaultValue"]) {
if (type === "boolean") return null;
if (type === "date") {
return typeof current === "string" && isValidRoutineDateString(current) ? current : null;
}
return current;
}
export function RoutineVariablesEditor({
title,
description,
value,
onChange,
variant = "default",
}: {
title: string;
description: string;
value: RoutineVariable[];
onChange: (value: RoutineVariable[]) => void;
/** `compact` puts each variable on one row under shared column labels. */
variant?: "default" | "compact";
}) {
const [open, setOpen] = useState(true);
const syncedVariables = useMemo(
() => syncRoutineVariablesWithTemplate([title, description], value),
[description, title, value],
);
const syncedSignature = serializeVariables(syncedVariables);
const currentSignature = serializeVariables(value);
useEffect(() => {
if (syncedSignature !== currentSignature) {
onChange(syncedVariables);
}
}, [currentSignature, onChange, syncedSignature, syncedVariables]);
if (syncedVariables.length === 0) {
return null;
}
if (variant === "compact") {
return (
<CompactVariableRows
variables={syncedVariables}
onPatch={(name, mutate) => onChange(updateVariableList(syncedVariables, name, mutate))}
/>
);
}
return (
<Collapsible open={open} onOpenChange={setOpen} className="overflow-hidden rounded-lg border border-border/70">
<CollapsibleTrigger className="flex w-full items-center justify-between px-3 py-2 text-left">
<div>
<p className="text-sm font-medium">Variables</p>
<p className="text-xs text-muted-foreground">
Detected from `{"{{name}}"}` placeholders in the title and instructions.
</p>
</div>
{open ? <ChevronDown className="h-4 w-4 text-muted-foreground" /> : <ChevronRight className="h-4 w-4 text-muted-foreground" />}
</CollapsibleTrigger>
<CollapsibleContent className="divide-y divide-border/70 border-t border-border/70">
{syncedVariables.map((variable) => (
<div key={variable.name} className="p-4">
<div className="mb-3 flex flex-wrap items-center gap-2">
<Badge variant="outline" className="font-mono text-xs">
{`{{${variable.name}}}`}
</Badge>
<span className="text-xs text-muted-foreground">
Prompt the user for this value before each manual run.
</span>
</div>
<div className="grid gap-3 md:grid-cols-2">
<div className="space-y-1.5">
<Label className="text-xs">Label</Label>
<Input
value={variable.label ?? ""}
onChange={(event) => onChange(updateVariableList(syncedVariables, variable.name, (current) => ({
...current,
label: event.target.value || null,
})))}
placeholder={variable.name.replaceAll("_", " ")}
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Type</Label>
<Select
value={variable.type}
onValueChange={(type) => onChange(updateVariableList(syncedVariables, variable.name, (current) => ({
...current,
type: type as RoutineVariable["type"],
defaultValue: defaultValueForType(type as RoutineVariable["type"], current.defaultValue),
options: type === "select" ? current.options : [],
})))}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{variableTypes.map((type) => (
<SelectItem key={type} value={type}>{type}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5 md:col-span-2">
<div className="flex items-center justify-between gap-3">
<Label className="text-xs">Default value</Label>
<label className="flex items-center gap-2 text-xs text-muted-foreground">
<input
type="checkbox"
checked={variable.required}
onChange={(event) => onChange(updateVariableList(syncedVariables, variable.name, (current) => ({
...current,
required: event.target.checked,
})))}
/>
Required
</label>
</div>
{variable.type === "textarea" ? (
<Textarea
rows={3}
value={variable.defaultValue == null ? "" : String(variable.defaultValue)}
onChange={(event) => onChange(updateVariableList(syncedVariables, variable.name, (current) => ({
...current,
defaultValue: event.target.value || null,
})))}
/>
) : variable.type === "boolean" ? (
<Select
value={variable.defaultValue === true ? "true" : variable.defaultValue === false ? "false" : "__unset__"}
onValueChange={(next) => onChange(updateVariableList(syncedVariables, variable.name, (current) => ({
...current,
defaultValue: next === "__unset__" ? null : next === "true",
})))}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="__unset__">No default</SelectItem>
<SelectItem value="true">True</SelectItem>
<SelectItem value="false">False</SelectItem>
</SelectContent>
</Select>
) : variable.type === "select" ? (
<div className="grid gap-3 md:grid-cols-2">
<div className="space-y-1.5">
<Label className="text-xs">Options</Label>
<Input
value={variable.options.join(", ")}
onChange={(event) => {
const options = parseSelectOptions(event.target.value);
onChange(updateVariableList(syncedVariables, variable.name, (current) => ({
...current,
options,
defaultValue:
typeof current.defaultValue === "string" && options.includes(current.defaultValue)
? current.defaultValue
: null,
})));
}}
placeholder="high, medium, low"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Default option</Label>
<Select
value={typeof variable.defaultValue === "string" ? variable.defaultValue : "__unset__"}
onValueChange={(next) => onChange(updateVariableList(syncedVariables, variable.name, (current) => ({
...current,
defaultValue: next === "__unset__" ? null : next,
})))}
>
<SelectTrigger>
<SelectValue placeholder="No default" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__unset__">No default</SelectItem>
{variable.options.map((option) => (
<SelectItem key={option} value={option}>{option}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
) : variable.type === "date" ? (
<Input
type="date"
value={typeof variable.defaultValue === "string" ? variable.defaultValue : ""}
onChange={(event) => onChange(updateVariableList(syncedVariables, variable.name, (current) => ({
...current,
defaultValue: event.target.value || null,
})))}
/>
) : (
<Input
type={variable.type === "number" ? "number" : "text"}
value={variable.defaultValue == null ? "" : String(variable.defaultValue)}
onChange={(event) => onChange(updateVariableList(syncedVariables, variable.name, (current) => ({
...current,
defaultValue: event.target.value || null,
})))}
placeholder={variable.type === "number" ? "42" : "Default value"}
/>
)}
</div>
</div>
</div>
))}
</CollapsibleContent>
</Collapsible>
);
}
const compactColumns = {
name: "w-full shrink-0 sm:w-48",
type: "w-28 shrink-0",
defaultValue: "min-w-0 flex-1 basis-32",
required: "flex w-16 shrink-0 justify-center",
};
/** One row per variable: name, type, default and required, with the column labels shown once.
* A saved label is kept as-is; this layout does not edit it. */
function CompactVariableRows({
variables,
onPatch,
}: {
variables: RoutineVariable[];
onPatch: (name: string, mutate: (variable: RoutineVariable) => RoutineVariable) => void;
}) {
return (
<div className="flex flex-col gap-2" role="group" aria-label="Variables">
<Label>Variables</Label>
<div className="hidden items-center gap-2 text-xs text-muted-foreground sm:flex" aria-hidden="true">
<span className={compactColumns.name}>Name</span>
<span className={compactColumns.type}>Type</span>
<span className={compactColumns.defaultValue}>Default</span>
<span className={compactColumns.required}>Required</span>
</div>
{variables.map((variable) => {
const patch = (change: Partial<RoutineVariable>) => onPatch(variable.name, (current) => ({ ...current, ...change }));
return (
<div key={variable.name} className="flex flex-col gap-2">
<div className="flex flex-wrap items-center gap-2">
<code className={`${compactColumns.name} truncate font-mono text-xs`} title={`{{${variable.name}}}`}>
{`{{${variable.name}}}`}
</code>
<Select
value={variable.type}
onValueChange={(type) => onPatch(variable.name, (current) => ({
...current,
type: type as RoutineVariable["type"],
defaultValue: defaultValueForType(type as RoutineVariable["type"], current.defaultValue),
options: type === "select" ? current.options : [],
}))}
>
<SelectTrigger className={compactColumns.type} aria-label={`Type of ${variable.name}`}>
<SelectValue />
</SelectTrigger>
<SelectContent>
{variableTypes.map((type) => (
<SelectItem key={type} value={type}>{type}</SelectItem>
))}
</SelectContent>
</Select>
<div className={compactColumns.defaultValue}>
{variable.type === "boolean" ? (
<Select
value={variable.defaultValue === true ? "true" : variable.defaultValue === false ? "false" : "__unset__"}
onValueChange={(next) => patch({ defaultValue: next === "__unset__" ? null : next === "true" })}
>
<SelectTrigger className="w-full" aria-label={`Default for ${variable.name}`}>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="__unset__">No default</SelectItem>
<SelectItem value="true">True</SelectItem>
<SelectItem value="false">False</SelectItem>
</SelectContent>
</Select>
) : variable.type === "select" ? (
<Select
value={typeof variable.defaultValue === "string" ? variable.defaultValue : "__unset__"}
onValueChange={(next) => patch({ defaultValue: next === "__unset__" ? null : next })}
>
<SelectTrigger className="w-full" aria-label={`Default for ${variable.name}`}>
<SelectValue placeholder="No default" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__unset__">No default</SelectItem>
{variable.options.map((option) => (
<SelectItem key={option} value={option}>{option}</SelectItem>
))}
</SelectContent>
</Select>
) : variable.type === "textarea" ? (
<Textarea
rows={1}
aria-label={`Default for ${variable.name}`}
value={variable.defaultValue == null ? "" : String(variable.defaultValue)}
placeholder="No default"
onChange={(event) => patch({ defaultValue: event.target.value || null })}
/>
) : (
<Input
type={variable.type === "number" ? "number" : variable.type === "date" ? "date" : "text"}
aria-label={`Default for ${variable.name}`}
value={variable.defaultValue == null ? "" : String(variable.defaultValue)}
placeholder="No default"
onChange={(event) => patch({ defaultValue: event.target.value || null })}
/>
)}
</div>
<label className={`${compactColumns.required} items-center gap-2 text-xs text-muted-foreground`}>
<input
type="checkbox"
checked={variable.required}
aria-label={`${variable.name} is required`}
onChange={(event) => patch({ required: event.target.checked })}
/>
<span className="sm:hidden">Required</span>
</label>
</div>
{variable.type === "select" ? (
<div className="flex items-center gap-2">
<span className={`${compactColumns.name} hidden sm:block`} aria-hidden="true" />
<Input
className="min-w-0 flex-1"
aria-label={`Options for ${variable.name}`}
value={variable.options.join(", ")}
placeholder="Options, separated by commas: high, medium, low"
onChange={(event) => {
const options = parseSelectOptions(event.target.value);
onPatch(variable.name, (current) => ({
...current,
options,
defaultValue:
typeof current.defaultValue === "string" && options.includes(current.defaultValue)
? current.defaultValue
: null,
}));
}}
/>
<span className={`${compactColumns.required} hidden sm:block`} aria-hidden="true" />
</div>
) : null}
</div>
);
})}
</div>
);
}
type BuiltinVariableDoc = {
name: string;
example: string;
description: string;
};
const BUILTIN_VARIABLE_DOCS: BuiltinVariableDoc[] = [
{
name: "date",
example: "2026-04-28",
description: "Current date in YYYY-MM-DD format (UTC) at the time the routine runs.",
},
{
name: "timestamp",
example: "April 28, 2026 at 12:17 PM UTC",
description: "Human-readable date and time (UTC) at the time the routine runs.",
},
];
export function RoutineVariablesHint() {
const [helpOpen, setHelpOpen] = useState(false);
return (
<>
<div className="flex items-center justify-between gap-2 rounded-lg border border-dashed border-border/70 px-3 py-2 text-xs text-muted-foreground">
<span>
Use `{"{{variable_name}}"}` placeholders in the title or instructions to prompt for inputs when the routine runs.
</span>
<button
type="button"
onClick={() => setHelpOpen(true)}
className="shrink-0 rounded-full p-0.5 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label="Show variable help"
>
<HelpCircle className="h-3.5 w-3.5" />
</button>
</div>
<Dialog open={helpOpen} onOpenChange={setHelpOpen}>
<DialogContent className="sm:max-w-xl">
<DialogHeader>
<DialogTitle>Routine variables</DialogTitle>
<DialogDescription>
How to prompt for inputs and which variables Paperclip fills in automatically.
</DialogDescription>
</DialogHeader>
<div className="space-y-5 text-sm">
<section className="space-y-2">
<h3 className="text-xs font-semibold uppercase tracking-(--tracking-caps) text-muted-foreground">
Custom variables
</h3>
<p className="text-muted-foreground">
Type{" "}
<code className="rounded bg-muted px-1 py-0.5 font-mono text-xs text-foreground">
{"{{variable_name}}"}
</code>{" "}
anywhere in the title or instructions. Paperclip detects each placeholder, lists it
under <span className="font-medium text-foreground">Variables</span>, and prompts
for a value before each run.
</p>
<ul className="list-disc space-y-1 pl-5 text-muted-foreground">
<li>Names must start with a letter and may use letters, numbers, and underscores.</li>
<li>Pick a type (text, textarea, number, boolean, select, date), default value, and whether it is required.</li>
<li>Variable names ending in capital Date, such as startDate, are created as date variables by default.</li>
<li>The same name reused across the title and instructions is treated as one variable.</li>
</ul>
</section>
<section className="space-y-2">
<h3 className="text-xs font-semibold uppercase tracking-(--tracking-caps) text-muted-foreground">
Built-in variables
</h3>
<p className="text-muted-foreground">
These are filled in automatically — no setup needed and they will not appear in the
Variables list.
</p>
<div className="overflow-hidden rounded-lg border border-border/70">
<table className="w-full text-left text-xs">
<thead className="bg-muted/40 text-muted-foreground">
<tr>
<th className="px-3 py-2 font-medium">Placeholder</th>
<th className="px-3 py-2 font-medium">Example</th>
<th className="px-3 py-2 font-medium">Description</th>
</tr>
</thead>
<tbody className="divide-y divide-border/70">
{BUILTIN_VARIABLE_DOCS.map((entry) => (
<tr key={entry.name} className="align-top">
<td className="px-3 py-2">
<Badge variant="outline" className="font-mono text-xs">{`{{${entry.name}}}`}</Badge>
</td>
<td className="px-3 py-2 font-mono text-muted-foreground">{entry.example}</td>
<td className="px-3 py-2 text-muted-foreground">{entry.description}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
</div>
</DialogContent>
</Dialog>
</>
);
}