mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 11:54:35 +01:00
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:
1 parent
f4d44ac13e
commit
33fac97cad
94 files changed
+6116
-9212
No files matched your search
@@ -20,6 +20,8 @@ interface InlineEntitySelectorProps {
|
||||
noneAtTop?: boolean;
|
||||
/** Keep the no-selection action after the project choices. */
|
||||
noneAtEnd?: boolean;
|
||||
/** Leave out the no-selection action, for a value that can be changed but not cleared. */
|
||||
hideNone?: boolean;
|
||||
searchPlaceholder: string;
|
||||
emptyMessage: string;
|
||||
onChange: (id: string) => void;
|
||||
@@ -76,6 +78,7 @@ export const InlineEntitySelector = forwardRef<HTMLButtonElement, InlineEntitySe
|
||||
noneLabel,
|
||||
noneAtTop = false,
|
||||
noneAtEnd = false,
|
||||
hideNone = false,
|
||||
searchPlaceholder,
|
||||
emptyMessage,
|
||||
onChange,
|
||||
@@ -107,11 +110,12 @@ export const InlineEntitySelector = forwardRef<HTMLButtonElement, InlineEntitySe
|
||||
const isPointerDownRef = useRef(false);
|
||||
|
||||
const allOptions = useMemo<InlineEntityOption[]>(() => {
|
||||
if (hideNone) return orderItemsBySelectedAndRecent([...options], value, recentOptionIds);
|
||||
const baseOptions = [{ id: "", label: noneLabel, searchText: noneLabel }, ...options];
|
||||
const ordered = orderItemsBySelectedAndRecent(baseOptions, value, recentOptionIds);
|
||||
if (noneAtTop) return [baseOptions[0]!, ...ordered.filter((option) => option.id)];
|
||||
return noneAtEnd ? [...ordered.filter((option) => option.id), baseOptions[0]!] : ordered;
|
||||
}, [noneAtEnd, noneAtTop, noneLabel, options, recentOptionIds, value]);
|
||||
}, [hideNone, noneAtEnd, noneAtTop, noneLabel, options, recentOptionIds, value]);
|
||||
|
||||
const filteredOptions = useMemo(() => {
|
||||
const term = query.trim().toLowerCase();
|
||||
|
||||
@@ -102,12 +102,6 @@ vi.mock("./AgentContextualSidebar", () => ({
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("./RoutineContextualSidebar", () => ({
|
||||
RoutineContextualSidebar: ({ routineId }: { routineId: string }) => (
|
||||
<div>Routine sidebar {routineId}</div>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("./SkillsContextualSidebar", () => ({
|
||||
SkillsContextualSidebar: () => <div>Skills sidebar</div>,
|
||||
}));
|
||||
@@ -885,7 +879,7 @@ describe("Layout", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps global navigation beside Agent and Routine details", async () => {
|
||||
it("keeps global navigation beside Agent details", async () => {
|
||||
async function renderAt(pathname: string) {
|
||||
currentPathname = pathname;
|
||||
const root = createRoot(container);
|
||||
@@ -907,7 +901,6 @@ describe("Layout", () => {
|
||||
"/PAP/agents/briefing-analyst/runs/run-1",
|
||||
"Agent sidebar briefing-analyst",
|
||||
],
|
||||
["/PAP/routines/routine-1/overview", "Routine sidebar routine-1"],
|
||||
] as const) {
|
||||
const root = await renderAt(pathname);
|
||||
expect(container.textContent).toContain(sidebarText);
|
||||
@@ -957,7 +950,7 @@ describe("Layout", () => {
|
||||
expect(container.textContent).toContain("Main company nav");
|
||||
if (pathname.includes("/agents/")) expect(container.textContent).toContain("Agent sidebar");
|
||||
else expect(container.textContent).not.toContain("Agent sidebar");
|
||||
expect(container.textContent).not.toContain("Routine sidebar");
|
||||
if (pathname.includes("/routines/")) expect(container.querySelector("[data-secondary-sidebar]")).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
@@ -1027,7 +1020,7 @@ describe("Layout", () => {
|
||||
|
||||
expect(container.textContent).toContain("Main company nav");
|
||||
expect(container.textContent).not.toContain("Agent sidebar");
|
||||
expect(container.textContent).not.toContain("Routine sidebar");
|
||||
if (pathname.includes("/routines/")) expect(container.querySelector("[data-secondary-sidebar]")).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
|
||||
@@ -5,7 +5,6 @@ import { useBrowserTimeZoneSync } from "@/hooks/useBrowserTimeZoneSync";
|
||||
import { useDesignSandbox } from "@/context/DesignSandboxContext";
|
||||
import { DesignSandboxSidebar } from "./DesignSandboxSidebar";
|
||||
import { BoardDialogs } from "./BoardDialogs";
|
||||
import { SetupWizardSidebarOutlet } from "./SetupWizard";
|
||||
import { ChatSetupSidebarProvider } from "@/context/ChatSetupSidebarContext";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
@@ -16,7 +15,6 @@ import { CompanySettingsNav } from "./access/CompanySettingsNav";
|
||||
import { AppsSidebar, AppsMobileNav } from "./AppsSidebar";
|
||||
import { AppDetailSidebar } from "./AppConnectionSidebar";
|
||||
import { AgentContextualSidebar } from "./AgentContextualSidebar";
|
||||
import { RoutineContextualSidebar } from "./RoutineContextualSidebar";
|
||||
import { SkillsContextualSidebar } from "./SkillsContextualSidebar";
|
||||
import { BreadcrumbBar } from "./BreadcrumbBar";
|
||||
import { PropertiesPanel } from "./PropertiesPanel";
|
||||
@@ -109,12 +107,10 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
|
||||
companyPrefix,
|
||||
pluginRoutePath: matchedPluginRoutePath,
|
||||
agentId,
|
||||
routineId,
|
||||
} = useParams<{
|
||||
companyPrefix: string;
|
||||
pluginRoutePath?: string;
|
||||
agentId?: string;
|
||||
routineId?: string;
|
||||
}>();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
@@ -220,14 +216,11 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
|
||||
) : null;
|
||||
const secondarySidebar = isAgentChatRoute ? <AgentConversationsSidebar /> : shellRoute.builtInContextualSurface === "agent" && agentId ? (
|
||||
<AgentContextualSidebar agentRef={agentId} />
|
||||
) : streamlinedUiEnabled && shellRoute.builtInContextualSurface === "routine" && routineId ? (
|
||||
<SetupWizardSidebarOutlet><RoutineContextualSidebar routineId={routineId} /></SetupWizardSidebarOutlet>
|
||||
) : sharedSecondarySidebar;
|
||||
const hasSecondarySidebar = secondarySidebar != null;
|
||||
const keepsPrimarySidebar = streamlinedUiEnabled && hasSecondarySidebar && (
|
||||
isAgentChatRoute
|
||||
|| shellRoute.builtInContextualSurface === "agent"
|
||||
|| shellRoute.builtInContextualSurface === "routine"
|
||||
|| isAppsRoute
|
||||
|| isToolsRoute
|
||||
);
|
||||
|
||||
@@ -47,7 +47,7 @@ const actionLabels: Record<string, string> = {
|
||||
"routine.webhook_rejected": "Webhook authentication failed",
|
||||
"routine.created": "Routine created", "routine.updated": "Routine updated",
|
||||
"routine.trigger_created": "Trigger added", "routine.trigger_updated": "Trigger updated",
|
||||
"routine.trigger_deleted": "Trigger removed", "routine.trigger_removed": "Trigger removed", "routine.trigger_restored": "Trigger restored", "routine.trigger_setup_finished": "Webhook setup finished", "routine.trigger_secret_rotated": "Webhook key replaced",
|
||||
"routine.trigger_deleted": "Trigger removed", "routine.trigger_removed": "Trigger removed", "routine.trigger_restored": "Trigger restored", "routine.trigger_setup_finished": "Webhook setup finished", "routine.trigger_test_started": "Started testing a webhook", "routine.trigger_secret_rotated": "Webhook key replaced",
|
||||
"routine.run_triggered": "Routine started", "routine.run_created": "Run created",
|
||||
};
|
||||
function actionLabel(action: string) {
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
RoutineContextualSidebar,
|
||||
resolveRoutineDetailDestination,
|
||||
routineDetailHref,
|
||||
} from "./RoutineContextualSidebar";
|
||||
|
||||
vi.mock("@/lib/router", () => ({
|
||||
useParams: () => ({ routineId: "routine-route" }),
|
||||
}));
|
||||
|
||||
vi.mock("@/api/routines", () => ({
|
||||
routinesApi: { get: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("./ContextualSidebarFrame", () => ({
|
||||
ContextualSidebarFrame: ({
|
||||
surface,
|
||||
title,
|
||||
fallbackTo,
|
||||
showHeader,
|
||||
className,
|
||||
children,
|
||||
}: {
|
||||
surface: string;
|
||||
title: string;
|
||||
fallbackTo: string;
|
||||
showHeader?: boolean;
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
}) => (
|
||||
<aside
|
||||
className={className}
|
||||
data-surface={surface}
|
||||
data-title={title}
|
||||
data-fallback={fallbackTo}
|
||||
data-show-header={String(showHeader)}
|
||||
>
|
||||
{children}
|
||||
</aside>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("./SidebarNavItem", () => ({
|
||||
SidebarNavItem: ({ to, label }: { to: string; label: string }) => <a href={to}>{label}</a>,
|
||||
}));
|
||||
|
||||
describe("routine contextual navigation", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
container.remove();
|
||||
});
|
||||
|
||||
it("builds stable routine detail destinations", () => {
|
||||
expect(routineDetailHref("routine-1")).toBe("/routines/routine-1/overview");
|
||||
expect(routineDetailHref("routine-1", "triggers")).toBe("/routines/routine-1/triggers");
|
||||
expect(routineDetailHref("routine-1", "runs")).toBe(
|
||||
"/routines/routine-1/runs",
|
||||
);
|
||||
expect(routineDetailHref("routine-1", "activity")).toBe(
|
||||
"/routines/routine-1/activity",
|
||||
);
|
||||
});
|
||||
|
||||
it("defaults and resolves legacy operation routes locally without remembering a prior section", () => {
|
||||
expect(resolveRoutineDetailDestination({ routineId: "routine-1" }))
|
||||
.toBe("/routines/routine-1/overview");
|
||||
expect(resolveRoutineDetailDestination({ routineId: "routine-1", section: "unknown" }))
|
||||
.toBe("/routines/routine-1/overview");
|
||||
expect(resolveRoutineDetailDestination({ routineId: "routine-1", section: "runs" }))
|
||||
.toBe("/routines/routine-1/runs");
|
||||
expect(resolveRoutineDetailDestination({ routineId: "routine-1", legacyTab: "activity" }))
|
||||
.toBe("/routines/routine-1/activity");
|
||||
});
|
||||
|
||||
it("renders the routine contextual sidebar with configuration and operation links", () => {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
flushSync(() => root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RoutineContextualSidebar routineId="routine-1" title="Weekly release review" />
|
||||
</QueryClientProvider>,
|
||||
));
|
||||
|
||||
const frame = container.querySelector("aside");
|
||||
expect(frame?.getAttribute("data-surface")).toBe("routine");
|
||||
expect(frame?.getAttribute("data-title")).toBe("Weekly release review");
|
||||
expect(frame?.getAttribute("data-fallback")).toBe("/routines");
|
||||
expect(frame?.getAttribute("data-show-header")).toBe("false");
|
||||
expect(frame?.classList).toContain("bg-background");
|
||||
expect(frame?.classList).toContain("border-r");
|
||||
expect(container.querySelector('a[href="/routines/routine-1/overview"]')?.textContent).toBe("Overview");
|
||||
expect(container.querySelector('a[href="/routines/routine-1/triggers"]')?.textContent).toBe("Triggers");
|
||||
expect(container.querySelector('a[href="/routines/routine-1/runs"]'))
|
||||
.not.toBeNull();
|
||||
expect(container.querySelector('a[href="/routines/routine-1/activity"]'))
|
||||
.not.toBeNull();
|
||||
expect(container.textContent).not.toContain("History");
|
||||
});
|
||||
});
|
||||
@@ -1,121 +0,0 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
Activity,
|
||||
Braces,
|
||||
CalendarClock,
|
||||
KeyRound,
|
||||
LayoutDashboard,
|
||||
Play,
|
||||
Repeat,
|
||||
Send,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { routinesApi } from "@/api/routines";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { useParams } from "@/lib/router";
|
||||
import { ContextualSidebarFrame } from "./ContextualSidebarFrame";
|
||||
import { SidebarNavItem } from "./SidebarNavItem";
|
||||
|
||||
export const ROUTINE_DETAIL_VIEWS = [
|
||||
"overview",
|
||||
"triggers",
|
||||
"variables",
|
||||
"delivery",
|
||||
"secrets",
|
||||
"history",
|
||||
"runs",
|
||||
"activity",
|
||||
] as const;
|
||||
|
||||
export type RoutineDetailView = (typeof ROUTINE_DETAIL_VIEWS)[number];
|
||||
|
||||
export type RoutineContextualNavItem = {
|
||||
view: Exclude<RoutineDetailView, "history">;
|
||||
label: string;
|
||||
icon: LucideIcon;
|
||||
};
|
||||
|
||||
export const ROUTINE_CONTEXTUAL_NAV_ITEMS: readonly RoutineContextualNavItem[] = [
|
||||
{ view: "overview", label: "Overview", icon: LayoutDashboard },
|
||||
{ view: "triggers", label: "Triggers", icon: CalendarClock },
|
||||
{ view: "variables", label: "Variables", icon: Braces },
|
||||
{ view: "delivery", label: "Delivery", icon: Send },
|
||||
{ view: "secrets", label: "Secrets", icon: KeyRound },
|
||||
];
|
||||
|
||||
export function isRoutineDetailView(value: string | null | undefined): value is RoutineDetailView {
|
||||
return ROUTINE_DETAIL_VIEWS.includes(value as RoutineDetailView);
|
||||
}
|
||||
|
||||
export function routineDetailHref(routineId: string, view: RoutineDetailView = "overview") {
|
||||
return `/routines/${routineId}/${view}`;
|
||||
}
|
||||
|
||||
/** Keep routine configuration and operations in the routine detail shell. */
|
||||
export function resolveRoutineDetailDestination(input: {
|
||||
routineId: string;
|
||||
section?: string | null;
|
||||
legacyTab?: string | null;
|
||||
}) {
|
||||
const requested = input.legacyTab ?? input.section;
|
||||
if (isRoutineDetailView(requested)) return routineDetailHref(input.routineId, requested);
|
||||
return routineDetailHref(input.routineId, "overview");
|
||||
}
|
||||
|
||||
export function RoutineContextualSidebar({
|
||||
routineId: routineIdProp,
|
||||
title,
|
||||
}: {
|
||||
routineId?: string;
|
||||
title?: string;
|
||||
} = {}) {
|
||||
const params = useParams<{ routineId?: string }>();
|
||||
const routineId = routineIdProp ?? params.routineId ?? "";
|
||||
const { data: routine } = useQuery({
|
||||
queryKey: queryKeys.routines.detail(routineId),
|
||||
queryFn: () => routinesApi.get(routineId),
|
||||
enabled: Boolean(routineId && !title),
|
||||
});
|
||||
const frameTitle = title ?? routine?.title ?? "Routine";
|
||||
|
||||
return (
|
||||
<ContextualSidebarFrame
|
||||
surface="routine"
|
||||
title={frameTitle}
|
||||
icon={Repeat}
|
||||
fallbackTo="/routines"
|
||||
showHeader={false}
|
||||
className="border-r border-border bg-background"
|
||||
>
|
||||
<nav className="min-h-0 flex-1 overflow-y-auto px-3 py-2" aria-label="Routine navigation">
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{ROUTINE_CONTEXTUAL_NAV_ITEMS.map((item) => (
|
||||
<SidebarNavItem
|
||||
key={item.view}
|
||||
to={routineDetailHref(routineId, item.view)}
|
||||
label={item.label}
|
||||
icon={item.icon}
|
||||
end
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p className="px-4 pb-1 pt-5 text-(length:--text-nano) font-mono font-medium uppercase tracking-widest text-muted-foreground/60">
|
||||
Operate
|
||||
</p>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<SidebarNavItem
|
||||
to={routineDetailHref(routineId, "runs")}
|
||||
label="Runs"
|
||||
icon={Play}
|
||||
/>
|
||||
<SidebarNavItem
|
||||
to={routineDetailHref(routineId, "activity")}
|
||||
label="Activity"
|
||||
icon={Activity}
|
||||
/>
|
||||
</div>
|
||||
</nav>
|
||||
</ContextualSidebarFrame>
|
||||
);
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import type { RoutineDetail, RoutineRunSummary } from "@paperclipai/shared";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { RoutineDetailContext, type RoutineDetailContextValue } from "./routine-sections/context";
|
||||
import {
|
||||
RoutineOverview,
|
||||
routineRunIssue,
|
||||
summarizeRoutineSchedule,
|
||||
} from "./RoutineOverview";
|
||||
|
||||
const issueRowRender = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("./RoutineResponsibleUser", () => ({
|
||||
RoutineResponsibleUser: ({ routine }: { routine: RoutineDetail }) => <section data-responsible-routine={routine.id}>Responsible user</section>,
|
||||
}));
|
||||
|
||||
vi.mock("@/components/IssueRow", () => ({
|
||||
IssueRow: (props: { issue: { title: string }; presentation?: string }) => {
|
||||
issueRowRender(props);
|
||||
return <div data-slot="task-row">{props.issue.title}</div>;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/components/MarkdownBody", () => ({
|
||||
MarkdownBody: ({ children }: { children: string }) => <div data-testid="markdown">{children}</div>,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/router", () => ({
|
||||
Link: ({ to, children, ...props }: { to: string; children: ReactNode }) => (
|
||||
<a href={to} {...props}>{children}</a>
|
||||
),
|
||||
}));
|
||||
|
||||
const triggeredAt = new Date("2026-08-31T16:00:00.000Z");
|
||||
const run: RoutineRunSummary = {
|
||||
id: "run-1",
|
||||
companyId: "company-1",
|
||||
routineId: "routine-1",
|
||||
triggerId: "trigger-1",
|
||||
source: "schedule",
|
||||
status: "succeeded",
|
||||
triggeredAt,
|
||||
idempotencyKey: null,
|
||||
triggerPayload: null,
|
||||
dispatchFingerprint: null,
|
||||
linkedIssueId: "issue-1",
|
||||
coalescedIntoRunId: null,
|
||||
failureReason: null,
|
||||
completedAt: triggeredAt,
|
||||
createdAt: triggeredAt,
|
||||
updatedAt: triggeredAt,
|
||||
trigger: { id: "trigger-1", kind: "schedule", label: "weekday" },
|
||||
linkedIssue: {
|
||||
id: "issue-1",
|
||||
identifier: "PAP-42",
|
||||
title: "Prepare the release digest",
|
||||
status: "done",
|
||||
priority: "high",
|
||||
updatedAt: triggeredAt,
|
||||
},
|
||||
};
|
||||
|
||||
const routine = {
|
||||
id: "routine-1",
|
||||
companyId: "company-1",
|
||||
projectId: "project-1",
|
||||
folderId: null,
|
||||
goalId: null,
|
||||
parentIssueId: null,
|
||||
title: "Weekly release review",
|
||||
description: "Summarize **release readiness** for the operator.",
|
||||
assigneeAgentId: "agent-1",
|
||||
priority: "medium",
|
||||
status: "active",
|
||||
concurrencyPolicy: "coalesce_if_active",
|
||||
catchUpPolicy: "skip_missed",
|
||||
activityGatePolicy: "always",
|
||||
activityGateScope: "company",
|
||||
variables: [],
|
||||
env: { PRIVATE_TOKEN: { type: "secret_ref", secretId: "secret-1" } },
|
||||
latestRevisionId: "revision-1",
|
||||
latestRevisionNumber: 1,
|
||||
createdByAgentId: null,
|
||||
createdByUserId: null,
|
||||
responsibleUserId: null,
|
||||
updatedByAgentId: null,
|
||||
updatedByUserId: null,
|
||||
lastTriggeredAt: triggeredAt,
|
||||
lastEnqueuedAt: triggeredAt,
|
||||
createdAt: triggeredAt,
|
||||
updatedAt: triggeredAt,
|
||||
project: null,
|
||||
assignee: { id: "agent-1", name: "Release Manager", role: "manager", title: null, urlKey: "release-manager" },
|
||||
parentIssue: null,
|
||||
triggers: [{
|
||||
id: "trigger-1",
|
||||
companyId: "company-1",
|
||||
routineId: "routine-1",
|
||||
kind: "schedule",
|
||||
label: "weekday",
|
||||
enabled: true,
|
||||
cronExpression: "0 9 * * 1-5",
|
||||
timezone: "America/Los_Angeles",
|
||||
nextRunAt: new Date("2026-09-01T16:00:00.000Z"),
|
||||
lastFiredAt: triggeredAt,
|
||||
publicId: null,
|
||||
secretId: null,
|
||||
signingMode: null,
|
||||
replayWindowSec: null,
|
||||
lastRotatedAt: null,
|
||||
lastResult: "succeeded",
|
||||
createdByAgentId: null,
|
||||
createdByUserId: null,
|
||||
updatedByAgentId: null,
|
||||
updatedByUserId: null,
|
||||
createdAt: triggeredAt,
|
||||
updatedAt: triggeredAt,
|
||||
}],
|
||||
recentRuns: [run],
|
||||
activeIssue: null,
|
||||
} as RoutineDetail;
|
||||
|
||||
function contextFixture(): RoutineDetailContextValue {
|
||||
return {
|
||||
routine,
|
||||
routineId: routine.id,
|
||||
companyId: routine.companyId,
|
||||
routineRuns: [run],
|
||||
currentAssignee: {
|
||||
id: "agent-1",
|
||||
name: "Release Manager",
|
||||
urlKey: "release-manager",
|
||||
},
|
||||
hasLiveRun: false,
|
||||
} as RoutineDetailContextValue;
|
||||
}
|
||||
|
||||
describe("RoutineOverview", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
beforeEach(() => {
|
||||
issueRowRender.mockClear();
|
||||
vi.spyOn(Date, "now").mockReturnValue(new Date("2026-08-31T17:00:00.000Z").getTime());
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
container.remove();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("summarizes enabled schedules and their next run", () => {
|
||||
expect(summarizeRoutineSchedule(routine.triggers)).toMatchObject({
|
||||
label: "1 active schedule",
|
||||
detail: "0 9 * * 1-5 · America/Los_Angeles",
|
||||
nextRunAt: new Date("2026-09-01T16:00:00.000Z"),
|
||||
});
|
||||
expect(summarizeRoutineSchedule([{ ...routine.triggers[0]!, enabled: false }])).toEqual({
|
||||
label: "No active schedule",
|
||||
detail: "Manual runs only",
|
||||
nextRunAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("describes webhook-only routines as externally triggered", () => {
|
||||
expect(summarizeRoutineSchedule([{ ...routine.triggers[0]!, kind: "webhook", enabled: true }])).toEqual({
|
||||
label: "1 active webhook", detail: "Runs on incoming requests", nextRunAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("adapts compact run tasks to the canonical task presentation", () => {
|
||||
const issue = routineRunIssue(run.linkedIssue!, run, "company-1", "project-1");
|
||||
expect(issue).toMatchObject({
|
||||
id: "issue-1",
|
||||
companyId: "company-1",
|
||||
projectId: "project-1",
|
||||
status: "done",
|
||||
priority: "high",
|
||||
originKind: "routine_execution",
|
||||
originId: "routine-1",
|
||||
originRunId: "run-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("shows operational facts, readable description, agent, and recent task rows without secrets", () => {
|
||||
flushSync(() => root.render(
|
||||
<RoutineDetailContext.Provider value={contextFixture()}>
|
||||
<RoutineOverview />
|
||||
</RoutineDetailContext.Provider>,
|
||||
));
|
||||
|
||||
expect(container.textContent).toContain("1 active schedule");
|
||||
expect(container.textContent).toContain("Next run");
|
||||
expect(container.textContent).toContain("Release Manager");
|
||||
expect(container.textContent).toContain("Summarize **release readiness** for the operator.");
|
||||
expect(container.textContent).toContain("Prepare the release digest");
|
||||
expect(container.textContent).not.toContain("PRIVATE_TOKEN");
|
||||
expect(container.textContent).not.toContain("secret-1");
|
||||
expect(issueRowRender).toHaveBeenCalledWith(expect.objectContaining({ presentation: "task" }));
|
||||
expect(container.querySelector('a[href="/routines/routine-1/runs"]'))
|
||||
.not.toBeNull();
|
||||
expect(container.querySelector('a[href="/routines/routine-1/activity"]'))
|
||||
.not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,263 +0,0 @@
|
||||
import type {
|
||||
Issue,
|
||||
IssuePriority,
|
||||
IssueStatus,
|
||||
RoutineRunSummary,
|
||||
RoutineTrigger,
|
||||
} from "@paperclipai/shared";
|
||||
import { ISSUE_PRIORITIES, ISSUE_STATUSES } from "@paperclipai/shared";
|
||||
import { CalendarClock, Clock3, Play, Repeat, UserRound } from "lucide-react";
|
||||
import { IssueRow } from "@/components/IssueRow";
|
||||
import { MarkdownBody } from "@/components/MarkdownBody";
|
||||
import { StatusBadge } from "@/components/StatusBadge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { createIssueDetailLocationState } from "@/lib/issueDetailBreadcrumb";
|
||||
import { Link } from "@/lib/router";
|
||||
import {
|
||||
routineDetailHref,
|
||||
} from "./RoutineContextualSidebar";
|
||||
import { useRoutineDetail } from "./routine-sections/context";
|
||||
import { RoutineResponsibleUser } from "./RoutineResponsibleUser";
|
||||
|
||||
export type RoutineScheduleSummary = {
|
||||
label: string;
|
||||
detail: string;
|
||||
nextRunAt: Date | null;
|
||||
};
|
||||
|
||||
export function formatRoutineTimestamp(value: Date | string) {
|
||||
return new Date(value).toLocaleString(undefined, {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
});
|
||||
}
|
||||
|
||||
export function summarizeRoutineSchedule(triggers: RoutineTrigger[]): RoutineScheduleSummary {
|
||||
const schedules = triggers.filter((trigger) => trigger.kind === "schedule" && trigger.enabled);
|
||||
const nextRunAt = schedules
|
||||
.map((trigger) => trigger.nextRunAt ? new Date(trigger.nextRunAt) : null)
|
||||
.filter((value): value is Date => value !== null && Number.isFinite(value.getTime()))
|
||||
.sort((left, right) => left.getTime() - right.getTime())[0] ?? null;
|
||||
|
||||
if (schedules.length === 0) {
|
||||
const webhooks = triggers.filter((trigger) => trigger.kind === "webhook" && trigger.enabled);
|
||||
if (webhooks.length > 0) {
|
||||
return {
|
||||
label: `${webhooks.length} active webhook${webhooks.length === 1 ? "" : "s"}`,
|
||||
detail: "Runs on incoming requests",
|
||||
nextRunAt: null,
|
||||
};
|
||||
}
|
||||
if (triggers.some((trigger) => trigger.kind === "heartbeat" && trigger.enabled)) {
|
||||
return { label: "Standing check", detail: "Carried out on each of the agent's wake-ups", nextRunAt: null };
|
||||
}
|
||||
return { label: "No active schedule", detail: "Manual runs only", nextRunAt: null };
|
||||
}
|
||||
|
||||
const first = schedules[0]!;
|
||||
return {
|
||||
label: schedules.length === 1 ? "1 active schedule" : `${schedules.length} active schedules`,
|
||||
detail: first.cronExpression
|
||||
? `${first.cronExpression}${first.timezone ? ` · ${first.timezone}` : ""}`
|
||||
: first.label ?? "Scheduled trigger",
|
||||
nextRunAt,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeIssueStatus(value: string): IssueStatus {
|
||||
return ISSUE_STATUSES.includes(value as IssueStatus) ? value as IssueStatus : "todo";
|
||||
}
|
||||
|
||||
function normalizeIssuePriority(value: string): IssuePriority {
|
||||
return ISSUE_PRIORITIES.includes(value as IssuePriority) ? value as IssuePriority : "medium";
|
||||
}
|
||||
|
||||
/** Display-only adapter for the canonical task row; run summaries intentionally carry compact task data. */
|
||||
export function routineRunIssue(
|
||||
summary: NonNullable<RoutineRunSummary["linkedIssue"]>,
|
||||
run: RoutineRunSummary,
|
||||
companyId: string,
|
||||
projectId: string | null,
|
||||
): Issue {
|
||||
return {
|
||||
...summary,
|
||||
companyId,
|
||||
projectId,
|
||||
projectWorkspaceId: null,
|
||||
goalId: null,
|
||||
parentId: null,
|
||||
description: null,
|
||||
status: normalizeIssueStatus(summary.status),
|
||||
workMode: "standard",
|
||||
priority: normalizeIssuePriority(summary.priority),
|
||||
reviewPolicy: null,
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
checkoutRunId: null,
|
||||
executionRunId: null,
|
||||
executionAgentNameKey: null,
|
||||
executionLockedAt: null,
|
||||
createdByAgentId: null,
|
||||
createdByUserId: null,
|
||||
responsibleUserId: null,
|
||||
issueNumber: null,
|
||||
originKind: "routine_execution",
|
||||
originId: run.routineId,
|
||||
originRunId: run.id,
|
||||
requestDepth: 0,
|
||||
billingCode: null,
|
||||
assigneeAdapterOverrides: null,
|
||||
executionWorkspaceId: null,
|
||||
executionWorkspacePreference: null,
|
||||
executionWorkspaceSettings: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
cancelledAt: null,
|
||||
hiddenAt: null,
|
||||
createdAt: run.triggeredAt,
|
||||
};
|
||||
}
|
||||
|
||||
function OverviewFact({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
detail,
|
||||
}: {
|
||||
icon: typeof Clock3;
|
||||
label: string;
|
||||
value: React.ReactNode;
|
||||
detail?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col gap-1 rounded-lg border border-border p-3">
|
||||
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Icon className="h-3.5 w-3.5" aria-hidden="true" />
|
||||
<span>{label}</span>
|
||||
</div>
|
||||
<div className="min-w-0 text-sm font-medium text-foreground">{value}</div>
|
||||
{detail ? <div className="min-w-0 text-xs text-muted-foreground">{detail}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function RoutineOverview() {
|
||||
const { routine, routineRuns, currentAssignee, hasLiveRun } = useRoutineDetail();
|
||||
const schedule = summarizeRoutineSchedule(routine.triggers);
|
||||
const hasWebhook = routine.triggers.some((trigger) => trigger.kind === "webhook" && trigger.enabled);
|
||||
const sortedRuns = [...(routineRuns ?? [])].sort(
|
||||
(left, right) => new Date(right.triggeredAt).getTime() - new Date(left.triggeredAt).getTime(),
|
||||
);
|
||||
const lastRun = sortedRuns[0] ?? null;
|
||||
const recentRuns = sortedRuns.slice(0, 5);
|
||||
const detailOrigin = createIssueDetailLocationState(
|
||||
routine.title,
|
||||
routineDetailHref(routine.id),
|
||||
"issues",
|
||||
);
|
||||
const automationState = routine.status === "archived"
|
||||
? "archived"
|
||||
: !routine.assigneeAgentId
|
||||
? "draft"
|
||||
: routine.status;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6" data-routine-overview-mode="read">
|
||||
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<OverviewFact
|
||||
icon={Repeat}
|
||||
label="State"
|
||||
value={<StatusBadge status={automationState} />}
|
||||
detail={hasLiveRun ? "A run is active now" : "No active run"}
|
||||
/>
|
||||
<OverviewFact
|
||||
icon={CalendarClock}
|
||||
label="Triggers"
|
||||
value={schedule.label}
|
||||
detail={<span className="font-mono">{schedule.detail}</span>}
|
||||
/>
|
||||
<OverviewFact
|
||||
icon={Clock3}
|
||||
label="Next run"
|
||||
value={schedule.nextRunAt ? formatRoutineTimestamp(schedule.nextRunAt) : hasWebhook ? "On webhook delivery" : "Not scheduled"}
|
||||
detail={schedule.nextRunAt ? "Scheduled" : hasWebhook ? "Waiting for an incoming request" : "Add or enable a schedule"}
|
||||
/>
|
||||
<OverviewFact
|
||||
icon={Play}
|
||||
label="Last run"
|
||||
value={lastRun ? <StatusBadge status={lastRun.status} /> : "No runs yet"}
|
||||
detail={lastRun ? formatRoutineTimestamp(lastRun.triggeredAt) : "Run manually or wait for a trigger"}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 sm:grid-cols-2">
|
||||
<section className="flex flex-col gap-2" aria-labelledby="routine-agent-heading">
|
||||
<h2 id="routine-agent-heading" className="text-sm font-semibold">Default agent</h2>
|
||||
{currentAssignee ? (
|
||||
<Link
|
||||
to={`/agents/${currentAssignee.urlKey ?? currentAssignee.id}`}
|
||||
className="flex w-fit items-center gap-2 rounded-md text-sm font-medium hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<UserRound className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
|
||||
{currentAssignee.name}
|
||||
</Link>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">No default agent. Automatic triggers remain paused.</p>
|
||||
)}
|
||||
</section>
|
||||
<RoutineResponsibleUser key={routine.id} routine={routine} />
|
||||
</div>
|
||||
|
||||
<section className="flex flex-col gap-2" aria-labelledby="routine-description-heading">
|
||||
<h2 id="routine-description-heading" className="text-sm font-semibold">Description</h2>
|
||||
{routine.description?.trim() ? (
|
||||
<MarkdownBody className="text-sm text-foreground" linkIssueReferences>
|
||||
{routine.description}
|
||||
</MarkdownBody>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">No description yet.</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="flex flex-col gap-2" aria-labelledby="routine-recent-runs-heading">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 id="routine-recent-runs-heading" className="text-sm font-semibold">Recent runs</h2>
|
||||
<Button variant="ghost" size="sm" asChild>
|
||||
<Link to={routineDetailHref(routine.id, "runs")}>View all runs</Link>
|
||||
</Button>
|
||||
</div>
|
||||
{recentRuns.length === 0 ? (
|
||||
<p className="py-6 text-center text-sm text-muted-foreground">
|
||||
No runs yet. Run the routine now or wait for its schedule.
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{recentRuns.map((run) => run.linkedIssue ? (
|
||||
<IssueRow
|
||||
key={run.id}
|
||||
issue={routineRunIssue(run.linkedIssue, run, routine.companyId, routine.projectId)}
|
||||
issueLinkState={detailOrigin}
|
||||
presentation="task"
|
||||
metadata={(
|
||||
<span className="flex items-center gap-2">
|
||||
<StatusBadge status={run.status} />
|
||||
<span className="font-mono text-xs text-muted-foreground">{formatRoutineTimestamp(run.triggeredAt)}</span>
|
||||
</span>
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<div key={run.id} className="flex min-w-0 items-center gap-2 rounded-lg px-2 py-2 text-sm">
|
||||
<StatusBadge status={run.status} />
|
||||
<span className="min-w-0 flex-1 truncate">{run.trigger?.label ?? "Routine run"}</span>
|
||||
<span className="shrink-0 font-mono text-xs text-muted-foreground">{formatRoutineTimestamp(run.triggeredAt)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<Button variant="link" size="sm" className="w-fit px-0" asChild>
|
||||
<Link to={routineDetailHref(routine.id, "activity")}>View routine activity</Link>
|
||||
</Button>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
|
||||
import type { RoutineDetail } from "@paperclipai/shared";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { accessApi } from "@/api/access";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { routinesApi } from "@/api/routines";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { RoutineResponsibleUser } from "./RoutineResponsibleUser";
|
||||
|
||||
const routine = {
|
||||
id: "routine-1", companyId: "company-1", responsibleUserId: "user-alex",
|
||||
latestRevisionId: "revision-1", canChangeResponsibleUser: true,
|
||||
} as RoutineDetail;
|
||||
const users = ["Alex", "Sam"].map((name) => ({
|
||||
principalId: `user-${name.toLowerCase()}`, status: "active" as const, membershipRole: "member" as const,
|
||||
user: { id: `user-${name.toLowerCase()}`, name, email: `${name.toLowerCase()}@example.test`, image: null },
|
||||
}));
|
||||
|
||||
describe("RoutineResponsibleUser", () => {
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
let client: QueryClient;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} });
|
||||
HTMLElement.prototype.scrollIntoView = vi.fn();
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
||||
vi.spyOn(accessApi, "listUserDirectory").mockResolvedValue({ users });
|
||||
vi.spyOn(routinesApi, "update").mockResolvedValue({ ...routine, responsibleUserId: "user-sam" });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
client.clear();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
async function render(value = routine) {
|
||||
await act(async () => root.render(<QueryClientProvider client={client}><RoutineResponsibleUser routine={value} /></QueryClientProvider>));
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); });
|
||||
}
|
||||
|
||||
async function selectSam() {
|
||||
await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());
|
||||
const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find((item) => item.textContent?.includes("Sam"));
|
||||
expect(option).toBeDefined();
|
||||
await act(async () => option!.click());
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); });
|
||||
}
|
||||
|
||||
it("shows the person and inheritance rules to read-only viewers", async () => {
|
||||
await render({ ...routine, canChangeResponsibleUser: false });
|
||||
expect(container.textContent).toContain("Alex");
|
||||
expect(container.textContent).toContain("Automatic tasks use this person. Manual runs use the person who starts them.");
|
||||
expect(container.querySelector("button")).toBeNull();
|
||||
});
|
||||
|
||||
it("saves only responsibility and its base revision, then refreshes routine data", async () => {
|
||||
const invalidate = vi.spyOn(client, "invalidateQueries");
|
||||
await render();
|
||||
await selectSam();
|
||||
expect(routinesApi.update).toHaveBeenCalledWith("routine-1", { responsibleUserId: "user-sam", baseRevisionId: "revision-1" });
|
||||
expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.routines.detail("routine-1") });
|
||||
expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.routines.revisions("routine-1") });
|
||||
expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.routines.activity("company-1", "routine-1") });
|
||||
expect(document.querySelector('[role="option"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the picker disabled until the saved detail is refreshed, then uses the new revision", async () => {
|
||||
let resolveRefresh!: (value: RoutineDetail) => void;
|
||||
const refresh = new Promise<RoutineDetail>((resolve) => { resolveRefresh = resolve; });
|
||||
const saved = { ...routine, responsibleUserId: "user-sam", latestRevisionId: "revision-2" };
|
||||
vi.mocked(routinesApi.update).mockResolvedValue(saved);
|
||||
function Detail() {
|
||||
const detail = useQuery({
|
||||
queryKey: queryKeys.routines.detail(routine.id),
|
||||
queryFn: () => refresh,
|
||||
initialData: routine,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
return <RoutineResponsibleUser routine={detail.data} />;
|
||||
}
|
||||
await act(async () => root.render(<QueryClientProvider client={client}><Detail /></QueryClientProvider>));
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); });
|
||||
await selectSam();
|
||||
expect(container.querySelector<HTMLButtonElement>("button")?.disabled).toBe(true);
|
||||
expect(container.textContent).toContain("Saving…");
|
||||
await act(async () => resolveRefresh(saved));
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); });
|
||||
expect(container.querySelector<HTMLButtonElement>("button")?.disabled).toBe(false);
|
||||
expect(container.textContent).toContain("Sam");
|
||||
await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());
|
||||
const alex = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find((item) => item.textContent?.includes("Alex"));
|
||||
await act(async () => alex!.click());
|
||||
expect(routinesApi.update).toHaveBeenLastCalledWith(routine.id, { responsibleUserId: "user-alex", baseRevisionId: "revision-2" });
|
||||
});
|
||||
|
||||
it("does not save when the current person is selected", async () => {
|
||||
await render();
|
||||
await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());
|
||||
const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find((item) => item.textContent?.includes("Alex"));
|
||||
await act(async () => option!.click());
|
||||
expect(routinesApi.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([403, 409])("keeps the saved person and shows the %s failure", async (status) => {
|
||||
vi.mocked(routinesApi.update).mockRejectedValue(new ApiError("Missing permission: tasks:assign", status, null));
|
||||
await render();
|
||||
await selectSam();
|
||||
expect(container.textContent).toContain("Alex");
|
||||
expect(container.querySelector('[role="alert"]')?.textContent).toContain(status === 409 ? "Reload before changing responsibility" : "Missing permission");
|
||||
});
|
||||
|
||||
it("shows an unavailable person without inventing a name and permits repair", async () => {
|
||||
await render({ ...routine, responsibleUserId: "former-user" });
|
||||
expect(container.textContent).toContain("Unavailable user");
|
||||
await selectSam();
|
||||
expect(routinesApi.update).toHaveBeenCalledWith(routine.id, expect.objectContaining({ responsibleUserId: "user-sam" }));
|
||||
});
|
||||
|
||||
it("disables the picker and explains a directory failure", async () => {
|
||||
vi.mocked(accessApi.listUserDirectory).mockRejectedValue(new Error("Unavailable"));
|
||||
await render();
|
||||
expect(container.querySelector<HTMLButtonElement>("button")?.disabled).toBe(true);
|
||||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("Unavailable");
|
||||
expect(container.textContent).toContain("Retry");
|
||||
});
|
||||
|
||||
it("keeps a cached person visible without a local alert during a transient directory failure", async () => {
|
||||
await render();
|
||||
vi.mocked(accessApi.listUserDirectory).mockRejectedValue(new ApiError("tenant_app_unavailable", 503, { error: "tenant_app_unavailable" }));
|
||||
await act(async () => client.invalidateQueries({ queryKey: queryKeys.access.companyUserDirectory(routine.companyId) }));
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); });
|
||||
expect(container.textContent).toContain("Alex");
|
||||
expect(container.querySelector<HTMLButtonElement>("button")?.disabled).toBe(false);
|
||||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,105 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { RoutineDetail } from "@paperclipai/shared";
|
||||
import { Check, ChevronDown, UserRound } from "lucide-react";
|
||||
import { accessApi } from "@/api/access";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { describeError } from "@/api/errors";
|
||||
import { routinesApi } from "@/api/routines";
|
||||
import { buildCompanyUserProfileMap } from "@/lib/company-members";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { Command, CommandEmpty, CommandInput, CommandItem, CommandList } from "./ui/command";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
|
||||
import { QueryErrorState, useQueryView } from "./QueryView";
|
||||
|
||||
export function RoutineResponsibleUser({ routine }: { routine: RoutineDetail }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const queryClient = useQueryClient();
|
||||
const directory = useQuery({
|
||||
queryKey: queryKeys.access.companyUserDirectory(routine.companyId),
|
||||
queryFn: () => accessApi.listUserDirectory(routine.companyId),
|
||||
});
|
||||
const directoryView = useQueryView(directory);
|
||||
const profiles = buildCompanyUserProfileMap(directory.data?.users);
|
||||
const label = routine.responsibleUserId
|
||||
? profiles.get(routine.responsibleUserId)?.label
|
||||
?? (directory.isPending ? "Loading…" : "Unavailable user")
|
||||
: "No responsible user";
|
||||
const change = useMutation({
|
||||
mutationFn: (responsibleUserId: string) => routinesApi.update(routine.id, {
|
||||
responsibleUserId,
|
||||
baseRevisionId: routine.latestRevisionId,
|
||||
}),
|
||||
onSuccess: async (saved) => {
|
||||
queryClient.setQueryData<RoutineDetail>(queryKeys.routines.detail(routine.id), (current) => (
|
||||
current ? { ...current, ...saved } : current
|
||||
));
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.routines.detail(routine.id) }),
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(routine.companyId) }),
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.routines.revisions(routine.id) }),
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.routines.activity(routine.companyId, routine.id) }),
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<section className="flex min-w-0 flex-col gap-2" aria-labelledby="routine-responsible-heading">
|
||||
<h2 id="routine-responsible-heading" className="text-sm font-semibold">Responsible user</h2>
|
||||
{routine.canChangeResponsibleUser ? (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Change responsible user: ${label}`}
|
||||
disabled={change.isPending || !directory.data}
|
||||
className="group flex w-fit max-w-full items-center gap-2 rounded-md text-left text-sm font-medium hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"
|
||||
>
|
||||
<UserRound className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
|
||||
<span className="truncate">{change.isPending ? "Saving…" : label}</span>
|
||||
<ChevronDown className="h-3.5 w-3.5 shrink-0 text-muted-foreground opacity-60 group-hover:opacity-100 group-focus-visible:opacity-100" aria-hidden="true" />
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="start" className="w-72 p-0">
|
||||
<Command>
|
||||
<CommandInput placeholder="Find a person…" aria-label="Find a responsible user" />
|
||||
<CommandList aria-label="Responsible user">
|
||||
<CommandEmpty>No people found.</CommandEmpty>
|
||||
{(directory.data?.users ?? []).map((member) => (
|
||||
<CommandItem
|
||||
key={member.principalId}
|
||||
value={`${member.principalId} ${profiles.get(member.principalId)?.label} ${member.user?.email ?? ""}`}
|
||||
onSelect={() => {
|
||||
setOpen(false);
|
||||
if (member.principalId !== routine.responsibleUserId) change.mutate(member.principalId);
|
||||
}}
|
||||
>
|
||||
<UserRound className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
|
||||
<span className="min-w-0 flex-1 truncate">{profiles.get(member.principalId)?.label}</span>
|
||||
{member.principalId === routine.responsibleUserId ? <Check className="h-4 w-4" aria-label="Current responsible user" /> : null}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
) : (
|
||||
<p className="flex items-center gap-2 text-sm font-medium">
|
||||
<UserRound className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
|
||||
<span className="truncate">{label}</span>
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">Automatic tasks use this person. Manual runs use the person who starts them.</p>
|
||||
{directoryView.kind === "error" ? (
|
||||
<QueryErrorState error={directoryView.error} size="inline" action="load people" onRetry={directoryView.retry} retrying={directoryView.isFetching} />
|
||||
) : null}
|
||||
{change.error ? (
|
||||
<p role="alert" className="text-xs text-destructive">
|
||||
{change.error instanceof ApiError && change.error.status === 409
|
||||
? "This routine changed. Reload before changing responsibility."
|
||||
: describeError(change.error, { action: "change responsibility" }).body}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import type React from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { RoutineSaveBar } from "./RoutineSaveBar";
|
||||
import type { RoutineHistoryDirtyFieldDescriptor } from "./RoutineHistoryTab";
|
||||
|
||||
function act(callback: () => void) {
|
||||
flushSync(callback);
|
||||
}
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let root: ReturnType<typeof createRoot>;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const DIRTY: RoutineHistoryDirtyFieldDescriptor[] = [
|
||||
{ key: "title", label: "the title" },
|
||||
{ key: "description", label: "the description" },
|
||||
];
|
||||
|
||||
function renderBar(props: Partial<React.ComponentProps<typeof RoutineSaveBar>>) {
|
||||
const handlers = {
|
||||
onSave: vi.fn(),
|
||||
onDiscard: vi.fn(),
|
||||
onReload: vi.fn(),
|
||||
};
|
||||
act(() => {
|
||||
root.render(
|
||||
<RoutineSaveBar
|
||||
dirtyFields={props.dirtyFields ?? []}
|
||||
isSaving={props.isSaving ?? false}
|
||||
saveConflict={props.saveConflict ?? false}
|
||||
onSave={props.onSave ?? handlers.onSave}
|
||||
onDiscard={props.onDiscard ?? handlers.onDiscard}
|
||||
onReload={props.onReload ?? handlers.onReload}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
return handlers;
|
||||
}
|
||||
|
||||
describe("RoutineSaveBar", () => {
|
||||
it("renders nothing when clean and no conflict", () => {
|
||||
renderBar({ dirtyFields: [] });
|
||||
expect(container.textContent).toBe("");
|
||||
});
|
||||
|
||||
it("shows the unsaved change count when dirty", () => {
|
||||
renderBar({ dirtyFields: DIRTY });
|
||||
expect(container.textContent).toContain("2 unsaved changes");
|
||||
});
|
||||
|
||||
it("invokes onSave on Cmd/Ctrl+S while dirty", () => {
|
||||
const handlers = renderBar({ dirtyFields: DIRTY });
|
||||
act(() => {
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", { key: "s", metaKey: true }));
|
||||
});
|
||||
expect(handlers.onSave).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not invoke onSave on Cmd+S when clean", () => {
|
||||
const handlers = renderBar({ dirtyFields: [] });
|
||||
act(() => {
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", { key: "s", metaKey: true }));
|
||||
});
|
||||
expect(handlers.onSave).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("surfaces the conflict recovery actions on saveConflict", () => {
|
||||
const handlers = renderBar({ dirtyFields: DIRTY, saveConflict: true });
|
||||
expect(container.textContent).toContain("Routine changed elsewhere");
|
||||
const buttons = Array.from(container.querySelectorAll("button"));
|
||||
const reload = buttons.find((button) => button.textContent?.includes("Reload latest"));
|
||||
const overwrite = buttons.find((button) => button.textContent?.includes("Overwrite anyway"));
|
||||
expect(reload).toBeTruthy();
|
||||
expect(overwrite).toBeTruthy();
|
||||
act(() => {
|
||||
reload!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
expect(handlers.onReload).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -1,203 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { AlertTriangle, Loader2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { RoutineHistoryDirtyFieldDescriptor } from "./RoutineHistoryTab";
|
||||
|
||||
/**
|
||||
* Per-section sticky save bar (§1.4–§1.5). Hidden when clean; reveals on dirty.
|
||||
* On a 409 it swaps to the conflict-recovery surface ("Reload latest" /
|
||||
* "Overwrite anyway"). Wires ⌘/Ctrl+S → save and Esc → discard-with-confirm.
|
||||
*/
|
||||
export function RoutineSaveBar({
|
||||
dirtyFields,
|
||||
isSaving,
|
||||
saveConflict,
|
||||
onSave,
|
||||
onDiscard,
|
||||
onReload,
|
||||
disabled,
|
||||
}: {
|
||||
dirtyFields: RoutineHistoryDirtyFieldDescriptor[];
|
||||
isSaving: boolean;
|
||||
saveConflict: boolean;
|
||||
onSave: () => void;
|
||||
onDiscard: () => void;
|
||||
onReload: () => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const dirtyCount = dirtyFields.length;
|
||||
const isDirty = dirtyCount > 0;
|
||||
const [confirmDiscardOpen, setConfirmDiscardOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDirty && !saveConflict) return;
|
||||
const handler = (event: KeyboardEvent) => {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "s") {
|
||||
event.preventDefault();
|
||||
if (!isSaving && !disabled) onSave();
|
||||
} else if (event.key === "Escape" && isDirty) {
|
||||
event.preventDefault();
|
||||
setConfirmDiscardOpen(true);
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [isDirty, saveConflict, isSaving, disabled, onSave]);
|
||||
|
||||
if (!isDirty && !saveConflict) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={cn(
|
||||
"sticky bottom-0 z-10 -mx-8 mt-6 flex h-14 items-center justify-between border-t px-8 backdrop-blur",
|
||||
"motion-safe:transition-colors motion-safe:duration-200",
|
||||
"motion-safe:animate-in motion-safe:fade-in motion-safe:slide-in-from-bottom-2",
|
||||
saveConflict
|
||||
? "border-amber-500/30 bg-amber-500/5"
|
||||
: "border-border bg-background/95",
|
||||
)}
|
||||
>
|
||||
{saveConflict ? (
|
||||
<div className="flex items-center gap-2 text-sm text-amber-800 dark:text-amber-200">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<span>Routine changed elsewhere. Reload to merge.</span>
|
||||
</div>
|
||||
) : (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center gap-2 text-sm text-foreground hover:text-foreground"
|
||||
>
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-amber-500" />
|
||||
<span className="font-medium">
|
||||
{dirtyCount} unsaved {dirtyCount === 1 ? "change" : "changes"}
|
||||
</span>
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="start" className="w-64">
|
||||
<p className="mb-2 text-xs font-medium text-muted-foreground">
|
||||
Pending changes
|
||||
</p>
|
||||
<ul className="space-y-1 text-sm">
|
||||
{dirtyFields.map((field) => (
|
||||
<li key={field.key} className="flex items-center gap-2">
|
||||
<span className="h-1 w-1 rounded-full bg-amber-500" />
|
||||
<span className="capitalize">{field.label}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{saveConflict ? (
|
||||
<>
|
||||
<Button variant="outline" size="sm" onClick={onReload}>
|
||||
Reload latest
|
||||
</Button>
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
disabled={isSaving || disabled}
|
||||
onClick={onSave}
|
||||
>
|
||||
{isSaving ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : null}
|
||||
Overwrite anyway
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
Replaces the newer revision with your local edits.
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={isSaving || disabled}
|
||||
onClick={() => setConfirmDiscardOpen(true)}
|
||||
>
|
||||
Discard
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={isSaving || disabled}
|
||||
onClick={onSave}
|
||||
>
|
||||
{isSaving ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : null}
|
||||
Save changes
|
||||
<kbd className="ml-2 hidden rounded bg-foreground/10 px-1 text-(length:--text-nano) font-medium sm:inline">
|
||||
⌘S
|
||||
</kbd>
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Dialog open={confirmDiscardOpen} onOpenChange={setConfirmDiscardOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Discard changes?</DialogTitle>
|
||||
<DialogDescription>
|
||||
This will revert {dirtyCount} unsaved{" "}
|
||||
{dirtyCount === 1 ? "change" : "changes"} in this section.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" size="sm" onClick={() => setConfirmDiscardOpen(false)}>
|
||||
Keep editing
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
onDiscard();
|
||||
setConfirmDiscardOpen(false);
|
||||
}}
|
||||
>
|
||||
Discard changes
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Read-only strip for non-owners on editable sections (§1.6). */
|
||||
export function RoutineReadOnlyStrip() {
|
||||
return (
|
||||
<div className="-mx-8 mt-6 border-t border-border bg-muted/20 px-8 py-3 text-xs text-muted-foreground">
|
||||
Read-only — you don't own this routine.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { RoutineSectionHeading } from "./RoutineSectionHeading";
|
||||
|
||||
const copyTextToClipboard = vi.hoisted(() => vi.fn(async () => {}));
|
||||
|
||||
vi.mock("@/lib/clipboard", () => ({
|
||||
copyTextToClipboard,
|
||||
}));
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
async function act(callback: () => void | Promise<void>) {
|
||||
let result: void | Promise<void> = undefined;
|
||||
flushSync(() => {
|
||||
result = callback();
|
||||
});
|
||||
await result;
|
||||
}
|
||||
|
||||
describe("RoutineSectionHeading", () => {
|
||||
let container: HTMLDivElement;
|
||||
|
||||
afterEach(() => {
|
||||
container?.remove();
|
||||
copyTextToClipboard.mockClear();
|
||||
});
|
||||
|
||||
it("copies the description markdown from the button next to the heading", async () => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const description = "```text\n- keep this line\n```";
|
||||
|
||||
await act(async () => {
|
||||
root.render(<RoutineSectionHeading title="Overview" copyText={description} />);
|
||||
});
|
||||
|
||||
const button = container.querySelector('button[aria-label="Copy description"]');
|
||||
expect(button).not.toBeNull();
|
||||
expect(container.querySelector("#routine-section-title")?.textContent).toBe("Overview");
|
||||
|
||||
await act(async () => {
|
||||
button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(copyTextToClipboard).toHaveBeenCalledWith(description);
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("omits the copy button on sections that are not the overview", async () => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root.render(<RoutineSectionHeading title="Triggers" />);
|
||||
});
|
||||
|
||||
expect(container.querySelector('button[aria-label="Copy description"]')).toBeNull();
|
||||
expect(container.querySelector("#routine-section-title")?.textContent).toBe("Triggers");
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,30 +0,0 @@
|
||||
import { Copy } from "lucide-react";
|
||||
import { CopyText } from "./CopyText";
|
||||
|
||||
export function RoutineSectionHeading({
|
||||
title,
|
||||
copyText = null,
|
||||
}: {
|
||||
title: string;
|
||||
/** Description markdown to copy. Omit the button when this is null. */
|
||||
copyText?: string | null;
|
||||
}) {
|
||||
return (
|
||||
<div className="mb-4 flex items-center gap-1">
|
||||
<h2 id="routine-section-title" className="text-lg font-semibold">
|
||||
{title}
|
||||
</h2>
|
||||
{copyText != null ? (
|
||||
<CopyText
|
||||
text={copyText}
|
||||
ariaLabel="Copy description"
|
||||
title="Copy description"
|
||||
copiedLabel="Description copied"
|
||||
className="inline-flex size-6 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
<Copy className="size-3.5" aria-hidden="true" />
|
||||
</CopyText>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import type { AnchorHTMLAttributes, ReactNode } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/lib/router", () => ({
|
||||
Link: ({
|
||||
to,
|
||||
children,
|
||||
...props
|
||||
}: AnchorHTMLAttributes<HTMLAnchorElement> & { to: string; children: ReactNode; replace?: boolean }) => {
|
||||
const { replace: _replace, ...rest } = props as Record<string, unknown>;
|
||||
return (
|
||||
<a href={to} {...(rest as AnchorHTMLAttributes<HTMLAnchorElement>)}>
|
||||
{children}
|
||||
</a>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
import { RoutineSubSidebar } from "./RoutineSubSidebar";
|
||||
import type { RoutineSectionKey } from "./routine-sections/context";
|
||||
|
||||
function act(callback: () => void) {
|
||||
flushSync(callback);
|
||||
}
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let root: ReturnType<typeof createRoot>;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
function renderSidebar(overrides?: {
|
||||
activeSection?: RoutineSectionKey;
|
||||
dirty?: RoutineSectionKey[];
|
||||
hasLiveRun?: boolean;
|
||||
onNavigate?: (section: RoutineSectionKey) => void;
|
||||
}) {
|
||||
const dirty = new Set(overrides?.dirty ?? []);
|
||||
const onNavigate = overrides?.onNavigate ?? vi.fn();
|
||||
act(() => {
|
||||
root.render(
|
||||
<RoutineSubSidebar
|
||||
activeSection={overrides?.activeSection ?? "overview"}
|
||||
hrefFor={(section) => `/routines/r1/${section}`}
|
||||
isSectionDirty={(section) => dirty.has(section)}
|
||||
hasLiveRun={overrides?.hasLiveRun ?? false}
|
||||
onNavigate={onNavigate}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
return { onNavigate };
|
||||
}
|
||||
|
||||
describe("RoutineSubSidebar", () => {
|
||||
it("renders all eight sections grouped under ROUTINE and OPERATE", () => {
|
||||
renderSidebar();
|
||||
const links = Array.from(container.querySelectorAll("a"));
|
||||
const labels = links.map((link) => link.textContent?.trim());
|
||||
expect(labels).toEqual([
|
||||
"Overview",
|
||||
"Triggers",
|
||||
"Variables",
|
||||
"Secrets",
|
||||
"Delivery",
|
||||
"Runs",
|
||||
"Activity",
|
||||
"History",
|
||||
]);
|
||||
const groupLabels = Array.from(container.querySelectorAll("p")).map((p) => p.textContent);
|
||||
expect(groupLabels).toContain("Routine");
|
||||
expect(groupLabels).toContain("Operate");
|
||||
});
|
||||
|
||||
it("marks the active section with aria-current=page", () => {
|
||||
renderSidebar({ activeSection: "secrets" });
|
||||
const active = container.querySelector('a[aria-current="page"]');
|
||||
expect(active?.textContent?.trim()).toBe("Secrets");
|
||||
});
|
||||
|
||||
it("links each section to its section URL", () => {
|
||||
renderSidebar();
|
||||
const variables = Array.from(container.querySelectorAll("a")).find(
|
||||
(link) => link.textContent?.trim() === "Variables",
|
||||
);
|
||||
expect(variables?.getAttribute("href")).toBe("/routines/r1/variables");
|
||||
});
|
||||
|
||||
it("shows a dirty marker only on dirty editable sections", () => {
|
||||
renderSidebar({ dirty: ["overview", "delivery"] });
|
||||
const dirtyMarkers = container.querySelectorAll('[aria-label="Unsaved changes"]');
|
||||
expect(dirtyMarkers.length).toBe(2);
|
||||
});
|
||||
|
||||
it("fires onNavigate when a section is clicked", () => {
|
||||
const { onNavigate } = renderSidebar();
|
||||
const triggers = Array.from(container.querySelectorAll("a")).find(
|
||||
(link) => link.textContent?.trim() === "Triggers",
|
||||
) as HTMLAnchorElement;
|
||||
act(() => {
|
||||
triggers.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
expect(onNavigate).toHaveBeenCalledWith("triggers");
|
||||
});
|
||||
});
|
||||
@@ -1,216 +0,0 @@
|
||||
import { useRef } from "react";
|
||||
import {
|
||||
Activity as ActivityIcon,
|
||||
Circle,
|
||||
Clock3,
|
||||
History as HistoryIcon,
|
||||
KeyRound,
|
||||
LayoutGrid,
|
||||
Play,
|
||||
Send,
|
||||
SlidersHorizontal,
|
||||
} from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { Link } from "@/lib/router";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
ROUTINE_SECTION_KEYS,
|
||||
type RoutineSectionKey,
|
||||
} from "./routine-sections/context";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
|
||||
type NavItem = {
|
||||
key: RoutineSectionKey;
|
||||
label: string;
|
||||
icon: LucideIcon;
|
||||
};
|
||||
|
||||
type NavGroup = {
|
||||
label: string;
|
||||
items: NavItem[];
|
||||
};
|
||||
|
||||
const NAV_GROUPS: NavGroup[] = [
|
||||
{
|
||||
label: "Routine",
|
||||
items: [
|
||||
{ key: "overview", label: "Overview", icon: Circle },
|
||||
{ key: "triggers", label: "Triggers", icon: Clock3 },
|
||||
{ key: "variables", label: "Variables", icon: LayoutGrid },
|
||||
{ key: "secrets", label: "Secrets", icon: KeyRound },
|
||||
{ key: "delivery", label: "Delivery", icon: Send },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Operate",
|
||||
items: [
|
||||
{ key: "runs", label: "Runs", icon: Play },
|
||||
{ key: "activity", label: "Activity", icon: ActivityIcon },
|
||||
{ key: "history", label: "History", icon: HistoryIcon },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const ALL_ITEMS: NavItem[] = NAV_GROUPS.flatMap((group) => group.items);
|
||||
|
||||
export function RoutineSubSidebar({
|
||||
activeSection,
|
||||
hrefFor,
|
||||
isSectionDirty,
|
||||
hasLiveRun,
|
||||
onNavigate,
|
||||
}: {
|
||||
activeSection: RoutineSectionKey;
|
||||
hrefFor: (section: RoutineSectionKey) => string;
|
||||
isSectionDirty: (section: RoutineSectionKey) => boolean;
|
||||
hasLiveRun: boolean;
|
||||
onNavigate: (section: RoutineSectionKey) => void;
|
||||
}) {
|
||||
const itemRefs = useRef<Array<HTMLAnchorElement | null>>([]);
|
||||
|
||||
const focusItem = (index: number) => {
|
||||
const clamped = (index + ALL_ITEMS.length) % ALL_ITEMS.length;
|
||||
itemRefs.current[clamped]?.focus();
|
||||
onNavigate(ALL_ITEMS[clamped].key);
|
||||
};
|
||||
|
||||
const handleKeyDown = (event: React.KeyboardEvent, index: number) => {
|
||||
switch (event.key) {
|
||||
case "ArrowDown":
|
||||
event.preventDefault();
|
||||
focusItem(index + 1);
|
||||
break;
|
||||
case "ArrowUp":
|
||||
event.preventDefault();
|
||||
focusItem(index - 1);
|
||||
break;
|
||||
case "Home":
|
||||
event.preventDefault();
|
||||
focusItem(0);
|
||||
break;
|
||||
case "End":
|
||||
event.preventDefault();
|
||||
focusItem(ALL_ITEMS.length - 1);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
let flatIndex = -1;
|
||||
|
||||
return (
|
||||
<nav
|
||||
aria-label="Routine sections"
|
||||
className="hidden h-full w-52 shrink-0 flex-col gap-4 overflow-y-auto border-r border-border bg-background px-3 py-4 md:flex"
|
||||
>
|
||||
{NAV_GROUPS.map((group) => (
|
||||
<div key={group.label} className="flex flex-col gap-0.5">
|
||||
<p className="mx-2 px-2 pb-1 text-(length:--text-nano) font-medium uppercase tracking-widest font-mono text-muted-foreground/60">
|
||||
{group.label}
|
||||
</p>
|
||||
{group.items.map((item) => {
|
||||
flatIndex += 1;
|
||||
const index = flatIndex;
|
||||
const isActive = item.key === activeSection;
|
||||
const Icon = item.icon;
|
||||
const dirty = isSectionDirty(item.key);
|
||||
const showLiveDot = item.key === "runs" && hasLiveRun;
|
||||
return (
|
||||
<Link
|
||||
key={item.key}
|
||||
ref={(node) => {
|
||||
itemRefs.current[index] = node;
|
||||
}}
|
||||
to={hrefFor(item.key)}
|
||||
replace
|
||||
role="tab"
|
||||
aria-current={isActive ? "page" : undefined}
|
||||
tabIndex={isActive ? 0 : -1}
|
||||
onKeyDown={(event) => handleKeyDown(event, index)}
|
||||
onClick={() => onNavigate(item.key)}
|
||||
className={cn(
|
||||
// Match the primary nav rows (SidebarNavItem): same rhythm,
|
||||
// inset pill, type scale, and icon size.
|
||||
"flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium transition-colors motion-safe:duration-150",
|
||||
isActive
|
||||
? "bg-accent text-foreground"
|
||||
: "text-foreground/80 hover:bg-accent/50 hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<Icon className="h-4 w-4 shrink-0" />
|
||||
<span className="truncate">{item.label}</span>
|
||||
{showLiveDot ? (
|
||||
<span className="ml-auto h-1.5 w-1.5 shrink-0 rounded-full bg-blue-500 motion-safe:animate-pulse" />
|
||||
) : dirty ? (
|
||||
<span
|
||||
aria-label="Unsaved changes"
|
||||
className="ml-auto h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500 ring-2 ring-background"
|
||||
/>
|
||||
) : null}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
/** Mobile section picker — collapses the sub-sidebar into a grouped `<Select>`. */
|
||||
export function RoutineSectionPicker({
|
||||
activeSection,
|
||||
onNavigate,
|
||||
isSectionDirty,
|
||||
}: {
|
||||
activeSection: RoutineSectionKey;
|
||||
onNavigate: (section: RoutineSectionKey) => void;
|
||||
isSectionDirty: (section: RoutineSectionKey) => boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className="sticky top-0 z-10 border-b border-border bg-background px-4 py-2 md:hidden">
|
||||
<Select
|
||||
value={activeSection}
|
||||
onValueChange={(value) => {
|
||||
if (ROUTINE_SECTION_KEYS.includes(value as RoutineSectionKey)) {
|
||||
onNavigate(value as RoutineSectionKey);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="h-11 w-full" aria-label="Routine section">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{NAV_GROUPS.map((group) => (
|
||||
<SelectGroup key={group.label}>
|
||||
<SelectLabel className="uppercase tracking-(--tracking-eyebrow) text-(length:--text-micro)">
|
||||
{group.label}
|
||||
</SelectLabel>
|
||||
{group.items.map((item) => (
|
||||
<SelectItem key={item.key} value={item.key} className="h-11">
|
||||
<span className="flex items-center gap-2">
|
||||
<item.icon className="h-3.5 w-3.5" />
|
||||
{item.label}
|
||||
{isSectionDirty(item.key) ? (
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-amber-500" />
|
||||
) : null}
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export { ALL_ITEMS as ROUTINE_NAV_ITEMS };
|
||||
@@ -1,207 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Clock3, Radar, RefreshCw, Save, Trash2, Webhook, Zap } from "lucide-react";
|
||||
import type { RoutineTrigger } from "@paperclipai/shared";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { ScheduleEditor } from "./ScheduleEditor";
|
||||
import { buildRoutineTriggerPatch } from "../lib/routine-trigger-patch";
|
||||
import { describeCron } from "../lib/cron-readable";
|
||||
|
||||
const signingModes = ["app_webhook", "bearer", "hmac_sha256", "github_hmac", "none"];
|
||||
const SIGNING_MODES_WITHOUT_REPLAY_WINDOW = new Set(["app_webhook", "bearer", "github_hmac", "fireflies_hmac", "none"]);
|
||||
|
||||
function getLocalTimezone(): string {
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
} catch {
|
||||
return "UTC";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Single trigger card with its own field-edit + save state (§3.2). Extracted
|
||||
* from the previous inline `TriggerEditor` in `RoutineDetail.tsx` — same logic.
|
||||
*/
|
||||
export function RoutineTriggerCard({
|
||||
trigger,
|
||||
onSave,
|
||||
onRotate,
|
||||
onDelete,
|
||||
disabled,
|
||||
}: {
|
||||
trigger: RoutineTrigger;
|
||||
onSave: (id: string, patch: Record<string, unknown>) => void;
|
||||
onRotate: (id: string) => void;
|
||||
onDelete: (id: string) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const [draft, setDraft] = useState({
|
||||
label: trigger.label ?? "",
|
||||
cronExpression: trigger.cronExpression ?? "",
|
||||
signingMode: trigger.signingMode ?? "bearer",
|
||||
replayWindowSec: String(trigger.replayWindowSec ?? 300),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
setDraft({
|
||||
label: trigger.label ?? "",
|
||||
cronExpression: trigger.cronExpression ?? "",
|
||||
signingMode: trigger.signingMode ?? "bearer",
|
||||
replayWindowSec: String(trigger.replayWindowSec ?? 300),
|
||||
});
|
||||
}, [trigger]);
|
||||
|
||||
const KindIcon =
|
||||
trigger.kind === "schedule" ? Clock3 : trigger.kind === "webhook" ? Webhook : trigger.kind === "heartbeat" ? Radar : Zap;
|
||||
const humanCron = trigger.kind === "schedule" ? describeCron(draft.cronExpression) : null;
|
||||
const lastResultFailed = /fail|error/i.test(trigger.lastResult ?? "");
|
||||
const lastResultLabel = trigger.lastResult?.startsWith("Created execution issue ")
|
||||
? "Task created"
|
||||
: trigger.lastResult;
|
||||
|
||||
return (
|
||||
<form
|
||||
aria-label={`Trigger: ${trigger.label ?? trigger.kind}`}
|
||||
className="space-y-4 rounded-lg border border-border p-4"
|
||||
onSubmit={(event) => event.preventDefault()}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<KindIcon className="h-3.5 w-3.5 shrink-0" />
|
||||
<span className="truncate">{trigger.label ?? trigger.kind}</span>
|
||||
</div>
|
||||
{humanCron ? (
|
||||
<p id={`cron-readable-${trigger.id}`} className="text-xs text-muted-foreground">
|
||||
{humanCron}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{trigger.lastResult ? (
|
||||
<Badge variant={lastResultFailed ? "destructive" : "secondary"}>
|
||||
{lastResultLabel}
|
||||
</Badge>
|
||||
) : null}
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{trigger.kind === "schedule" && trigger.nextRunAt
|
||||
? `Next: ${new Date(trigger.nextRunAt).toLocaleString()}`
|
||||
: trigger.kind === "webhook"
|
||||
? "Webhook"
|
||||
: trigger.kind === "heartbeat"
|
||||
? "Standing check"
|
||||
: "API"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{trigger.kind === "webhook" && trigger.webhookUrl && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={`webhook-url-${trigger.id}`} className="text-xs">Webhook URL</Label>
|
||||
<Input id={`webhook-url-${trigger.id}`} value={trigger.webhookUrl} readOnly onFocus={(event) => event.target.select()} />
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Send a POST request with Content-Type: application/json. Keep this URL private when signing is disabled.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">Label</Label>
|
||||
<Input
|
||||
value={draft.label}
|
||||
disabled={disabled}
|
||||
onChange={(event) => setDraft((current) => ({ ...current, label: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
{trigger.kind === "schedule" && (
|
||||
<div className="space-y-1.5 md:col-span-2">
|
||||
<Label className="text-xs">Schedule</Label>
|
||||
<ScheduleEditor
|
||||
value={draft.cronExpression}
|
||||
onChange={(cronExpression) =>
|
||||
setDraft((current) => ({ ...current, cronExpression }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{trigger.kind === "webhook" && (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">Signing mode</Label>
|
||||
<Select
|
||||
value={draft.signingMode}
|
||||
onValueChange={(signingMode) =>
|
||||
setDraft((current) => ({ ...current, signingMode }))
|
||||
}
|
||||
disabled={disabled}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{signingModes.map((mode) => (
|
||||
<SelectItem key={mode} value={mode}>
|
||||
{mode}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{!SIGNING_MODES_WITHOUT_REPLAY_WINDOW.has(draft.signingMode) && (
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">Replay window (seconds)</Label>
|
||||
<Input
|
||||
value={draft.replayWindowSec}
|
||||
disabled={disabled}
|
||||
onChange={(event) =>
|
||||
setDraft((current) => ({ ...current, replayWindowSec: event.target.value }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!disabled && (
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="mr-auto text-muted-foreground hover:text-destructive"
|
||||
onClick={() => onDelete(trigger.id)}
|
||||
>
|
||||
<Trash2 className="mr-1.5 h-3.5 w-3.5" />
|
||||
Delete
|
||||
</Button>
|
||||
{trigger.kind === "webhook" && (
|
||||
<Button variant="outline" size="sm" onClick={() => onRotate(trigger.id)}>
|
||||
<RefreshCw className="mr-1.5 h-3.5 w-3.5" />
|
||||
Rotate secret
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
onSave(trigger.id, buildRoutineTriggerPatch(trigger, draft, getLocalTimezone()))
|
||||
}
|
||||
>
|
||||
<Save className="mr-1.5 h-3.5 w-3.5" />
|
||||
Save trigger
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -55,11 +55,14 @@ export function RoutineVariablesEditor({
|
||||
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(
|
||||
@@ -79,6 +82,15 @@ export function RoutineVariablesEditor({
|
||||
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">
|
||||
@@ -249,6 +261,145 @@ export function RoutineVariablesEditor({
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@@ -195,10 +195,16 @@ export function ScheduleEditor({
|
||||
value,
|
||||
onChange,
|
||||
onValidityChange,
|
||||
inline = false,
|
||||
trailing,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (cron: string) => void;
|
||||
onValidityChange?: (valid: boolean) => void;
|
||||
/** Lay the frequency and its time controls out on one wrapping line. */
|
||||
inline?: boolean;
|
||||
/** Extra control placed after the time controls, such as a time zone picker. */
|
||||
trailing?: ReactNode;
|
||||
}) {
|
||||
const parsed = useMemo(() => parseCronToPreset(value), [value]);
|
||||
const [preset, setPreset] = useState<SchedulePreset>(parsed.preset);
|
||||
@@ -245,9 +251,9 @@ export function ScheduleEditor({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className={inline ? "flex flex-wrap items-center gap-2" : "space-y-3"}>
|
||||
<Select value={preset} onValueChange={(v) => handlePresetChange(v as SchedulePreset)}>
|
||||
<SelectTrigger className="w-full" aria-label="Schedule frequency">
|
||||
<SelectTrigger className={inline ? "w-36" : "w-full"} aria-label="Schedule frequency">
|
||||
<SelectValue placeholder="Choose frequency..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -260,7 +266,7 @@ export function ScheduleEditor({
|
||||
</Select>
|
||||
|
||||
{preset === "custom" ? (
|
||||
<div className="space-y-1.5">
|
||||
<div className={inline ? "min-w-48 flex-1 space-y-1.5" : "space-y-1.5"}>
|
||||
<Input
|
||||
value={customCron}
|
||||
onChange={(e) => {
|
||||
@@ -295,7 +301,7 @@ export function ScheduleEditor({
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className={inline ? "contents" : "flex flex-wrap items-center gap-2"}>
|
||||
{preset !== "every_minute" && preset !== "every_hour" && (
|
||||
<>
|
||||
<span className="text-sm text-muted-foreground">at</span>
|
||||
@@ -412,6 +418,7 @@ export function ScheduleEditor({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{trailing}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -200,7 +200,7 @@ export function EnvironmentVariableRow({
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"group/row grid grid-cols-(--gtc-13) items-start gap-x-1.5 gap-y-1 rounded-md px-1 py-1",
|
||||
"group/row -mx-1 grid grid-cols-(--gtc-13) items-start gap-x-1.5 gap-y-1 rounded-md px-1 py-1",
|
||||
"@[40rem]/env:grid-cols-(--gtc-14) @[40rem]/env:items-center",
|
||||
isDirty && "bg-amber-500/[0.06] ring-1 ring-amber-500/20",
|
||||
)}
|
||||
@@ -523,7 +523,7 @@ export function EnvironmentVariableRow({
|
||||
id={healthId}
|
||||
role="status"
|
||||
className={cn(
|
||||
"mt-0.5 text-(length:--text-micro)",
|
||||
"mt-1.5 text-(length:--text-micro)",
|
||||
health.level === "error" ? "text-destructive" : "text-amber-600 dark:text-amber-400",
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -137,6 +137,10 @@ export interface EnvironmentVariablesEditorProps {
|
||||
onDirtyChange?: (dirty: boolean) => void;
|
||||
/** Parent owns Save/Discard and flushes the editor through its ref. */
|
||||
hideDraftActions?: boolean;
|
||||
/** Open with one blank, focused row when there is nothing saved yet. */
|
||||
startWithEmptyRow?: boolean;
|
||||
/** Label for the add-row action. Defaults to "Add variable". */
|
||||
addLabel?: string;
|
||||
}
|
||||
|
||||
export interface EnvironmentVariablesEditorHandle {
|
||||
@@ -159,10 +163,15 @@ export const EnvironmentVariablesEditor = forwardRef<EnvironmentVariablesEditorH
|
||||
footerHint,
|
||||
onDirtyChange,
|
||||
hideDraftActions = false,
|
||||
startWithEmptyRow = false,
|
||||
addLabel = "Add variable",
|
||||
}: EnvironmentVariablesEditorProps, ref) {
|
||||
const toast = useOptionalToastActions();
|
||||
const editorRootRef = useRef<HTMLDivElement | null>(null);
|
||||
const [rows, setRows] = useState<EnvRow[]>(() => rowsFromValue(value));
|
||||
const [rows, setRows] = useState<EnvRow[]>(() => {
|
||||
const saved = rowsFromValue(value);
|
||||
return saved.length === 0 && startWithEmptyRow ? [emptyRow()] : saved;
|
||||
});
|
||||
const rowsRef = useRef(rows);
|
||||
const [committedRows, setCommittedRows] = useState<EnvRow[]>(() => cloneRows(rows));
|
||||
const initialValueKey = useMemo(() => normalizedEnvKey(value), []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
@@ -175,7 +184,9 @@ export const EnvironmentVariablesEditor = forwardRef<EnvironmentVariablesEditorH
|
||||
const [touchedNames, setTouchedNames] = useState<ReadonlySet<string>>(
|
||||
() => new Set(rowsFromValue(value).map((row) => row.name.trim()).filter(Boolean)),
|
||||
);
|
||||
const [pendingFocus, setPendingFocus] = useState<{ rowId: string; field: "name" | "value" } | null>(null);
|
||||
const [pendingFocus, setPendingFocus] = useState<{ rowId: string; field: "name" | "value" } | null>(
|
||||
() => (startWithEmptyRow && rows.length === 1 && !rows[0]!.name ? { rowId: rows[0]!.id, field: "name" } : null),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
rowsRef.current = rows;
|
||||
@@ -496,7 +507,7 @@ export const EnvironmentVariablesEditor = forwardRef<EnvironmentVariablesEditorH
|
||||
className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50"
|
||||
>
|
||||
<Plus className="size-3.5" />
|
||||
Add variable
|
||||
{addLabel}
|
||||
</button>
|
||||
|
||||
{quickBind.length > 0 && !disabled ? (
|
||||
|
||||
@@ -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=<signature>.
|
||||
</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 };
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
import { createContext, useContext } from "react";
|
||||
import type { UseMutationResult } from "@tanstack/react-query";
|
||||
import type {
|
||||
CompanySecret,
|
||||
RoutineDetail as RoutineDetailType,
|
||||
RoutineEnvConfig,
|
||||
RoutineVariable,
|
||||
} from "@paperclipai/shared";
|
||||
import type { MarkdownEditorRef, MentionOption } from "../MarkdownEditor";
|
||||
import type { InlineEntityOption } from "../InlineEntitySelector";
|
||||
import type { RoutineHistoryDirtyFieldDescriptor } from "../RoutineHistoryTab";
|
||||
import type { RoutineRunDialogSubmitData } from "../RoutineRunVariablesDialog";
|
||||
import type {
|
||||
RoutineTriggerResponse,
|
||||
RotateRoutineTriggerResponse,
|
||||
} from "../../api/routines";
|
||||
import type { agentsApi } from "../../api/agents";
|
||||
import type { projectsApi } from "../../api/projects";
|
||||
import type { secretsApi } from "../../api/secrets";
|
||||
|
||||
export const ROUTINE_SECTION_KEYS = [
|
||||
"overview",
|
||||
"triggers",
|
||||
"variables",
|
||||
"secrets",
|
||||
"delivery",
|
||||
"runs",
|
||||
"activity",
|
||||
"history",
|
||||
] as const;
|
||||
|
||||
export type RoutineSectionKey = (typeof ROUTINE_SECTION_KEYS)[number];
|
||||
|
||||
/** Editable sections own a save bar; read-only (operate) sections do not. */
|
||||
export const EDITABLE_SECTIONS: RoutineSectionKey[] = [
|
||||
"overview",
|
||||
"triggers",
|
||||
"variables",
|
||||
"secrets",
|
||||
"delivery",
|
||||
];
|
||||
|
||||
/** Which dirty-field keys belong to which section (for scoped save state). */
|
||||
export const SECTION_FIELD_KEYS: Record<string, string[]> = {
|
||||
overview: ["title", "description", "projectId", "assigneeAgentId", "priority"],
|
||||
variables: ["variables"],
|
||||
secrets: ["env"],
|
||||
delivery: ["concurrencyPolicy", "catchUpPolicy", "activityGatePolicy", "activityGateScope"],
|
||||
};
|
||||
|
||||
export type RoutineEditDraft = {
|
||||
title: string;
|
||||
description: string;
|
||||
projectId: string;
|
||||
assigneeAgentId: string;
|
||||
priority: string;
|
||||
concurrencyPolicy: string;
|
||||
catchUpPolicy: string;
|
||||
activityGatePolicy: string;
|
||||
activityGateScope: string;
|
||||
variables: RoutineVariable[];
|
||||
env: RoutineEnvConfig | null;
|
||||
};
|
||||
|
||||
export type NewTriggerDraft = {
|
||||
kind: string;
|
||||
cronExpression: string;
|
||||
signingMode: string;
|
||||
replayWindowSec: string;
|
||||
};
|
||||
|
||||
export function createDefaultNewTrigger(): NewTriggerDraft {
|
||||
return {
|
||||
kind: "schedule",
|
||||
cronExpression: "0 10 * * *",
|
||||
signingMode: "bearer",
|
||||
replayWindowSec: "300",
|
||||
};
|
||||
}
|
||||
|
||||
export type SecretMessage = {
|
||||
title: string;
|
||||
entries: Array<{ webhookUrl: string; webhookSecret: string }>;
|
||||
};
|
||||
|
||||
type AgentList = Awaited<ReturnType<typeof agentsApi.list>>;
|
||||
type ProjectList = Awaited<ReturnType<typeof projectsApi.list>>;
|
||||
type SecretList = Awaited<ReturnType<typeof secretsApi.list>>;
|
||||
type RoutineRunList = Awaited<ReturnType<typeof import("../../api/routines").routinesApi.listRuns>>;
|
||||
type RoutineActivityList = Awaited<
|
||||
ReturnType<typeof import("../../api/routines").routinesApi.activity>
|
||||
>;
|
||||
|
||||
export type RoutineDetailContextValue = {
|
||||
routine: RoutineDetailType;
|
||||
routineId: string;
|
||||
companyId: string;
|
||||
|
||||
// edit state
|
||||
editDraft: RoutineEditDraft;
|
||||
setEditDraft: React.Dispatch<React.SetStateAction<RoutineEditDraft>>;
|
||||
routineDefaults: RoutineEditDraft;
|
||||
dirtyFields: RoutineHistoryDirtyFieldDescriptor[];
|
||||
isEditDirty: boolean;
|
||||
sectionDirtyFields: (section: RoutineSectionKey) => RoutineHistoryDirtyFieldDescriptor[];
|
||||
isSectionDirty: (section: RoutineSectionKey) => boolean;
|
||||
discardSection: (section: RoutineSectionKey) => void;
|
||||
|
||||
// save
|
||||
saveRoutine: UseMutationResult<unknown, unknown, void, unknown>;
|
||||
saveConflict: boolean;
|
||||
reloadLatest: () => void;
|
||||
|
||||
// header / automation
|
||||
automationEnabled: boolean;
|
||||
automationLabel: string;
|
||||
automationLabelClassName: string;
|
||||
automationToggleDisabled: boolean;
|
||||
onToggleAutomation: () => void;
|
||||
onOpenRunDialog: () => void;
|
||||
runRoutinePending: boolean;
|
||||
|
||||
// triggers
|
||||
newTrigger: NewTriggerDraft;
|
||||
setNewTrigger: React.Dispatch<React.SetStateAction<NewTriggerDraft>>;
|
||||
createTrigger: UseMutationResult<RoutineTriggerResponse, unknown, void, unknown>;
|
||||
updateTrigger: UseMutationResult<unknown, unknown, { id: string; patch: Record<string, unknown> }, unknown>;
|
||||
deleteTrigger: UseMutationResult<unknown, unknown, string, unknown>;
|
||||
rotateTrigger: UseMutationResult<RotateRoutineTriggerResponse, unknown, string, unknown>;
|
||||
|
||||
// secrets
|
||||
secretMessage: SecretMessage | null;
|
||||
setSecretMessage: (message: SecretMessage | null) => void;
|
||||
copySecretValue: (label: string, value: string) => void;
|
||||
availableSecrets: SecretList;
|
||||
createSecret: UseMutationResult<CompanySecret, unknown, { name: string; value: string }, unknown>;
|
||||
|
||||
// entities
|
||||
agents: AgentList;
|
||||
projects: ProjectList;
|
||||
agentById: Map<string, AgentList[number]>;
|
||||
projectById: Map<string, ProjectList[number]>;
|
||||
assigneeOptions: InlineEntityOption[];
|
||||
projectOptions: InlineEntityOption[];
|
||||
recentAssigneeIds: string[];
|
||||
recentProjectIds: string[];
|
||||
mentionOptions: MentionOption[];
|
||||
currentAssignee: AgentList[number] | null;
|
||||
currentProject: ProjectList[number] | null;
|
||||
|
||||
// operate data
|
||||
routineRuns: RoutineRunList | undefined;
|
||||
activity: RoutineActivityList | undefined;
|
||||
hasLiveRun: boolean;
|
||||
activeIssueId: string | undefined;
|
||||
|
||||
// refs
|
||||
titleInputRef: React.RefObject<HTMLTextAreaElement | null>;
|
||||
descriptionEditorRef: React.RefObject<MarkdownEditorRef | null>;
|
||||
assigneeSelectorRef: React.RefObject<HTMLButtonElement | null>;
|
||||
projectSelectorRef: React.RefObject<HTMLButtonElement | null>;
|
||||
|
||||
// history restore plumbing
|
||||
onHistoryRestoreSecretMaterials: (
|
||||
response: import("../../api/routines").RestoreRoutineRevisionResponse,
|
||||
) => void;
|
||||
onHistoryRestored: (
|
||||
response: import("../../api/routines").RestoreRoutineRevisionResponse,
|
||||
) => void;
|
||||
|
||||
navigateToSection: (section: RoutineSectionKey, options?: { replace?: boolean }) => void;
|
||||
};
|
||||
|
||||
export const RoutineDetailContext = createContext<RoutineDetailContextValue | null>(null);
|
||||
|
||||
export function useRoutineDetail(): RoutineDetailContextValue {
|
||||
const value = useContext(RoutineDetailContext);
|
||||
if (!value) {
|
||||
throw new Error("useRoutineDetail must be used within a RoutineDetailContext provider");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -1,862 +0,0 @@
|
||||
import { AgentAvatar } from "@/components/AgentAvatar";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
ArrowRight,
|
||||
Braces,
|
||||
Clock3,
|
||||
Edit3,
|
||||
KeyRound,
|
||||
Play,
|
||||
Plus,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { RadioCardGroup } from "@/components/ui/radio-card";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { nextCronFires, previewFirePolicies } from "../../lib/cron-fires";
|
||||
import { timeAgo } from "../../lib/timeAgo";
|
||||
import { EmptyState } from "../EmptyState";
|
||||
import { InlineEntitySelector } from "../InlineEntitySelector";
|
||||
import { DocumentAnnotationsCountChip, IssueDocumentAnnotations } from "../IssueDocumentAnnotations";
|
||||
import { MarkdownEditor } from "../MarkdownEditor";
|
||||
import { ScheduleEditor, getScheduleCronValidation } from "../ScheduleEditor";
|
||||
import { RoutineVariablesEditor, RoutineVariablesHint } from "../RoutineVariablesEditor";
|
||||
import { RoutineTriggerCard } from "../RoutineTriggerCard";
|
||||
import { EnvironmentVariablesEditor } from "../environment-variables-editor";
|
||||
import { createDefaultNewTrigger, useRoutineDetail } from "./context";
|
||||
import type { EnvBinding, RoutineDetail as RoutineDetailType } from "@paperclipai/shared";
|
||||
|
||||
const concurrencyPolicyOptions = [
|
||||
{
|
||||
value: "coalesce_if_active",
|
||||
title: "Coalesce if active",
|
||||
description: "Keep one follow-up run queued while an active run is still working.",
|
||||
},
|
||||
{
|
||||
value: "always_enqueue",
|
||||
title: "Always enqueue",
|
||||
description: "Queue every trigger occurrence, even if several runs stack up.",
|
||||
},
|
||||
{
|
||||
value: "skip_if_active",
|
||||
title: "Skip if active",
|
||||
description: "Drop overlapping trigger occurrences while the routine is already active.",
|
||||
},
|
||||
];
|
||||
|
||||
const catchUpPolicyOptions = [
|
||||
{
|
||||
value: "skip_missed",
|
||||
title: "Skip missed",
|
||||
description: "Ignore schedule windows that were missed while paused.",
|
||||
},
|
||||
{
|
||||
value: "enqueue_missed_with_cap",
|
||||
title: "Enqueue missed with cap",
|
||||
description: "Catch up missed schedule windows after recovery; sub-hourly schedules are combined into one catch-up run, slower schedules replay each missed window up to a cap.",
|
||||
},
|
||||
];
|
||||
|
||||
const activityGatePolicyOptions = [
|
||||
{
|
||||
value: "always",
|
||||
title: "Run on every scheduled tick",
|
||||
description: "Fire on the schedule no matter what — the default behavior.",
|
||||
},
|
||||
{
|
||||
value: "require_external_activity",
|
||||
title: "Skip when there's been no activity since the last run",
|
||||
description:
|
||||
"On a scheduled tick, only run if something happened since the last run that finished. Lets a watcher-style routine stay asleep while the system is settled instead of burning tokens.",
|
||||
},
|
||||
];
|
||||
|
||||
const activityGateScopeOptions = [
|
||||
{
|
||||
value: "company",
|
||||
title: "Company-wide",
|
||||
description: "Any activity across the company counts as a reason to run.",
|
||||
},
|
||||
{
|
||||
value: "project",
|
||||
title: "This project",
|
||||
description: "Only activity in the routine's project counts as a reason to run.",
|
||||
},
|
||||
];
|
||||
|
||||
const triggerKinds = ["schedule", "webhook"];
|
||||
const signingModes = ["app_webhook", "bearer", "hmac_sha256", "github_hmac", "none"];
|
||||
const signingModeDescriptions: Record<string, string> = {
|
||||
bearer: "Send Authorization: Bearer <secret> with each request.",
|
||||
hmac_sha256: "Send X-Paperclip-Timestamp and X-Paperclip-Signature: sha256=<hex>, signing timestamp + a dot + the exact JSON body.",
|
||||
github_hmac: "Accept GitHub-style X-Hub-Signature-256 header (HMAC over raw body, no timestamp).",
|
||||
app_webhook: "Accept a bearer token or an HMAC-SHA256 signature over the exact request body in X-Hub-Signature or X-Hub-Signature-256.",
|
||||
fireflies_hmac: "Signed webhook (legacy).",
|
||||
none: "No authentication — the webhook URL itself acts as a shared secret.",
|
||||
};
|
||||
const SIGNING_MODES_WITHOUT_REPLAY_WINDOW = new Set(["app_webhook", "bearer", "github_hmac", "fireflies_hmac", "none"]);
|
||||
|
||||
export function OverviewSection({
|
||||
defaultDescriptionAnnotationsOpen = false,
|
||||
}: {
|
||||
defaultDescriptionAnnotationsOpen?: boolean;
|
||||
} = {}) {
|
||||
const ctx = useRoutineDetail();
|
||||
const {
|
||||
routine,
|
||||
editDraft,
|
||||
setEditDraft,
|
||||
assigneeOptions,
|
||||
projectOptions,
|
||||
recentAssigneeIds,
|
||||
recentProjectIds,
|
||||
agentById,
|
||||
projectById,
|
||||
currentAssignee,
|
||||
currentProject,
|
||||
mentionOptions,
|
||||
assigneeSelectorRef,
|
||||
projectSelectorRef,
|
||||
descriptionEditorRef,
|
||||
routineRuns,
|
||||
activity,
|
||||
saveRoutine,
|
||||
saveConflict,
|
||||
isSectionDirty,
|
||||
navigateToSection,
|
||||
} = ctx;
|
||||
const [descriptionAnnotationsOpen, setDescriptionAnnotationsOpen] = useState(defaultDescriptionAnnotationsOpen);
|
||||
|
||||
const activeTriggers = routine.triggers.length;
|
||||
const nextFire = useMemo(() => {
|
||||
const upcoming = routine.triggers
|
||||
.filter((trigger) => trigger.kind === "schedule" && trigger.nextRunAt)
|
||||
.map((trigger) => new Date(trigger.nextRunAt as Date))
|
||||
.sort((a, b) => a.getTime() - b.getTime())[0];
|
||||
return upcoming ? upcoming.toLocaleString() : null;
|
||||
}, [routine.triggers]);
|
||||
const boundSecrets = editDraft.env ? Object.keys(editDraft.env).length : 0;
|
||||
const lastRun = (routineRuns ?? [])[0] ?? null;
|
||||
const recentActivity = (activity ?? []).slice(0, 5);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Assignment row */}
|
||||
<div className="overflow-x-auto overscroll-x-contain">
|
||||
<div className="inline-flex min-w-full flex-wrap items-center gap-2 text-sm text-muted-foreground sm:min-w-max sm:flex-nowrap">
|
||||
<span>For</span>
|
||||
<InlineEntitySelector
|
||||
ref={assigneeSelectorRef}
|
||||
value={editDraft.assigneeAgentId}
|
||||
options={assigneeOptions}
|
||||
recentOptionIds={recentAssigneeIds}
|
||||
placeholder="Responsible"
|
||||
noneLabel="No responsible"
|
||||
searchPlaceholder="Search responsible..."
|
||||
emptyMessage="No responsible found."
|
||||
onChange={(assigneeAgentId) =>
|
||||
setEditDraft((current) => ({ ...current, assigneeAgentId }))
|
||||
}
|
||||
onConfirm={() => {
|
||||
if (editDraft.projectId) {
|
||||
descriptionEditorRef.current?.focus();
|
||||
} else {
|
||||
projectSelectorRef.current?.focus();
|
||||
}
|
||||
}}
|
||||
renderTriggerValue={(option) =>
|
||||
option ? (
|
||||
currentAssignee ? (
|
||||
<>
|
||||
<AgentAvatar agent={currentAssignee} size={16} className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/>
|
||||
<span className="truncate">{option.label}</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="truncate">{option.label}</span>
|
||||
)
|
||||
) : (
|
||||
<span className="text-muted-foreground">Responsible</span>
|
||||
)
|
||||
}
|
||||
renderOption={(option) => {
|
||||
if (!option.id) return <span className="truncate">{option.label}</span>;
|
||||
const assignee = agentById.get(option.id);
|
||||
return (
|
||||
<>
|
||||
{assignee ? (
|
||||
<AgentAvatar agent={assignee} size={16} className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/>
|
||||
) : null}
|
||||
<span className="truncate">{option.label}</span>
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<span>in</span>
|
||||
<InlineEntitySelector
|
||||
ref={projectSelectorRef}
|
||||
value={editDraft.projectId}
|
||||
options={projectOptions}
|
||||
recentOptionIds={recentProjectIds}
|
||||
placeholder="Project"
|
||||
noneLabel="No project"
|
||||
searchPlaceholder="Search projects..."
|
||||
emptyMessage="No projects found."
|
||||
onChange={(projectId) => setEditDraft((current) => ({ ...current, projectId }))}
|
||||
onConfirm={() => descriptionEditorRef.current?.focus()}
|
||||
renderTriggerValue={(option) =>
|
||||
option && currentProject ? (
|
||||
<>
|
||||
<span
|
||||
className="h-3.5 w-3.5 shrink-0 rounded-sm"
|
||||
style={{ backgroundColor: currentProject.color ?? "var(--project-none)" }}
|
||||
/>
|
||||
<span className="truncate">{option.label}</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-muted-foreground">Project</span>
|
||||
)
|
||||
}
|
||||
renderOption={(option) => {
|
||||
if (!option.id) return <span className="truncate">{option.label}</span>;
|
||||
const project = projectById.get(option.id);
|
||||
return (
|
||||
<>
|
||||
<span
|
||||
className="h-3.5 w-3.5 shrink-0 rounded-sm"
|
||||
style={{ backgroundColor: project?.color ?? "var(--project-none)" }}
|
||||
/>
|
||||
<span className="truncate">{option.label}</span>
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!routine.assigneeAgentId ? (
|
||||
<div className="rounded-lg border border-amber-500/30 bg-amber-500/5 p-4 text-sm text-amber-900 dark:text-amber-200">
|
||||
Default agent required. This routine can stay as a draft and still run manually, but
|
||||
automation stays paused until you assign a default agent.
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Instructions */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-end">
|
||||
{routine.descriptionDocument ? (
|
||||
<DocumentAnnotationsCountChip
|
||||
issueId={routine.id}
|
||||
docKey="description"
|
||||
target={{ kind: "routine", routineId: routine.id, documentKey: "description" }}
|
||||
panelOpen={descriptionAnnotationsOpen}
|
||||
onToggle={() => setDescriptionAnnotationsOpen((open) => !open)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
{routine.descriptionDocument ? (
|
||||
<IssueDocumentAnnotations
|
||||
issueId={routine.id}
|
||||
doc={routine.descriptionDocument}
|
||||
target={{ kind: "routine", routineId: routine.id, documentKey: "description" }}
|
||||
bodyMarkdown={editDraft.description}
|
||||
draftDirty={isSectionDirty("overview") || saveRoutine.isPending}
|
||||
draftConflicted={saveConflict}
|
||||
historicalPreview={false}
|
||||
locationHash={typeof window === "undefined" ? "" : window.location.hash}
|
||||
panelOpen={descriptionAnnotationsOpen}
|
||||
onPanelOpenChange={setDescriptionAnnotationsOpen}
|
||||
>
|
||||
<MarkdownEditor
|
||||
ref={descriptionEditorRef}
|
||||
value={editDraft.description}
|
||||
onChange={(description) => setEditDraft((current) => ({ ...current, description }))}
|
||||
placeholder="Add instructions..."
|
||||
bordered={false}
|
||||
contentClassName="min-h-(--sz-120px) text-sm leading-7"
|
||||
mentions={mentionOptions}
|
||||
onSubmit={() => {
|
||||
if (!saveRoutine.isPending && editDraft.title.trim()) {
|
||||
saveRoutine.mutate();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</IssueDocumentAnnotations>
|
||||
) : (
|
||||
<MarkdownEditor
|
||||
ref={descriptionEditorRef}
|
||||
value={editDraft.description}
|
||||
onChange={(description) => setEditDraft((current) => ({ ...current, description }))}
|
||||
placeholder="Add instructions..."
|
||||
bordered={false}
|
||||
contentClassName="min-h-(--sz-120px) text-sm leading-7"
|
||||
mentions={mentionOptions}
|
||||
onSubmit={() => {
|
||||
if (!saveRoutine.isPending && editDraft.title.trim()) {
|
||||
saveRoutine.mutate();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Variables peek */}
|
||||
<div className="space-y-3">
|
||||
<RoutineVariablesHint />
|
||||
<RoutineVariablesEditor
|
||||
title={editDraft.title}
|
||||
description={editDraft.description}
|
||||
value={editDraft.variables}
|
||||
onChange={(variables) => setEditDraft((current) => ({ ...current, variables }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Summary cards */}
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<SummaryCard
|
||||
icon={Clock3}
|
||||
label="Triggers"
|
||||
value={activeTriggers === 0 ? "None" : `${activeTriggers} active`}
|
||||
hint={nextFire ? `Next fire ${nextFire}` : "No schedule"}
|
||||
to={() => navigateToSection("triggers")}
|
||||
ariaLabel={`${activeTriggers} triggers. Open triggers.`}
|
||||
/>
|
||||
<SummaryCard
|
||||
icon={KeyRound}
|
||||
label="Secrets"
|
||||
value={boundSecrets === 0 ? "None" : `${boundSecrets} bound`}
|
||||
hint="Manage bound secrets"
|
||||
to={() => navigateToSection("secrets")}
|
||||
ariaLabel={`${boundSecrets} secrets bound. Open secrets.`}
|
||||
/>
|
||||
<SummaryCard
|
||||
icon={Play}
|
||||
label="Last run"
|
||||
value={lastRun ? lastRun.status.replaceAll("_", " ") : "No runs"}
|
||||
hint={lastRun ? timeAgo(lastRun.triggeredAt) : "Trigger a run"}
|
||||
to={() => navigateToSection("runs")}
|
||||
ariaLabel={lastRun ? `Last run ${lastRun.status}. Open runs.` : "No runs. Open runs."}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Recent activity */}
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Recent activity
|
||||
</p>
|
||||
{recentActivity.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">No activity yet.</p>
|
||||
) : (
|
||||
<div className="divide-y divide-border/60">
|
||||
{recentActivity.map((event) => (
|
||||
<div key={event.id} className="flex items-center gap-2 py-1.5 text-xs">
|
||||
<Badge variant="outline" className="shrink-0 font-mono">
|
||||
{event.action}
|
||||
</Badge>
|
||||
<span className="min-w-0 flex-1 truncate text-muted-foreground">
|
||||
{event.details && Object.keys(event.details).length > 0
|
||||
? Object.keys(event.details).slice(0, 3).join(" · ")
|
||||
: ""}
|
||||
</span>
|
||||
<span className="shrink-0 text-muted-foreground/60">{timeAgo(event.createdAt)}</span>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigateToSection("activity")}
|
||||
className="flex items-center gap-1 pt-2 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
View all activity <ArrowRight className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SummaryCard({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
hint,
|
||||
to,
|
||||
ariaLabel,
|
||||
}: {
|
||||
icon: typeof Clock3;
|
||||
label: string;
|
||||
value: string;
|
||||
hint: string;
|
||||
to: () => void;
|
||||
ariaLabel: string;
|
||||
}) {
|
||||
return (
|
||||
<button type="button" onClick={to} aria-label={ariaLabel} className="text-left">
|
||||
<Card className="gap-2 p-4 transition-colors hover:border-border hover:bg-accent/30">
|
||||
<CardContent className="space-y-1 p-0">
|
||||
<div className="flex items-center gap-1.5 text-xs uppercase tracking-wide text-muted-foreground">
|
||||
<Icon className="h-3.5 w-3.5" />
|
||||
{label}
|
||||
<ArrowRight className="ml-auto h-3.5 w-3.5 text-muted-foreground/60" />
|
||||
</div>
|
||||
<p className="text-lg font-semibold">{value}</p>
|
||||
<p className="text-xs text-muted-foreground">{hint}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function TriggersSection() {
|
||||
const ctx = useRoutineDetail();
|
||||
const { routine, newTrigger, setNewTrigger, createTrigger, updateTrigger, deleteTrigger, rotateTrigger, secretMessage, copySecretValue, setSecretMessage } = ctx;
|
||||
const [addOpen, setAddOpen] = useState(false);
|
||||
const [newScheduleEditorValid, setNewScheduleEditorValid] = useState(true);
|
||||
const newScheduleValidation = useMemo(
|
||||
() => newTrigger.kind === "schedule" ? getScheduleCronValidation(newTrigger.cronExpression) : null,
|
||||
[newTrigger.cronExpression, newTrigger.kind],
|
||||
);
|
||||
const addDisabled =
|
||||
createTrigger.isPending ||
|
||||
(newScheduleValidation ? !newScheduleValidation.valid || !newScheduleEditorValid : false);
|
||||
|
||||
useEffect(() => {
|
||||
if (newTrigger.kind !== "schedule") setNewScheduleEditorValid(true);
|
||||
}, [newTrigger.kind]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Add-trigger drawer header (§3.2) */}
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm font-medium text-muted-foreground">
|
||||
{routine.triggers.length === 0
|
||||
? "No triggers yet"
|
||||
: `${routine.triggers.length} trigger${routine.triggers.length === 1 ? "" : "s"}`}
|
||||
</p>
|
||||
<Button
|
||||
size="sm"
|
||||
variant={addOpen ? "secondary" : "default"}
|
||||
onClick={() => setAddOpen((open) => !open)}
|
||||
aria-expanded={addOpen}
|
||||
>
|
||||
{addOpen ? (
|
||||
<>
|
||||
<X className="mr-1.5 h-3.5 w-3.5" />
|
||||
Cancel
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Plus className="mr-1.5 h-3.5 w-3.5" />
|
||||
New trigger
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Add trigger form — expand-on-click drawer */}
|
||||
{addOpen ? (
|
||||
<div className="space-y-3 rounded-lg border border-border p-4">
|
||||
<p className="text-sm font-medium">Add trigger</p>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">Kind</Label>
|
||||
<Select
|
||||
value={newTrigger.kind}
|
||||
onValueChange={(kind) => setNewTrigger((current) => ({ ...current, kind }))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{triggerKinds.map((kind) => (
|
||||
<SelectItem key={kind} value={kind}>
|
||||
{kind}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{newTrigger.kind === "schedule" && (
|
||||
<div className="space-y-1.5 md:col-span-2">
|
||||
<Label className="text-xs">Schedule</Label>
|
||||
<ScheduleEditor
|
||||
value={newTrigger.cronExpression}
|
||||
onChange={(cronExpression) =>
|
||||
setNewTrigger((current) => ({ ...current, cronExpression }))
|
||||
}
|
||||
onValidityChange={setNewScheduleEditorValid}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{newTrigger.kind === "webhook" && (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">Signing mode</Label>
|
||||
<Select
|
||||
value={newTrigger.signingMode}
|
||||
onValueChange={(signingMode) =>
|
||||
setNewTrigger((current) => ({ ...current, signingMode }))
|
||||
}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{signingModes.map((mode) => (
|
||||
<SelectItem key={mode} value={mode}>
|
||||
{mode}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{signingModeDescriptions[newTrigger.signingMode]}
|
||||
</p>
|
||||
</div>
|
||||
{!SIGNING_MODES_WITHOUT_REPLAY_WINDOW.has(newTrigger.signingMode) && (
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">Replay window (seconds)</Label>
|
||||
<Input
|
||||
value={newTrigger.replayWindowSec}
|
||||
onChange={(event) =>
|
||||
setNewTrigger((current) => ({ ...current, replayWindowSec: event.target.value }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Button size="sm" variant="ghost" onClick={() => setAddOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
createTrigger.mutate(undefined, {
|
||||
onSuccess: () => {
|
||||
setNewTrigger(createDefaultNewTrigger());
|
||||
setAddOpen(false);
|
||||
},
|
||||
})
|
||||
}
|
||||
disabled={addDisabled}
|
||||
>
|
||||
{createTrigger.isPending ? "Adding..." : "Add trigger"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{secretMessage ? (
|
||||
<div className="space-y-3 rounded-lg border border-border bg-muted/20 p-4 text-sm">
|
||||
<div>
|
||||
<p className="font-medium">{secretMessage.title}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Save this now. Paperclip will not show the secret value again.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{secretMessage.entries.map((entry, index) => (
|
||||
<div key={`${entry.webhookUrl}-${index}`} className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input aria-label="New webhook URL" value={entry.webhookUrl} readOnly className="flex-1" />
|
||||
<Button variant="outline" size="sm" onClick={() => copySecretValue("Webhook URL", entry.webhookUrl)}>
|
||||
URL
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input aria-label="New webhook secret" value={entry.webhookSecret} readOnly className="flex-1" />
|
||||
<Button variant="outline" size="sm" onClick={() => copySecretValue("Webhook secret", entry.webhookSecret)}>
|
||||
Secret
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={() => setSecretMessage(null)}>Done</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Existing triggers */}
|
||||
{routine.triggers.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={Clock3}
|
||||
message="No triggers yet."
|
||||
action="Add a trigger"
|
||||
onAction={() => setAddOpen(true)}
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{routine.triggers.map((trigger) => (
|
||||
<RoutineTriggerCard
|
||||
key={trigger.id}
|
||||
trigger={trigger}
|
||||
onSave={(id, patch) => updateTrigger.mutate({ id, patch })}
|
||||
onRotate={(id) => rotateTrigger.mutate(id)}
|
||||
onDelete={(id) => deleteTrigger.mutate(id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function VariablesSection() {
|
||||
const ctx = useRoutineDetail();
|
||||
const { editDraft, setEditDraft, navigateToSection } = ctx;
|
||||
const hasVariables = editDraft.variables.length > 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-3 rounded-md border border-border bg-muted/20 px-4 py-3 text-xs">
|
||||
<span className="flex-1 text-muted-foreground">
|
||||
Variables are auto-detected from <code className="font-mono">{"{{placeholders}}"}</code> in
|
||||
the title & instructions. The variable name is read-only — rename by editing the
|
||||
placeholder.
|
||||
</span>
|
||||
<Button variant="secondary" size="sm" onClick={() => navigateToSection("overview")}>
|
||||
<Edit3 className="mr-1.5 h-3.5 w-3.5" />
|
||||
Edit instructions
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{hasVariables ? (
|
||||
<RoutineVariablesEditor
|
||||
title={editDraft.title}
|
||||
description={editDraft.description}
|
||||
value={editDraft.variables}
|
||||
onChange={(variables) => setEditDraft((current) => ({ ...current, variables }))}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState
|
||||
icon={Braces}
|
||||
message="No variables yet. Add a {{placeholder}} in the title or instructions to create one."
|
||||
action="Edit instructions"
|
||||
onAction={() => navigateToSection("overview")}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SecretsSection() {
|
||||
const ctx = useRoutineDetail();
|
||||
const { editDraft, setEditDraft, availableSecrets, createSecret } = ctx;
|
||||
|
||||
// Project/company-scoped secrets that already see real usage, surfaced as
|
||||
// quick-bind chips (§3.4). Ranked by reference count then recency.
|
||||
const recentlyUsedSecrets = useMemo(
|
||||
() =>
|
||||
[...availableSecrets]
|
||||
.filter((secret) => secret.status === "active")
|
||||
.sort((a, b) => {
|
||||
const refDelta = (b.referenceCount ?? 0) - (a.referenceCount ?? 0);
|
||||
if (refDelta !== 0) return refDelta;
|
||||
return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
|
||||
})
|
||||
.slice(0, 8),
|
||||
[availableSecrets],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-md border border-border bg-muted/20 px-4 py-3 text-xs text-muted-foreground">
|
||||
Routine secrets apply to every task this routine creates. They override matching keys in
|
||||
project and agent env. <span className="font-mono">PAPERCLIP_*</span> names are reserved.
|
||||
</div>
|
||||
|
||||
|
||||
<EnvironmentVariablesEditor
|
||||
value={(editDraft.env ?? {}) as Record<string, EnvBinding>}
|
||||
secrets={availableSecrets}
|
||||
recentlyUsedSecrets={recentlyUsedSecrets}
|
||||
onCreateSecret={async (name, value) => createSecret.mutateAsync({ name, value })}
|
||||
onChange={(env) => setEditDraft((current) => ({ ...current, env: env ?? null }))}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DeliverySection() {
|
||||
const ctx = useRoutineDetail();
|
||||
const { editDraft, setEditDraft, routine } = ctx;
|
||||
|
||||
// The activity gate only affects schedule ticks (webhook/manual/API fires are
|
||||
// themselves activity and always run), so the control is only meaningful for
|
||||
// routines that have a schedule trigger. Disable — rather than hide — it
|
||||
// elsewhere so the capability stays discoverable.
|
||||
const hasScheduleTrigger = routine.triggers.some((trigger) => trigger.kind === "schedule");
|
||||
const gateEnabled = editDraft.activityGatePolicy === "require_external_activity";
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-3">
|
||||
<p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">
|
||||
Concurrency
|
||||
</p>
|
||||
<RadioCardGroup
|
||||
ariaLabel="Concurrency policy"
|
||||
value={editDraft.concurrencyPolicy}
|
||||
onValueChange={(concurrencyPolicy) =>
|
||||
setEditDraft((current) => ({ ...current, concurrencyPolicy }))
|
||||
}
|
||||
options={concurrencyPolicyOptions}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">
|
||||
Catch-up
|
||||
</p>
|
||||
<RadioCardGroup
|
||||
ariaLabel="Catch-up policy"
|
||||
value={editDraft.catchUpPolicy}
|
||||
onValueChange={(catchUpPolicy) =>
|
||||
setEditDraft((current) => ({ ...current, catchUpPolicy }))
|
||||
}
|
||||
options={catchUpPolicyOptions}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">
|
||||
Advanced run policy
|
||||
</p>
|
||||
<RadioCardGroup
|
||||
ariaLabel="Advanced run policy"
|
||||
value={editDraft.activityGatePolicy}
|
||||
onValueChange={(activityGatePolicy) =>
|
||||
setEditDraft((current) => ({ ...current, activityGatePolicy }))
|
||||
}
|
||||
options={activityGatePolicyOptions}
|
||||
disabled={!hasScheduleTrigger}
|
||||
/>
|
||||
{!hasScheduleTrigger ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Add a schedule trigger to gate runs on activity. Webhook, manual, and API fires always
|
||||
run.
|
||||
</p>
|
||||
) : gateEnabled ? (
|
||||
<div className="space-y-2 rounded-lg border border-border p-3">
|
||||
<Label className="text-xs font-medium">Activity scope</Label>
|
||||
<RadioCardGroup
|
||||
ariaLabel="Activity gate scope"
|
||||
value={editDraft.activityGateScope}
|
||||
onValueChange={(activityGateScope) =>
|
||||
setEditDraft((current) => ({ ...current, activityGateScope }))
|
||||
}
|
||||
options={activityGateScopeOptions}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<NextFiresPreview
|
||||
triggers={routine.triggers}
|
||||
concurrencyPolicy={editDraft.concurrencyPolicy}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const dispositionToneClass: Record<string, string> = {
|
||||
queued: "text-emerald-600 dark:text-emerald-400",
|
||||
coalesced: "text-amber-600 dark:text-amber-400",
|
||||
skipped: "text-muted-foreground",
|
||||
};
|
||||
|
||||
/**
|
||||
* "Next 5 fires" preview (§3.5) — the strongest "what does this policy mean?"
|
||||
* surface. Picks the soonest-firing schedule trigger, computes its next fires
|
||||
* client-side, and annotates each with how the chosen concurrency policy would
|
||||
* treat it.
|
||||
*/
|
||||
function NextFiresPreview({
|
||||
triggers,
|
||||
concurrencyPolicy,
|
||||
}: {
|
||||
triggers: RoutineDetailType["triggers"];
|
||||
concurrencyPolicy: string;
|
||||
}) {
|
||||
const preview = useMemo(() => {
|
||||
const schedule = triggers
|
||||
.filter((trigger) => trigger.kind === "schedule" && trigger.enabled && trigger.cronExpression)
|
||||
.map((trigger) => {
|
||||
const fires = nextCronFires(trigger.cronExpression, 5, {
|
||||
timeZone: trigger.timezone ?? "UTC",
|
||||
});
|
||||
return { trigger, fires };
|
||||
})
|
||||
.filter((entry) => entry.fires.length > 0)
|
||||
.sort((a, b) => a.fires[0]!.getTime() - b.fires[0]!.getTime())[0];
|
||||
if (!schedule) return null;
|
||||
return {
|
||||
timeZone: schedule.trigger.timezone ?? "UTC",
|
||||
entries: previewFirePolicies(schedule.fires, concurrencyPolicy),
|
||||
};
|
||||
}, [triggers, concurrencyPolicy]);
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">
|
||||
Next 5 fires
|
||||
</p>
|
||||
{preview ? (
|
||||
<>
|
||||
<div className="space-y-1.5 rounded-lg border border-border p-3 font-mono text-xs">
|
||||
{preview.entries.map((entry, index) => (
|
||||
<div key={index} className="flex items-center gap-2">
|
||||
<span className="text-muted-foreground/40">·</span>
|
||||
<span className="tabular-nums">{formatFireTime(entry.at, preview.timeZone)}</span>
|
||||
<ArrowRight className="h-3 w-3 shrink-0 text-muted-foreground/50" />
|
||||
<span className={cn("font-medium", dispositionToneClass[entry.disposition])}>
|
||||
{entry.label}
|
||||
</span>
|
||||
{entry.note ? (
|
||||
<span className="truncate text-muted-foreground/60">({entry.note})</span>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-(length:--text-micro) text-muted-foreground/60">
|
||||
Preview assumes the previous run is still in flight when the next fires. Times shown in{" "}
|
||||
{preview.timeZone}.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="rounded-lg border border-dashed border-border p-3 text-xs text-muted-foreground">
|
||||
No enabled schedule trigger to preview. Add a schedule in Triggers to see how this policy
|
||||
treats upcoming fires.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatFireTime(date: Date, timeZone: string): string {
|
||||
try {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
timeZone,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hourCycle: "h23",
|
||||
})
|
||||
.format(date)
|
||||
.replace(",", "");
|
||||
} catch {
|
||||
return date.toISOString();
|
||||
}
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { RoutineDetail, RoutineTrigger } from "@paperclipai/shared";
|
||||
import { BreadcrumbProvider } from "@/context/BreadcrumbContext";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { TriggersSection } from "./editable-sections";
|
||||
import { RoutineDetailContext, type RoutineDetailContextValue, type SecretMessage } from "./context";
|
||||
|
||||
const api = vi.hoisted(() => ({ get: vi.fn(), createTrigger: vi.fn(), updateTrigger: vi.fn() }));
|
||||
vi.mock("@/api/routines", () => ({ routinesApi: api }));
|
||||
vi.mock("@/context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: false, setSidebarOpen: vi.fn() }) }));
|
||||
vi.mock("../MarkdownEditor", () => ({ MarkdownEditor: () => null }));
|
||||
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
let client: QueryClient;
|
||||
let routine: RoutineDetail;
|
||||
function button(label: string) {
|
||||
const found = [...container.querySelectorAll<HTMLButtonElement>("button")].find((item) => item.textContent?.trim() === label);
|
||||
if (!found) throw new Error(`Button not found: ${label}`);
|
||||
return found;
|
||||
}
|
||||
async function click(label: string) { await act(async () => button(label).click()); }
|
||||
async function choose(label: string) {
|
||||
const option = [...container.querySelectorAll("label")].find((item) => item.textContent?.includes(label));
|
||||
expect(option).toBeTruthy();
|
||||
await act(async () => option!.click());
|
||||
}
|
||||
function Harness({ secretMessage, contextRoutine }: { secretMessage?: SecretMessage; contextRoutine?: RoutineDetail }) {
|
||||
const { data } = useQuery({ queryKey: queryKeys.routines.detail(routine.id), queryFn: api.get });
|
||||
const value = { routine: contextRoutine ?? data ?? routine, routineId: routine.id, companyId: routine.companyId, secretMessage, setSecretMessage: vi.fn() } as unknown as RoutineDetailContextValue;
|
||||
return <RoutineDetailContext.Provider value={value}><TriggersSection /></RoutineDetailContext.Provider>;
|
||||
}
|
||||
async function render(secretMessage?: SecretMessage, contextRoutine?: RoutineDetail) {
|
||||
await act(async () => root.render(<MemoryRouter initialEntries={["/routines/routine-1/triggers"]}>
|
||||
<QueryClientProvider client={client}><BreadcrumbProvider><Harness secretMessage={secretMessage} contextRoutine={contextRoutine} /></BreadcrumbProvider></QueryClientProvider>
|
||||
</MemoryRouter>));
|
||||
}
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
sessionStorage.clear();
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
|
||||
routine = { id: "routine-1", companyId: "company-1", title: "Verify deployment", status: "active", triggers: [] } as unknown as RoutineDetail;
|
||||
api.get.mockImplementation(async () => routine);
|
||||
api.createTrigger.mockImplementation(async (_id, input) => {
|
||||
const trigger = { id: "trigger-1", enabled: true, webhookUrl: "https://paperclip.example/api/routine-triggers/public/0123456789abcdef01234567/fire", ...input } as RoutineTrigger;
|
||||
routine = { ...routine, triggers: [...routine.triggers, trigger] };
|
||||
return { trigger, secretMaterial: { webhookUrl: trigger.webhookUrl, webhookSecret: "one-time-secret" } };
|
||||
});
|
||||
api.updateTrigger.mockImplementation(async (id, patch) => {
|
||||
routine = { ...routine, triggers: routine.triggers.map((trigger) => trigger.id === id ? { ...trigger, ...patch } : trigger) };
|
||||
return routine.triggers.find((trigger) => trigger.id === id);
|
||||
});
|
||||
});
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount());
|
||||
client.clear();
|
||||
container.remove();
|
||||
});
|
||||
|
||||
describe("TriggersSection", () => {
|
||||
it("offers schedule and webhook choices before creating a trigger", async () => {
|
||||
await render();
|
||||
await click("Add trigger");
|
||||
expect(button("Continue").disabled).toBe(true);
|
||||
expect(container.textContent).toContain("On a schedule");
|
||||
await choose("When another app sends a webhook");
|
||||
expect(button("Continue").disabled).toBe(false);
|
||||
expect(api.createTrigger).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("creates a pending webhook, shows credentials, and activates only when setup finishes", async () => {
|
||||
await render();
|
||||
await click("Add trigger");
|
||||
await choose("When another app sends a webhook");
|
||||
await click("Continue");
|
||||
expect(api.createTrigger).toHaveBeenCalledWith("routine-1", { kind: "webhook", signingMode: "app_webhook", setupPending: true });
|
||||
expect(container.textContent).toContain("one-time-secret");
|
||||
expect(container.textContent).toContain("signing secret field");
|
||||
expect(button("Copy for your agent")).toBeTruthy();
|
||||
expect(JSON.stringify(Object.values(sessionStorage))).not.toContain("one-time-secret");
|
||||
await click("Check connection");
|
||||
expect(container.textContent).toContain("This won’t start the routine");
|
||||
expect(api.updateTrigger).not.toHaveBeenCalled();
|
||||
await click("Finish without checking");
|
||||
expect(api.updateTrigger).toHaveBeenCalledWith("trigger-1", { setupPending: false });
|
||||
expect(button("Add trigger")).toBeTruthy();
|
||||
expect(container.textContent).not.toContain("one-time-secret");
|
||||
});
|
||||
|
||||
it("warns about private URLs without blocking webhook setup or completion", async () => {
|
||||
routine.triggers = [{ id: "trigger-1", kind: "webhook", enabled: true, setupPending: true, signingMode: "bearer", webhookUrl: "https://paperclip.internal/webhook" }] as RoutineTrigger[];
|
||||
await render();
|
||||
await click("Resume setup");
|
||||
expect(container.textContent).toContain("This webhook URL appears to be private");
|
||||
expect(container.querySelector('a[href="https://docs.paperclip.ing/reference/deploy/https/"]')).not.toBeNull();
|
||||
expect(button("Check connection").disabled).toBe(false);
|
||||
await click("Check connection");
|
||||
expect(container.textContent).toContain("This webhook URL appears to be private");
|
||||
expect(button("Finish without checking").disabled).toBe(false);
|
||||
await click("Finish without checking");
|
||||
expect(api.updateTrigger).toHaveBeenCalledWith("trigger-1", { setupPending: false });
|
||||
await click("Edit webhook");
|
||||
expect(container.textContent).toContain("This webhook URL appears to be private");
|
||||
});
|
||||
|
||||
it("shows polled connection results even when routine context is stale", async () => {
|
||||
routine.triggers = [{ id: "trigger-1", kind: "webhook", enabled: true, setupPending: true, signingMode: "bearer", webhookUrl: "https://paperclip.example/webhook" }] as RoutineTrigger[];
|
||||
await render(undefined, routine);
|
||||
await click("Resume setup");
|
||||
await click("Check connection");
|
||||
expect(container.textContent).toContain("Waiting to verify");
|
||||
for (const status of ["rejected", "received"] as const) {
|
||||
routine = { ...routine, triggers: [{ ...routine.triggers[0], lastWebhookDelivery: { status, test: true, receivedAt: new Date().toISOString() } }] };
|
||||
await act(async () => { await client.invalidateQueries({ queryKey: queryKeys.routines.detail(routine.id) }); });
|
||||
await vi.waitFor(() => expect(container.textContent).toContain(status === "received" ? "Authentication passed. No routine run or task was created." : "Go back to Connect your app, update the key"));
|
||||
}
|
||||
expect(button("Finish setup")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows restored one-time credentials on the triggers screen", async () => {
|
||||
await render({ title: "Webhook key restored", entries: [{ webhookUrl: "https://paperclip.example/webhook", webhookSecret: "restored-secret" }] });
|
||||
expect(container.textContent).toContain("restored-secret");
|
||||
expect(container.querySelector('[aria-label="Copy Secret key"]')).not.toBeNull();
|
||||
expect(button("Done")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("creates a schedule on confirmation and starts a fresh wizard afterward", async () => {
|
||||
await render();
|
||||
await click("Add trigger");
|
||||
await choose("On a schedule");
|
||||
await click("Continue");
|
||||
await click("Review schedule");
|
||||
expect(api.createTrigger).not.toHaveBeenCalled();
|
||||
await click("Add schedule");
|
||||
expect(api.createTrigger).toHaveBeenCalledWith("routine-1", expect.objectContaining({ kind: "schedule", cronExpression: "0 9 * * 1-5" }));
|
||||
await click("Add trigger");
|
||||
expect(button("Continue").disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("reveals schedule enable and pause actions only after opening the editor", async () => {
|
||||
routine.triggers = [{ id: "schedule-1", kind: "schedule", enabled: false, cronExpression: "* * * * *", timezone: "America/Chicago" }] as RoutineTrigger[];
|
||||
await render();
|
||||
expect(container.querySelector('section[aria-label="Schedule trigger"]')).not.toBeNull();
|
||||
expect(() => button("Enable trigger")).toThrow("Button not found");
|
||||
await click("Edit schedule");
|
||||
expect(button("Close").getAttribute("aria-expanded")).toBe("true");
|
||||
await click("Enable trigger");
|
||||
expect(api.updateTrigger).toHaveBeenNthCalledWith(1, "schedule-1", { enabled: true });
|
||||
expect(button("Pause trigger")).toBeTruthy();
|
||||
await click("Pause trigger");
|
||||
expect(api.updateTrigger).toHaveBeenNthCalledWith(2, "schedule-1", { enabled: false });
|
||||
expect(api.updateTrigger).toHaveBeenCalledTimes(2);
|
||||
expect(button("Enable trigger")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("blocks saving an invalid custom cron in the inline schedule editor", async () => {
|
||||
routine.triggers = [{ id: "schedule-1", kind: "schedule", enabled: true, cronExpression: "0 8-18/2 * * 1-5", timezone: "UTC" }] as RoutineTrigger[];
|
||||
await render();
|
||||
await click("Edit schedule");
|
||||
const input = container.querySelector<HTMLInputElement>('input[aria-label="Cron expression"]')!;
|
||||
expect(input).not.toBeNull();
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "0 8-18/2 *");
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
expect(container.textContent).toContain("Use exactly 5 fields");
|
||||
expect(button("Save schedule").disabled).toBe(true);
|
||||
expect(api.updateTrigger).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,642 +0,0 @@
|
||||
import { AgentAvatar } from "@/components/AgentAvatar";
|
||||
import { useMemo, useState } from "react";
|
||||
import {
|
||||
ArrowRight,
|
||||
Braces,
|
||||
Clock3,
|
||||
Edit3,
|
||||
Play,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { RadioCardGroup } from "@/components/ui/radio-card";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { nextCronFires, previewFirePolicies } from "../../lib/cron-fires";
|
||||
import { timeAgo } from "../../lib/timeAgo";
|
||||
import { EmptyState } from "../EmptyState";
|
||||
import { InlineEntitySelector } from "../InlineEntitySelector";
|
||||
import { DocumentAnnotationsCountChip, IssueDocumentAnnotations } from "../IssueDocumentAnnotations";
|
||||
import { MarkdownEditor } from "../MarkdownEditor";
|
||||
import { RoutineVariablesEditor, RoutineVariablesHint } from "../RoutineVariablesEditor";
|
||||
import { EnvironmentVariablesEditor } from "../environment-variables-editor";
|
||||
import { useRoutineDetail } from "./context";
|
||||
import type { EnvBinding, RoutineDetail as RoutineDetailType } from "@paperclipai/shared";
|
||||
|
||||
const concurrencyPolicyOptions = [
|
||||
{
|
||||
value: "coalesce_if_active",
|
||||
title: "Coalesce if active",
|
||||
description: "Keep one follow-up run queued while an active run is still working.",
|
||||
},
|
||||
{
|
||||
value: "always_enqueue",
|
||||
title: "Always enqueue",
|
||||
description: "Queue every trigger occurrence, even if several runs stack up.",
|
||||
},
|
||||
{
|
||||
value: "skip_if_active",
|
||||
title: "Skip if active",
|
||||
description: "Drop overlapping trigger occurrences while the routine is already active.",
|
||||
},
|
||||
];
|
||||
|
||||
const catchUpPolicyOptions = [
|
||||
{
|
||||
value: "skip_missed",
|
||||
title: "Skip missed",
|
||||
description: "Ignore schedule windows that were missed while paused.",
|
||||
},
|
||||
{
|
||||
value: "enqueue_missed_with_cap",
|
||||
title: "Enqueue missed with cap",
|
||||
description: "Catch up missed schedule windows after recovery; sub-hourly schedules are combined into one catch-up run, slower schedules replay each missed window up to a cap.",
|
||||
},
|
||||
];
|
||||
|
||||
const activityGatePolicyOptions = [
|
||||
{
|
||||
value: "always",
|
||||
title: "Run on every scheduled tick",
|
||||
description: "Fire on the schedule no matter what — the default behavior.",
|
||||
},
|
||||
{
|
||||
value: "require_external_activity",
|
||||
title: "Skip when there's been no activity since the last run",
|
||||
description:
|
||||
"On a scheduled tick, only run if something happened since the last run that finished. Lets a watcher-style routine stay asleep while the system is settled instead of burning tokens.",
|
||||
},
|
||||
];
|
||||
|
||||
const activityGateScopeOptions = [
|
||||
{
|
||||
value: "company",
|
||||
title: "Organization-wide",
|
||||
description: "Any activity across the organization counts as a reason to run.",
|
||||
},
|
||||
{
|
||||
value: "project",
|
||||
title: "This project",
|
||||
description: "Only activity in the routine's project counts as a reason to run.",
|
||||
},
|
||||
];
|
||||
|
||||
export function OverviewSection({
|
||||
defaultDescriptionAnnotationsOpen = false,
|
||||
}: {
|
||||
defaultDescriptionAnnotationsOpen?: boolean;
|
||||
} = {}) {
|
||||
const ctx = useRoutineDetail();
|
||||
const {
|
||||
routine,
|
||||
editDraft,
|
||||
setEditDraft,
|
||||
assigneeOptions,
|
||||
projectOptions,
|
||||
recentAssigneeIds,
|
||||
recentProjectIds,
|
||||
agentById,
|
||||
projectById,
|
||||
currentAssignee,
|
||||
currentProject,
|
||||
mentionOptions,
|
||||
assigneeSelectorRef,
|
||||
projectSelectorRef,
|
||||
descriptionEditorRef,
|
||||
routineRuns,
|
||||
activity,
|
||||
saveRoutine,
|
||||
saveConflict,
|
||||
isSectionDirty,
|
||||
navigateToSection,
|
||||
} = ctx;
|
||||
const [descriptionAnnotationsOpen, setDescriptionAnnotationsOpen] = useState(defaultDescriptionAnnotationsOpen);
|
||||
|
||||
const activeTriggers = routine.triggers.length;
|
||||
const nextFire = useMemo(() => {
|
||||
const upcoming = routine.triggers
|
||||
.filter((trigger) => trigger.kind === "schedule" && trigger.nextRunAt)
|
||||
.map((trigger) => new Date(trigger.nextRunAt as Date))
|
||||
.sort((a, b) => a.getTime() - b.getTime())[0];
|
||||
return upcoming ? upcoming.toLocaleString() : null;
|
||||
}, [routine.triggers]);
|
||||
const lastRun = (routineRuns ?? [])[0] ?? null;
|
||||
const recentActivity = (activity ?? []).slice(0, 5);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Assignment row */}
|
||||
<div className="overflow-x-auto overscroll-x-contain">
|
||||
<div className="inline-flex min-w-full flex-wrap items-center gap-2 text-sm text-muted-foreground sm:min-w-max sm:flex-nowrap">
|
||||
<span>For</span>
|
||||
<InlineEntitySelector
|
||||
ref={assigneeSelectorRef}
|
||||
value={editDraft.assigneeAgentId}
|
||||
options={assigneeOptions}
|
||||
recentOptionIds={recentAssigneeIds}
|
||||
placeholder="Responsible"
|
||||
noneLabel="No responsible"
|
||||
searchPlaceholder="Search responsible..."
|
||||
emptyMessage="No responsible found."
|
||||
onChange={(assigneeAgentId) =>
|
||||
setEditDraft((current) => ({ ...current, assigneeAgentId }))
|
||||
}
|
||||
onConfirm={() => {
|
||||
if (editDraft.projectId) {
|
||||
descriptionEditorRef.current?.focus();
|
||||
} else {
|
||||
projectSelectorRef.current?.focus();
|
||||
}
|
||||
}}
|
||||
renderTriggerValue={(option) =>
|
||||
option ? (
|
||||
currentAssignee ? (
|
||||
<>
|
||||
<AgentAvatar agent={currentAssignee} size={16} className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/>
|
||||
<span className="truncate">{option.label}</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="truncate">{option.label}</span>
|
||||
)
|
||||
) : (
|
||||
<span className="text-muted-foreground">Responsible</span>
|
||||
)
|
||||
}
|
||||
renderOption={(option) => {
|
||||
if (!option.id) return <span className="truncate">{option.label}</span>;
|
||||
const assignee = agentById.get(option.id);
|
||||
return (
|
||||
<>
|
||||
{assignee ? (
|
||||
<AgentAvatar agent={assignee} size={16} className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/>
|
||||
) : null}
|
||||
<span className="truncate">{option.label}</span>
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<span>in</span>
|
||||
<InlineEntitySelector
|
||||
ref={projectSelectorRef}
|
||||
value={editDraft.projectId}
|
||||
options={projectOptions}
|
||||
recentOptionIds={recentProjectIds}
|
||||
placeholder="Project"
|
||||
noneLabel="No project"
|
||||
searchPlaceholder="Search projects..."
|
||||
emptyMessage="No projects found."
|
||||
onChange={(projectId) => setEditDraft((current) => ({ ...current, projectId }))}
|
||||
onConfirm={() => descriptionEditorRef.current?.focus()}
|
||||
renderTriggerValue={(option) =>
|
||||
option && currentProject ? (
|
||||
<>
|
||||
<span
|
||||
className="h-3.5 w-3.5 shrink-0 rounded-sm"
|
||||
style={{ backgroundColor: currentProject.color ?? "var(--project-none)" }}
|
||||
/>
|
||||
<span className="truncate">{option.label}</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-muted-foreground">Project</span>
|
||||
)
|
||||
}
|
||||
renderOption={(option) => {
|
||||
if (!option.id) return <span className="truncate">{option.label}</span>;
|
||||
const project = projectById.get(option.id);
|
||||
return (
|
||||
<>
|
||||
<span
|
||||
className="h-3.5 w-3.5 shrink-0 rounded-sm"
|
||||
style={{ backgroundColor: project?.color ?? "var(--project-none)" }}
|
||||
/>
|
||||
<span className="truncate">{option.label}</span>
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!routine.assigneeAgentId ? (
|
||||
<div className="rounded-lg border border-amber-500/30 bg-amber-500/5 p-4 text-sm text-amber-900 dark:text-amber-200">
|
||||
Default agent required. This routine can stay as a draft and still run manually, but
|
||||
automation stays paused until you assign a default agent.
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Instructions */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-end">
|
||||
{routine.descriptionDocument ? (
|
||||
<DocumentAnnotationsCountChip
|
||||
issueId={routine.id}
|
||||
docKey="description"
|
||||
target={{ kind: "routine", routineId: routine.id, documentKey: "description" }}
|
||||
panelOpen={descriptionAnnotationsOpen}
|
||||
onToggle={() => setDescriptionAnnotationsOpen((open) => !open)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
{routine.descriptionDocument ? (
|
||||
<IssueDocumentAnnotations
|
||||
issueId={routine.id}
|
||||
doc={routine.descriptionDocument}
|
||||
target={{ kind: "routine", routineId: routine.id, documentKey: "description" }}
|
||||
bodyMarkdown={editDraft.description}
|
||||
draftDirty={isSectionDirty("overview") || saveRoutine.isPending}
|
||||
draftConflicted={saveConflict}
|
||||
historicalPreview={false}
|
||||
locationHash={typeof window === "undefined" ? "" : window.location.hash}
|
||||
panelOpen={descriptionAnnotationsOpen}
|
||||
onPanelOpenChange={setDescriptionAnnotationsOpen}
|
||||
>
|
||||
<MarkdownEditor
|
||||
ref={descriptionEditorRef}
|
||||
value={editDraft.description}
|
||||
onChange={(description) => setEditDraft((current) => ({ ...current, description }))}
|
||||
placeholder="Add instructions..."
|
||||
bordered={false}
|
||||
contentClassName="min-h-(--sz-120px) text-sm leading-7"
|
||||
mentions={mentionOptions}
|
||||
onSubmit={() => {
|
||||
if (!saveRoutine.isPending && editDraft.title.trim()) {
|
||||
saveRoutine.mutate();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</IssueDocumentAnnotations>
|
||||
) : (
|
||||
<MarkdownEditor
|
||||
ref={descriptionEditorRef}
|
||||
value={editDraft.description}
|
||||
onChange={(description) => setEditDraft((current) => ({ ...current, description }))}
|
||||
placeholder="Add instructions..."
|
||||
bordered={false}
|
||||
contentClassName="min-h-(--sz-120px) text-sm leading-7"
|
||||
mentions={mentionOptions}
|
||||
onSubmit={() => {
|
||||
if (!saveRoutine.isPending && editDraft.title.trim()) {
|
||||
saveRoutine.mutate();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Variables peek */}
|
||||
<div className="space-y-3">
|
||||
<RoutineVariablesHint />
|
||||
<RoutineVariablesEditor
|
||||
title={editDraft.title}
|
||||
description={editDraft.description}
|
||||
value={editDraft.variables}
|
||||
onChange={(variables) => setEditDraft((current) => ({ ...current, variables }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Summary cards */}
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<SummaryCard
|
||||
icon={Clock3}
|
||||
label="Triggers"
|
||||
value={activeTriggers === 0 ? "None" : `${activeTriggers} active`}
|
||||
hint={nextFire ? `Next fire ${nextFire}` : "No schedule"}
|
||||
to={() => navigateToSection("triggers")}
|
||||
ariaLabel={`${activeTriggers} triggers. Open triggers.`}
|
||||
/>
|
||||
<SummaryCard
|
||||
icon={Play}
|
||||
label="Last run"
|
||||
value={lastRun ? lastRun.status.replaceAll("_", " ") : "No runs"}
|
||||
hint={lastRun ? timeAgo(lastRun.triggeredAt) : "Trigger a run"}
|
||||
to={() => navigateToSection("runs")}
|
||||
ariaLabel={lastRun ? `Last run ${lastRun.status}. Open runs.` : "No runs. Open runs."}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Recent activity */}
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Recent activity
|
||||
</p>
|
||||
{recentActivity.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">No activity yet.</p>
|
||||
) : (
|
||||
<div className="divide-y divide-border/60">
|
||||
{recentActivity.map((event) => (
|
||||
<div key={event.id} className="flex items-center gap-2 py-1.5 text-xs">
|
||||
<Badge variant="outline" className="shrink-0 font-mono">
|
||||
{event.action}
|
||||
</Badge>
|
||||
<span className="min-w-0 flex-1 truncate text-muted-foreground">
|
||||
{event.details && Object.keys(event.details).length > 0
|
||||
? Object.keys(event.details).slice(0, 3).join(" · ")
|
||||
: ""}
|
||||
</span>
|
||||
<span className="shrink-0 text-muted-foreground/60">{timeAgo(event.createdAt)}</span>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigateToSection("activity")}
|
||||
className="flex items-center gap-1 pt-2 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
View all activity <ArrowRight className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SummaryCard({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
hint,
|
||||
to,
|
||||
ariaLabel,
|
||||
}: {
|
||||
icon: typeof Clock3;
|
||||
label: string;
|
||||
value: string;
|
||||
hint: string;
|
||||
to: () => void;
|
||||
ariaLabel: string;
|
||||
}) {
|
||||
return (
|
||||
<button type="button" onClick={to} aria-label={ariaLabel} className="text-left">
|
||||
<Card className="gap-2 p-4 transition-colors hover:border-border hover:bg-accent/30">
|
||||
<CardContent className="space-y-1 p-0">
|
||||
<div className="flex items-center gap-1.5 text-xs uppercase tracking-wide text-muted-foreground">
|
||||
<Icon className="h-3.5 w-3.5" />
|
||||
{label}
|
||||
<ArrowRight className="ml-auto h-3.5 w-3.5 text-muted-foreground/60" />
|
||||
</div>
|
||||
<p className="text-lg font-semibold">{value}</p>
|
||||
<p className="text-xs text-muted-foreground">{hint}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export { RoutineTriggers as TriggersSection } from "../routine-triggers/RoutineTriggers";
|
||||
|
||||
export function VariablesSection() {
|
||||
const ctx = useRoutineDetail();
|
||||
const { editDraft, setEditDraft, navigateToSection } = ctx;
|
||||
const hasVariables = editDraft.variables.length > 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-3 rounded-md border border-border bg-muted/20 px-4 py-3 text-xs">
|
||||
<span className="flex-1 text-muted-foreground">
|
||||
Variables are auto-detected from <code className="font-mono">{"{{placeholders}}"}</code> in
|
||||
the title & instructions. The variable name is read-only — rename by editing the
|
||||
placeholder.
|
||||
</span>
|
||||
<Button variant="secondary" size="sm" onClick={() => navigateToSection("overview")}>
|
||||
<Edit3 className="mr-1.5 h-3.5 w-3.5" />
|
||||
Edit instructions
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{hasVariables ? (
|
||||
<RoutineVariablesEditor
|
||||
title={editDraft.title}
|
||||
description={editDraft.description}
|
||||
value={editDraft.variables}
|
||||
onChange={(variables) => setEditDraft((current) => ({ ...current, variables }))}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState
|
||||
icon={Braces}
|
||||
message="No variables yet. Add a {{placeholder}} in the title or instructions to create one."
|
||||
action="Edit instructions"
|
||||
onAction={() => navigateToSection("overview")}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SecretsSection() {
|
||||
const ctx = useRoutineDetail();
|
||||
const { editDraft, setEditDraft, availableSecrets, createSecret } = ctx;
|
||||
|
||||
// Project/company-scoped secrets that already see real usage, surfaced as
|
||||
// quick-bind chips (§3.4). Ranked by reference count then recency.
|
||||
const recentlyUsedSecrets = useMemo(
|
||||
() =>
|
||||
[...availableSecrets]
|
||||
.filter((secret) => secret.status === "active")
|
||||
.sort((a, b) => {
|
||||
const refDelta = (b.referenceCount ?? 0) - (a.referenceCount ?? 0);
|
||||
if (refDelta !== 0) return refDelta;
|
||||
return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
|
||||
})
|
||||
.slice(0, 8),
|
||||
[availableSecrets],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-md border border-border bg-muted/20 px-4 py-3 text-xs text-muted-foreground">
|
||||
Routine secrets apply to every task this routine creates. They override matching keys in
|
||||
project and agent env. <span className="font-mono">PAPERCLIP_*</span> names are reserved.
|
||||
</div>
|
||||
|
||||
|
||||
<EnvironmentVariablesEditor
|
||||
value={(editDraft.env ?? {}) as Record<string, EnvBinding>}
|
||||
secrets={availableSecrets}
|
||||
recentlyUsedSecrets={recentlyUsedSecrets}
|
||||
onCreateSecret={async (name, value) => createSecret.mutateAsync({ name, value })}
|
||||
onChange={(env) => setEditDraft((current) => ({ ...current, env: env ?? null }))}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DeliverySection() {
|
||||
const ctx = useRoutineDetail();
|
||||
const { editDraft, setEditDraft, routine } = ctx;
|
||||
|
||||
// The activity gate only affects schedule ticks (webhook/manual/API fires are
|
||||
// themselves activity and always run), so the control is only meaningful for
|
||||
// routines that have a schedule trigger. Disable — rather than hide — it
|
||||
// elsewhere so the capability stays discoverable.
|
||||
const hasScheduleTrigger = routine.triggers.some((trigger) => trigger.kind === "schedule");
|
||||
const gateEnabled = editDraft.activityGatePolicy === "require_external_activity";
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-3">
|
||||
<p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">
|
||||
Concurrency
|
||||
</p>
|
||||
<RadioCardGroup
|
||||
ariaLabel="Concurrency policy"
|
||||
value={editDraft.concurrencyPolicy}
|
||||
onValueChange={(concurrencyPolicy) =>
|
||||
setEditDraft((current) => ({ ...current, concurrencyPolicy }))
|
||||
}
|
||||
options={concurrencyPolicyOptions}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">
|
||||
Catch-up
|
||||
</p>
|
||||
<RadioCardGroup
|
||||
ariaLabel="Catch-up policy"
|
||||
value={editDraft.catchUpPolicy}
|
||||
onValueChange={(catchUpPolicy) =>
|
||||
setEditDraft((current) => ({ ...current, catchUpPolicy }))
|
||||
}
|
||||
options={catchUpPolicyOptions}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">
|
||||
Advanced run policy
|
||||
</p>
|
||||
<RadioCardGroup
|
||||
ariaLabel="Advanced run policy"
|
||||
value={editDraft.activityGatePolicy}
|
||||
onValueChange={(activityGatePolicy) =>
|
||||
setEditDraft((current) => ({ ...current, activityGatePolicy }))
|
||||
}
|
||||
options={activityGatePolicyOptions}
|
||||
disabled={!hasScheduleTrigger}
|
||||
/>
|
||||
{!hasScheduleTrigger ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Add a schedule trigger to gate runs on activity. Webhook, manual, and API fires always
|
||||
run.
|
||||
</p>
|
||||
) : gateEnabled ? (
|
||||
<div className="space-y-2 rounded-lg border border-border p-3">
|
||||
<Label className="text-xs font-medium">Activity scope</Label>
|
||||
<RadioCardGroup
|
||||
ariaLabel="Activity gate scope"
|
||||
value={editDraft.activityGateScope}
|
||||
onValueChange={(activityGateScope) =>
|
||||
setEditDraft((current) => ({ ...current, activityGateScope }))
|
||||
}
|
||||
options={activityGateScopeOptions}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<NextFiresPreview
|
||||
triggers={routine.triggers}
|
||||
concurrencyPolicy={editDraft.concurrencyPolicy}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const dispositionToneClass: Record<string, string> = {
|
||||
queued: "text-emerald-600 dark:text-emerald-400",
|
||||
coalesced: "text-amber-600 dark:text-amber-400",
|
||||
skipped: "text-muted-foreground",
|
||||
};
|
||||
|
||||
/**
|
||||
* "Next 5 fires" preview (§3.5) — the strongest "what does this policy mean?"
|
||||
* surface. Picks the soonest-firing schedule trigger, computes its next fires
|
||||
* client-side, and annotates each with how the chosen concurrency policy would
|
||||
* treat it.
|
||||
*/
|
||||
function NextFiresPreview({
|
||||
triggers,
|
||||
concurrencyPolicy,
|
||||
}: {
|
||||
triggers: RoutineDetailType["triggers"];
|
||||
concurrencyPolicy: string;
|
||||
}) {
|
||||
const preview = useMemo(() => {
|
||||
const schedule = triggers
|
||||
.filter((trigger) => trigger.kind === "schedule" && trigger.enabled && trigger.cronExpression)
|
||||
.map((trigger) => {
|
||||
const fires = nextCronFires(trigger.cronExpression, 5, {
|
||||
timeZone: trigger.timezone ?? "UTC",
|
||||
});
|
||||
return { trigger, fires };
|
||||
})
|
||||
.filter((entry) => entry.fires.length > 0)
|
||||
.sort((a, b) => a.fires[0]!.getTime() - b.fires[0]!.getTime())[0];
|
||||
if (!schedule) return null;
|
||||
return {
|
||||
timeZone: schedule.trigger.timezone ?? "UTC",
|
||||
entries: previewFirePolicies(schedule.fires, concurrencyPolicy),
|
||||
};
|
||||
}, [triggers, concurrencyPolicy]);
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">
|
||||
Next 5 fires
|
||||
</p>
|
||||
{preview ? (
|
||||
<>
|
||||
<div className="space-y-1.5 rounded-lg border border-border p-3 font-mono text-xs">
|
||||
{preview.entries.map((entry, index) => (
|
||||
<div key={index} className="flex items-center gap-2">
|
||||
<span className="text-muted-foreground/40">·</span>
|
||||
<span className="tabular-nums">{formatFireTime(entry.at, preview.timeZone)}</span>
|
||||
<ArrowRight className="h-3 w-3 shrink-0 text-muted-foreground/50" />
|
||||
<span className={cn("font-medium", dispositionToneClass[entry.disposition])}>
|
||||
{entry.label}
|
||||
</span>
|
||||
{entry.note ? (
|
||||
<span className="truncate text-muted-foreground/60">({entry.note})</span>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-(length:--text-micro) text-muted-foreground/60">
|
||||
Preview assumes the previous run is still in flight when the next fires. Times shown in{" "}
|
||||
{preview.timeZone}.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="rounded-lg border border-dashed border-border p-3 text-xs text-muted-foreground">
|
||||
No enabled schedule trigger to preview. Add a schedule in Triggers to see how this policy
|
||||
treats upcoming fires.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatFireTime(date: Date, timeZone: string): string {
|
||||
try {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
timeZone,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hourCycle: "h23",
|
||||
})
|
||||
.format(date)
|
||||
.replace(",", "");
|
||||
} catch {
|
||||
return date.toISOString();
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { RunsSection, ActivitySection } from "./operate-sections";
|
||||
import { RoutineDetailContext, type RoutineDetailContextValue } from "./context";
|
||||
|
||||
const { list, update, renderList, toast } = vi.hoisted(() => ({
|
||||
list: vi.fn(), update: vi.fn(), renderList: vi.fn(), toast: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/api/issues", () => ({ issuesApi: { list, update } }));
|
||||
vi.mock("@/context/ToastContext", () => ({ useToastActions: () => ({ pushToast: toast }) }));
|
||||
vi.mock("../IssuesList", () => ({ IssuesList: (props: unknown) => { renderList(props); return <div>Issue list</div>; } }));
|
||||
vi.mock("../RoutineHistoryTab", () => ({ RoutineHistoryTab: () => null }));
|
||||
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
let queryClient: QueryClient;
|
||||
const context = {
|
||||
companyId: "company-1", routine: { id: "routine-1" }, agents: [], projects: [], activity: [],
|
||||
} as unknown as RoutineDetailContextValue;
|
||||
function render(section = <RunsSection />) {
|
||||
flushSync(() => root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RoutineDetailContext.Provider value={context}>{section}</RoutineDetailContext.Provider>
|
||||
</QueryClientProvider>,
|
||||
));
|
||||
}
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
});
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
queryClient.clear();
|
||||
container.remove();
|
||||
});
|
||||
|
||||
describe("routine operations", () => {
|
||||
it("passes a settled initial 429 and a working retry to the runs list", async () => {
|
||||
list.mockRejectedValueOnce(new ApiError("rate_limited", 429, null)).mockResolvedValueOnce([{ id: "recovered-run" }]);
|
||||
render();
|
||||
await vi.waitFor(() => expect(renderList.mock.lastCall?.[0].error?.status).toBe(429));
|
||||
expect(renderList.mock.lastCall?.[0].issues).toEqual([]);
|
||||
renderList.mock.lastCall?.[0].onRetry();
|
||||
await vi.waitFor(() => expect(renderList.mock.lastCall?.[0].issues).toEqual([{ id: "recovered-run" }]));
|
||||
expect(renderList.mock.lastCall?.[0].error).toBeNull();
|
||||
});
|
||||
|
||||
it("loads this routine's execution issues and keeps list search scoped to the same routine", async () => {
|
||||
const issues = [{ id: "execution-1", title: "Check deployment", status: "done" }];
|
||||
list.mockResolvedValue(issues);
|
||||
render();
|
||||
await vi.waitFor(() => expect(renderList.mock.lastCall?.[0].issues).toEqual(issues));
|
||||
expect(list).toHaveBeenCalledWith("company-1", { originKind: "routine_execution", originId: "routine-1" });
|
||||
expect(renderList.mock.lastCall?.[0].searchFilters).toEqual({ originKind: "routine_execution", originId: "routine-1" });
|
||||
expect(renderList.mock.lastCall?.[0].issueLinkState.issueDetailBreadcrumb.href).toBe("/routines/routine-1/runs");
|
||||
});
|
||||
|
||||
it("surfaces issue loading and update failures", async () => {
|
||||
list.mockRejectedValue(new Error("Could not load execution issues"));
|
||||
render();
|
||||
await vi.waitFor(() => expect(renderList.mock.lastCall?.[0].error?.message).toBe("Could not load execution issues"));
|
||||
update.mockRejectedValue(new Error("Update denied"));
|
||||
renderList.mock.lastCall?.[0].onUpdateIssue("execution-1", { status: "done" });
|
||||
await vi.waitFor(() => expect(toast).toHaveBeenCalledWith(expect.objectContaining({ body: "Update denied", tone: "error" })));
|
||||
});
|
||||
|
||||
it("distinguishes activity loading and failures from an empty timeline", () => {
|
||||
render(<ActivitySection isLoading />);
|
||||
expect(container.textContent).toContain("Loading activity");
|
||||
expect(container.textContent).not.toContain("No activity yet");
|
||||
render(<ActivitySection error={new Error("Activity unavailable")} />);
|
||||
const alert = container.querySelector('[role="alert"]');
|
||||
expect(alert?.textContent).toContain("Couldn't load routine activity");
|
||||
expect(alert?.textContent).toContain("Activity unavailable");
|
||||
});
|
||||
});
|
||||
@@ -1,162 +0,0 @@
|
||||
import { useMemo } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Activity as ActivityIcon } from "lucide-react";
|
||||
import { describeError } from "@/api/errors";
|
||||
import { issuesApi } from "@/api/issues";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { routineDetailHref } from "../RoutineContextualSidebar";
|
||||
import { createIssueDetailLocationState } from "@/lib/issueDetailBreadcrumb";
|
||||
import { useToastActions } from "@/context/ToastContext";
|
||||
import { IssuesList } from "../IssuesList";
|
||||
import { EmptyState } from "../EmptyState";
|
||||
import { QueryErrorState, useQueryView } from "../QueryView";
|
||||
import { RoutineHistoryTab } from "../RoutineHistoryTab";
|
||||
import { RoutineActivityRow } from "../RoutineActivityRow";
|
||||
import { useRoutineDetail } from "./context";
|
||||
|
||||
export function RunsSection() {
|
||||
const { routine, companyId, agents, projects, hasLiveRun, activeIssueId } = useRoutineDetail();
|
||||
const queryClient = useQueryClient();
|
||||
const { pushToast } = useToastActions();
|
||||
const filters = { originKind: "routine_execution", originId: routine.id };
|
||||
const issueQueryKey = [...queryKeys.issues.list(companyId), "routine", routine.id];
|
||||
const issuesQuery = useQuery({
|
||||
queryKey: issueQueryKey,
|
||||
queryFn: () => issuesApi.list(companyId, filters),
|
||||
});
|
||||
const { data: issues, isLoading } = issuesQuery;
|
||||
const issuesView = useQueryView(issuesQuery);
|
||||
const updateIssue = useMutation({
|
||||
mutationFn: ({ id, data }: { id: string; data: Record<string, unknown> }) => issuesApi.update(id, data),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(companyId) });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.routines.detail(routine.id) });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.routines.runs(routine.id) });
|
||||
},
|
||||
onError: (updateError) => pushToast({ title: "Failed to update task", body: describeError(updateError).body, tone: "error" }),
|
||||
});
|
||||
|
||||
return (
|
||||
<IssuesList
|
||||
issues={issues ?? []}
|
||||
isLoading={isLoading || issuesView.kind === "reconnecting"}
|
||||
error={issuesView.kind === "error" ? (issuesView.error as Error) : null}
|
||||
onRetry={issuesView.retry}
|
||||
retrying={issuesView.isFetching}
|
||||
agents={agents}
|
||||
projects={projects}
|
||||
liveIssueIds={new Set(hasLiveRun && activeIssueId ? [activeIssueId] : [])}
|
||||
viewStateKey={`paperclip:routine-runs:${companyId}:${routine.id}`}
|
||||
searchFilters={filters}
|
||||
issueLinkState={createIssueDetailLocationState("Runs", routineDetailHref(routine.id, "runs"))}
|
||||
rowPresentation="task"
|
||||
toolbarPresentation="collection"
|
||||
onUpdateIssue={(id, data) => updateIssue.mutate({ id, data })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ActivitySection({
|
||||
isLoading = false,
|
||||
error,
|
||||
onRetry,
|
||||
retrying = false,
|
||||
}: {
|
||||
isLoading?: boolean;
|
||||
error?: unknown;
|
||||
onRetry?: () => void;
|
||||
retrying?: boolean;
|
||||
} = {}) {
|
||||
const ctx = useRoutineDetail();
|
||||
const { activity } = ctx;
|
||||
const events = activity ?? [];
|
||||
|
||||
const groups = useMemo(() => {
|
||||
const byDay = new Map<string, typeof events>();
|
||||
for (const event of events) {
|
||||
let label = "Earlier";
|
||||
try {
|
||||
label = new Date(event.createdAt).toLocaleDateString(undefined, {
|
||||
weekday: "short",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
});
|
||||
} catch {
|
||||
/* keep fallback label */
|
||||
}
|
||||
const bucket = byDay.get(label) ?? [];
|
||||
bucket.push(event);
|
||||
byDay.set(label, bucket);
|
||||
}
|
||||
return Array.from(byDay.entries());
|
||||
}, [events]);
|
||||
|
||||
if (isLoading) return <p className="text-sm text-muted-foreground">Loading activity…</p>;
|
||||
if (error) {
|
||||
return (
|
||||
<QueryErrorState
|
||||
error={error}
|
||||
action="load routine activity"
|
||||
onRetry={onRetry}
|
||||
retrying={retrying}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (events.length === 0) {
|
||||
return <EmptyState icon={ActivityIcon} message="No activity yet." />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{groups.map(([day, dayEvents]) => (
|
||||
<div key={day}>
|
||||
<div className="sticky top-0 bg-background py-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
{day}
|
||||
</div>
|
||||
<div>
|
||||
{dayEvents.map((event) => (
|
||||
<RoutineActivityRow key={event.id} event={event} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function HistorySection() {
|
||||
const ctx = useRoutineDetail();
|
||||
const {
|
||||
routine,
|
||||
isEditDirty,
|
||||
dirtyFields,
|
||||
routineDefaults,
|
||||
setEditDraft,
|
||||
saveRoutine,
|
||||
agentById,
|
||||
projectById,
|
||||
availableSecrets,
|
||||
onHistoryRestoreSecretMaterials,
|
||||
onHistoryRestored,
|
||||
} = ctx;
|
||||
|
||||
return (
|
||||
<RoutineHistoryTab
|
||||
routine={routine}
|
||||
isEditDirty={isEditDirty}
|
||||
dirtyFields={dirtyFields}
|
||||
onDiscardEdits={() => setEditDraft(routineDefaults)}
|
||||
onSaveEdits={() => {
|
||||
if (!saveRoutine.isPending && routine.title.trim()) {
|
||||
saveRoutine.mutate();
|
||||
}
|
||||
}}
|
||||
agents={agentById}
|
||||
projects={projectById}
|
||||
secrets={availableSecrets}
|
||||
onRestoreSecretMaterials={onHistoryRestoreSecretMaterials}
|
||||
onRestored={onHistoryRestored}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,668 +0,0 @@
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { CalendarClock, Plus, Radar, Webhook } from "lucide-react";
|
||||
import type { RoutineTrigger } from "@paperclipai/shared";
|
||||
import { useSearchParams } from "@/lib/router";
|
||||
import { routinesApi } from "@/api/routines";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { describeCron } from "@/lib/cron-readable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from "@/components/ui/dialog";
|
||||
import { ScheduleEditor } from "@/components/ScheduleEditor";
|
||||
import { useRoutineDetail } from "@/components/routine-sections/context";
|
||||
import { RoutineTriggerCard } from "./TriggerCard";
|
||||
import {
|
||||
RoutineTriggerWizard,
|
||||
defaultTriggerDraft,
|
||||
webhookAgentInstructions,
|
||||
type TriggerDraft,
|
||||
} from "./TriggerWizard";
|
||||
import { AgentInstructions, CopyField } from "./WebhookFields";
|
||||
import { WebhookUrlWarning } from "./WebhookUrlWarning";
|
||||
|
||||
function readDraft(key: string): TriggerDraft | null {
|
||||
try {
|
||||
const draft = JSON.parse(sessionStorage.getItem(key) ?? "null");
|
||||
return draft && ["choose", "schedule", "webhook"].includes(draft.kind)
|
||||
? { ...defaultTriggerDraft, ...draft, sender: draft.sender === "github" ? "github" : "custom" }
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
function saveDraft(key: string, draft: TriggerDraft) {
|
||||
// Only setup choices are persisted. The one-time key stays in component memory.
|
||||
try {
|
||||
sessionStorage.setItem(key, JSON.stringify(draft));
|
||||
} catch {
|
||||
throw new Error(
|
||||
"Couldn’t save your draft in this browser. Keep this page open and try again.",
|
||||
);
|
||||
}
|
||||
}
|
||||
function scheduleCron(draft: TriggerDraft) {
|
||||
const [hour, minute] = draft.time.split(":").map(Number);
|
||||
const day = [
|
||||
"Sunday",
|
||||
"Monday",
|
||||
"Tuesday",
|
||||
"Wednesday",
|
||||
"Thursday",
|
||||
"Friday",
|
||||
"Saturday",
|
||||
].indexOf(draft.weekday);
|
||||
return `${minute} ${hour} * * ${draft.frequency === "daily" ? "*" : draft.frequency === "weekly" ? day : "1-5"}`;
|
||||
}
|
||||
|
||||
export function RoutineTriggers() {
|
||||
const ctx = useRoutineDetail();
|
||||
const [params, setParams] = useSearchParams();
|
||||
const setupId = params.get("triggerSetup");
|
||||
const client = useQueryClient();
|
||||
const { data, error: statusError } = useQuery({
|
||||
queryKey: queryKeys.routines.detail(ctx.routineId),
|
||||
queryFn: () => routinesApi.get(ctx.routineId),
|
||||
refetchInterval: 3000,
|
||||
});
|
||||
const routine = data ?? ctx.routine;
|
||||
const [expanded, setExpanded] = useState<string | null>(null);
|
||||
const [removed, setRemoved] = useState<RoutineTrigger[]>([]);
|
||||
const [error, setError] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const refresh = useCallback(async () => {
|
||||
await client.invalidateQueries({ queryKey: ["routines"] });
|
||||
}, [client]);
|
||||
const change = async (action: () => Promise<void>) => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
await action();
|
||||
await refresh();
|
||||
} catch (cause) {
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: "Couldn’t save the trigger. Please try again.",
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const startSetup = (id: string) => setParams({ triggerSetup: id });
|
||||
const closeSetup = useCallback(() => setParams({}), [setParams]);
|
||||
if (setupId) {
|
||||
const trigger = routine.triggers.find((item) => item.id === setupId);
|
||||
if (setupId !== "new" && !trigger)
|
||||
return (
|
||||
<p role="alert">
|
||||
This trigger is no longer available.{" "}
|
||||
<Button variant="link" onClick={closeSetup}>
|
||||
Back to triggers
|
||||
</Button>
|
||||
</p>
|
||||
);
|
||||
if (trigger && !trigger.setupPending)
|
||||
return (
|
||||
<p>
|
||||
This trigger is ready.{" "}
|
||||
<Button variant="link" onClick={closeSetup}>
|
||||
Back to triggers
|
||||
</Button>
|
||||
</p>
|
||||
);
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{statusError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
Connection status is unavailable. Retrying…
|
||||
</p>
|
||||
)}
|
||||
<TriggerSetup
|
||||
key={routine.id}
|
||||
routineId={routine.id}
|
||||
companyId={routine.companyId}
|
||||
routineTitle={routine.title}
|
||||
trigger={trigger}
|
||||
onExit={closeSetup}
|
||||
onRefresh={refresh}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{routine.triggers.length}{" "}
|
||||
{routine.triggers.length === 1 ? "trigger" : "triggers"}
|
||||
</p>
|
||||
<Button size="sm" onClick={() => startSetup("new")}>
|
||||
<Plus className="mr-1.5 h-3.5 w-3.5" />
|
||||
Add trigger
|
||||
</Button>
|
||||
</div>
|
||||
{(error || statusError) && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error || "Connection status is unavailable. Retrying…"}
|
||||
</p>
|
||||
)}
|
||||
{removed.map((trigger) => (
|
||||
<div
|
||||
key={trigger.id}
|
||||
role="status"
|
||||
className="flex items-center gap-3 rounded-md bg-muted/40 px-4 py-3 text-sm"
|
||||
>
|
||||
<span className="flex-1">
|
||||
{trigger.kind === "schedule"
|
||||
? "Schedule"
|
||||
: trigger.kind === "api"
|
||||
? "API trigger"
|
||||
: trigger.kind === "heartbeat"
|
||||
? "Standing check"
|
||||
: "Webhook"}{" "}
|
||||
removed.
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void change(async () => {
|
||||
await routinesApi.updateTrigger(trigger.id, {
|
||||
archived: false,
|
||||
});
|
||||
setRemoved((items) =>
|
||||
items.filter((item) => item.id !== trigger.id),
|
||||
);
|
||||
})
|
||||
}
|
||||
>
|
||||
Undo
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
{ctx.secretMessage && (
|
||||
<div className="space-y-3 rounded-md border p-4">
|
||||
<p className="text-sm font-medium">{ctx.secretMessage.title}</p>
|
||||
{ctx.secretMessage.entries.map((entry) => (
|
||||
<div key={entry.webhookUrl} className="space-y-3">
|
||||
<CopyField label="Webhook URL" value={entry.webhookUrl} />
|
||||
<CopyField label="Secret key" value={entry.webhookSecret} />
|
||||
</div>
|
||||
))}
|
||||
<Button variant="outline" onClick={() => ctx.setSecretMessage(null)}>
|
||||
Done
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{routine.triggers.length === 0 && (
|
||||
<p className="py-6 text-sm text-muted-foreground">
|
||||
Run this routine on a schedule or when another app sends a webhook.
|
||||
</p>
|
||||
)}
|
||||
<fieldset disabled={busy} className="min-w-0 space-y-3">
|
||||
{routine.triggers.map((trigger) => (
|
||||
<RoutineTriggerCard
|
||||
key={trigger.id}
|
||||
kind={
|
||||
trigger.kind === "schedule"
|
||||
? "schedule"
|
||||
: trigger.kind === "api"
|
||||
? "api"
|
||||
: trigger.kind === "heartbeat"
|
||||
? "heartbeat"
|
||||
: "webhook"
|
||||
}
|
||||
icon={
|
||||
trigger.kind === "schedule" ? (
|
||||
<CalendarClock className="h-4 w-4" />
|
||||
) : trigger.kind === "heartbeat" ? (
|
||||
<Radar className="h-4 w-4" />
|
||||
) : (
|
||||
<Webhook className="h-4 w-4" />
|
||||
)
|
||||
}
|
||||
title={
|
||||
trigger.kind === "schedule"
|
||||
? (describeCron(trigger.cronExpression) ?? "Schedule")
|
||||
: trigger.kind === "api"
|
||||
? "API trigger"
|
||||
: trigger.kind === "heartbeat"
|
||||
? "Standing check"
|
||||
: trigger.signingMode === "github_hmac"
|
||||
? "GitHub webhook"
|
||||
: "Webhook"
|
||||
}
|
||||
summary={
|
||||
trigger.setupPending
|
||||
? "Setup unfinished · Events only test the connection"
|
||||
: !trigger.enabled
|
||||
? "Paused"
|
||||
: trigger.kind === "schedule"
|
||||
? (trigger.timezone ?? "UTC")
|
||||
: trigger.kind === "api"
|
||||
? "Run through the API"
|
||||
: trigger.kind === "heartbeat"
|
||||
? trigger.lastResult ? `On each wake-up · Last: ${trigger.lastResult}` : "On each wake-up · Not checked yet"
|
||||
: trigger.lastWebhookDelivery?.status === "rejected"
|
||||
? "Authentication failed · Check the key in your app"
|
||||
: trigger.lastWebhookDelivery?.status === "received" &&
|
||||
!trigger.lastWebhookDelivery.test
|
||||
? "Receiving events"
|
||||
: "Ready · Waiting for an event"
|
||||
}
|
||||
expanded={expanded === trigger.id}
|
||||
editLabel={trigger.setupPending ? "Resume setup" : undefined}
|
||||
onEdit={() =>
|
||||
trigger.setupPending
|
||||
? startSetup(trigger.id)
|
||||
: setExpanded((id) => (id === trigger.id ? null : trigger.id))
|
||||
}
|
||||
onRemove={() =>
|
||||
void change(async () => {
|
||||
await routinesApi.updateTrigger(trigger.id, { archived: true });
|
||||
setRemoved((items) => [...items, trigger]);
|
||||
})
|
||||
}
|
||||
>
|
||||
{trigger.setupPending ? (
|
||||
<Button onClick={() => startSetup(trigger.id)}>
|
||||
Resume setup
|
||||
</Button>
|
||||
) : trigger.kind === "schedule" ? (
|
||||
<ScheduleSettings
|
||||
trigger={trigger}
|
||||
onSave={async (patch) => {
|
||||
await routinesApi.updateTrigger(trigger.id, patch);
|
||||
await refresh();
|
||||
setExpanded(null);
|
||||
}}
|
||||
onCancel={() => setExpanded(null)}
|
||||
/>
|
||||
) : trigger.kind === "api" ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This trigger starts the routine through the API.
|
||||
</p>
|
||||
) : trigger.kind === "heartbeat" ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
A standing check: the routine’s agent carries out these instructions each time its heartbeat wakes it, and reports what it found. It never creates a task by itself.
|
||||
</p>
|
||||
) : (
|
||||
<WebhookSettings
|
||||
trigger={trigger}
|
||||
routineTitle={routine.title}
|
||||
onRefresh={refresh}
|
||||
/>
|
||||
)}
|
||||
{!trigger.setupPending && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
void change(async () => {
|
||||
await routinesApi.updateTrigger(trigger.id, {
|
||||
enabled: !trigger.enabled,
|
||||
});
|
||||
})
|
||||
}
|
||||
>
|
||||
{trigger.enabled ? "Pause trigger" : "Enable trigger"}
|
||||
</Button>
|
||||
)}
|
||||
</RoutineTriggerCard>
|
||||
))}
|
||||
</fieldset>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TriggerSetup({
|
||||
routineId,
|
||||
companyId,
|
||||
routineTitle,
|
||||
trigger,
|
||||
onExit,
|
||||
onRefresh,
|
||||
}: {
|
||||
routineId: string;
|
||||
companyId: string;
|
||||
routineTitle: string;
|
||||
trigger?: RoutineTrigger;
|
||||
onExit: () => void;
|
||||
onRefresh: () => Promise<void>;
|
||||
}) {
|
||||
const [, setParams] = useSearchParams();
|
||||
const storagePrefix = `routine-trigger-draft:${companyId}:${routineId}:`;
|
||||
const createdRef = useRef<RoutineTrigger | undefined>(trigger);
|
||||
const [created, setCreated] = useState(trigger);
|
||||
const [secret, setSecret] = useState("");
|
||||
const currentTrigger = trigger ?? created;
|
||||
const [initialDraft] = useState<TriggerDraft>(() => {
|
||||
const saved = readDraft(storagePrefix + (trigger?.id ?? "new"));
|
||||
if (trigger)
|
||||
return {
|
||||
...defaultTriggerDraft,
|
||||
...saved,
|
||||
kind: "webhook",
|
||||
sender: trigger.signingMode === "github_hmac" ? "github" : "custom",
|
||||
signingMode: trigger.signingMode === "bearer" ? "bearer" : trigger.signingMode === "fireflies_hmac" ? "fireflies_hmac" : "app_webhook",
|
||||
created: true,
|
||||
step: saved?.step ?? 1,
|
||||
availableStep: Math.max(1, saved?.availableStep ?? 1),
|
||||
};
|
||||
return (
|
||||
saved ?? {
|
||||
...defaultTriggerDraft,
|
||||
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
created: false,
|
||||
}
|
||||
);
|
||||
});
|
||||
const createWebhook = useCallback(
|
||||
async (draft: TriggerDraft) => {
|
||||
if (createdRef.current) return;
|
||||
const response = await routinesApi.createTrigger(routineId, {
|
||||
kind: "webhook",
|
||||
signingMode: draft.sender === "github" ? "github_hmac" : "app_webhook",
|
||||
setupPending: true,
|
||||
});
|
||||
createdRef.current = response.trigger;
|
||||
setCreated({
|
||||
...response.trigger,
|
||||
webhookUrl:
|
||||
response.secretMaterial?.webhookUrl ?? response.trigger.webhookUrl,
|
||||
});
|
||||
setSecret(response.secretMaterial?.webhookSecret ?? "");
|
||||
saveDraft(storagePrefix + response.trigger.id, {
|
||||
...draft,
|
||||
created: true,
|
||||
step: 1,
|
||||
availableStep: 1,
|
||||
});
|
||||
sessionStorage.removeItem(storagePrefix + "new");
|
||||
await onRefresh();
|
||||
setParams({ triggerSetup: response.trigger.id }, { replace: true });
|
||||
},
|
||||
[routineId, onRefresh, storagePrefix, setParams],
|
||||
);
|
||||
const saveExit = useCallback(
|
||||
(draft: TriggerDraft) => {
|
||||
saveDraft(storagePrefix + (createdRef.current?.id ?? "new"), draft);
|
||||
onExit();
|
||||
},
|
||||
[onExit, storagePrefix],
|
||||
);
|
||||
const finish = useCallback(
|
||||
async (draft: TriggerDraft) => {
|
||||
if (draft.kind === "schedule")
|
||||
await routinesApi.createTrigger(routineId, {
|
||||
kind: "schedule",
|
||||
cronExpression: scheduleCron(draft),
|
||||
timezone: draft.timezone,
|
||||
});
|
||||
else {
|
||||
if (!createdRef.current)
|
||||
throw new Error("Create the webhook before finishing setup.");
|
||||
await routinesApi.updateTrigger(createdRef.current.id, {
|
||||
setupPending: false,
|
||||
});
|
||||
}
|
||||
try {
|
||||
sessionStorage.removeItem(
|
||||
storagePrefix + (createdRef.current?.id ?? "new"),
|
||||
);
|
||||
} catch {
|
||||
// The server mutation succeeded; draft cleanup must not cause a retry.
|
||||
}
|
||||
await onRefresh();
|
||||
onExit();
|
||||
},
|
||||
[routineId, onRefresh, onExit, storagePrefix],
|
||||
);
|
||||
const { routine: currentRoutine } = useRoutineDetail();
|
||||
return (
|
||||
<RoutineTriggerWizard
|
||||
initialDraft={initialDraft}
|
||||
routineTitle={routineTitle}
|
||||
routineId={routineId}
|
||||
routineActive={currentRoutine.status === "active"}
|
||||
webhookUrl={currentTrigger?.webhookUrl ?? ""}
|
||||
webhookSecret={secret}
|
||||
onCreateWebhook={createWebhook}
|
||||
onSaveExit={saveExit}
|
||||
onFinish={finish}
|
||||
onRotateKey={async () => {
|
||||
if (!createdRef.current) return;
|
||||
const response = await routinesApi.rotateTriggerSecret(
|
||||
createdRef.current.id,
|
||||
);
|
||||
setSecret(response.secretMaterial.webhookSecret);
|
||||
await onRefresh();
|
||||
}}
|
||||
checkResult={currentTrigger?.lastWebhookDelivery?.status ?? "waiting"}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ScheduleSettings({
|
||||
trigger,
|
||||
onSave,
|
||||
onCancel,
|
||||
}: {
|
||||
trigger: RoutineTrigger;
|
||||
onSave: (patch: Record<string, unknown>) => Promise<void>;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const [cronExpression, setCron] = useState(
|
||||
trigger.cronExpression ?? "0 9 * * *",
|
||||
);
|
||||
const [timezone, setTimezone] = useState(trigger.timezone ?? "UTC");
|
||||
const [valid, setValid] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
return (
|
||||
<fieldset disabled={busy} className="min-w-0 space-y-4">
|
||||
<ScheduleEditor
|
||||
value={cronExpression}
|
||||
onChange={setCron}
|
||||
onValidityChange={setValid}
|
||||
/>
|
||||
<Label>
|
||||
Time zone
|
||||
<Input
|
||||
value={timezone}
|
||||
onChange={(event) => setTimezone(event.target.value)}
|
||||
/>
|
||||
</Label>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
disabled={!valid}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
await onSave({ cronExpression, timezone });
|
||||
} catch (cause) {
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: "Couldn’t save schedule.",
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Save schedule
|
||||
</Button>
|
||||
<Button variant="outline" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
||||
function WebhookSettings({
|
||||
trigger,
|
||||
routineTitle,
|
||||
onRefresh,
|
||||
}: {
|
||||
trigger: RoutineTrigger;
|
||||
routineTitle: string;
|
||||
onRefresh: () => Promise<void>;
|
||||
}) {
|
||||
const [secret, setSecret] = useState("");
|
||||
const [replace, setReplace] = useState(false);
|
||||
const [checkBaseline, setCheckBaseline] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const github = trigger.signingMode === "github_hmac";
|
||||
const delivery = trigger.lastWebhookDelivery;
|
||||
const checked =
|
||||
checkBaseline !== null && delivery && delivery.receivedAt !== checkBaseline;
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<WebhookUrlWarning url={trigger.webhookUrl ?? ""} />
|
||||
{secret && (github || trigger.signingMode === "bearer" || trigger.signingMode === "app_webhook" || trigger.signingMode === "fireflies_hmac") && (
|
||||
<AgentInstructions
|
||||
value={webhookAgentInstructions(
|
||||
github ? "github" : "custom",
|
||||
routineTitle,
|
||||
trigger.webhookUrl ?? "",
|
||||
secret,
|
||||
false,
|
||||
trigger.signingMode === "bearer" ? "bearer" : trigger.signingMode === "fireflies_hmac" ? "fireflies_hmac" : "app_webhook",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<CopyField label="Webhook URL" value={trigger.webhookUrl ?? ""} />
|
||||
{trigger.signingMode !== "none" && (
|
||||
<div className="space-y-2">
|
||||
{secret ? (
|
||||
<CopyField
|
||||
label={
|
||||
trigger.signingMode === "bearer"
|
||||
? "Authorization header value"
|
||||
: "Secret key"
|
||||
}
|
||||
value={
|
||||
trigger.signingMode === "bearer" ? `Bearer ${secret}` : secret
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
The secret key is hidden.
|
||||
</p>
|
||||
)}
|
||||
<Button variant="outline" size="sm" onClick={() => setReplace(true)}>
|
||||
Replace key
|
||||
</Button>
|
||||
{secret && (
|
||||
<Button variant="ghost" size="sm" onClick={() => setSecret("")}>
|
||||
Hide key
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{trigger.signingMode === "none" && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This webhook uses its URL as the shared secret.
|
||||
</p>
|
||||
)}
|
||||
{trigger.signingMode === "hmac_sha256" && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Sign the timestamp, a period, and the exact JSON body with
|
||||
HMAC-SHA256. Send X-Paperclip-Timestamp and X-Paperclip-Signature:
|
||||
sha256=<signature>.
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
setCheckBaseline(trigger.lastWebhookDelivery?.receivedAt ?? "")
|
||||
}
|
||||
>
|
||||
Check connection
|
||||
</Button>
|
||||
<Dialog open={replace} onOpenChange={setReplace}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Replace the webhook key?</DialogTitle>
|
||||
<DialogDescription>
|
||||
The old key will stop working. Update your sending app with the
|
||||
new key.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
const response = await routinesApi.rotateTriggerSecret(
|
||||
trigger.id,
|
||||
);
|
||||
setSecret(response.secretMaterial.webhookSecret);
|
||||
setReplace(false);
|
||||
await onRefresh();
|
||||
} catch (cause) {
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: "Couldn’t replace the key.",
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Replace key
|
||||
</Button>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<Dialog
|
||||
open={checkBaseline !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setCheckBaseline(null);
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Check connection</DialogTitle>
|
||||
<DialogDescription>
|
||||
This webhook is already enabled. Events sent now can start the
|
||||
routine. Send an event from your app to check delivery.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<p role="status" className="text-sm">
|
||||
{checked
|
||||
? delivery.status === "received"
|
||||
? "Event received · Authentication passed"
|
||||
: "Event arrived, but authentication failed. Check the key in your app."
|
||||
: "Waiting for an event from your app…"}
|
||||
</p>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
import { useId, type ReactNode } from "react";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export function RoutineTriggerCard({
|
||||
kind,
|
||||
icon,
|
||||
title,
|
||||
summary,
|
||||
expanded,
|
||||
onEdit,
|
||||
onRemove,
|
||||
editLabel,
|
||||
children,
|
||||
}: {
|
||||
kind: "schedule" | "webhook" | "api" | "heartbeat";
|
||||
icon: ReactNode;
|
||||
title: string;
|
||||
summary: string;
|
||||
expanded: boolean;
|
||||
onEdit: () => void;
|
||||
editLabel?: string;
|
||||
onRemove: () => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const editorId = useId();
|
||||
return (
|
||||
<section
|
||||
aria-label={kind === "heartbeat" ? "Standing check" : `${kind === "schedule" ? "Schedule" : kind === "api" ? "API" : "Webhook"} trigger`}
|
||||
className="rounded-md border border-border"
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-3 p-4">
|
||||
<span className="shrink-0 text-muted-foreground">{icon}</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<h3 className="text-sm font-medium">{title}</h3>
|
||||
<p className="text-xs text-muted-foreground">{summary}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-expanded={expanded}
|
||||
aria-controls={editorId}
|
||||
onClick={onEdit}
|
||||
>
|
||||
{editLabel ?? (expanded ? "Close" : `Edit ${kind}`)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={`Remove ${kind}`}
|
||||
title={`Remove ${kind}`}
|
||||
onClick={onRemove}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{expanded && (
|
||||
<div id={editorId} className="space-y-5 border-t border-border p-4">
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { defaultTriggerDraft, RoutineTriggerWizard, webhookAgentInstructions } from "./TriggerWizard";
|
||||
|
||||
const { setBreadcrumbs } = vi.hoisted(() => ({ setBreadcrumbs: vi.fn() }));
|
||||
vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs }) }));
|
||||
vi.mock("@/context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: false, setSidebarOpen: () => {} }) }));
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
beforeEach(() => { vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); container = document.createElement("div"); document.body.append(container); root = createRoot(container); });
|
||||
afterEach(async () => { await act(async () => root.unmount()); container.remove(); });
|
||||
|
||||
it("offers the shared app flow without a Fireflies-specific sender", async () => {
|
||||
await act(async () => root.render(<RoutineTriggerWizard initialDraft={{ ...defaultTriggerDraft, kind: "webhook" }} routineTitle="Process meetings" routineId="routine-1" onSaveExit={() => {}} onFinish={() => {}} />));
|
||||
expect(container.textContent).toContain("Another app or script");
|
||||
expect(container.textContent).not.toContain("Fireflies");
|
||||
expect(container.textContent).toContain("publicly reachable HTTPS");
|
||||
});
|
||||
|
||||
it("resumes generic setup with a signing secret and preserves the draft", async () => {
|
||||
const onSaveExit = vi.fn();
|
||||
await act(async () => root.render(<RoutineTriggerWizard initialDraft={{ ...defaultTriggerDraft, kind: "webhook", created: true, step: 1, availableStep: 1 }} routineTitle="Process meetings" routineId="routine-1" webhookUrl="https://paperclip.example/api/routine-triggers/public/test/fire" webhookSecret="test-signing-secret" onSaveExit={onSaveExit} onFinish={() => {}} />));
|
||||
expect(container.textContent).toContain("Secret key");
|
||||
expect(container.textContent).toContain("signing secret field");
|
||||
expect(container.textContent).not.toContain("Fireflies");
|
||||
const save = [...container.querySelectorAll("button")].find((button) => button.textContent?.includes("Save & exit"))!;
|
||||
await act(async () => save.click());
|
||||
expect(onSaveExit).toHaveBeenCalledWith(expect.objectContaining({ sender: "custom", step: 1, created: true }));
|
||||
});
|
||||
|
||||
it("explains both supported app authentication methods", () => {
|
||||
const instructions = webhookAgentInstructions("custom", "Meetings", "https://paperclip.example/webhook", "signing-secret");
|
||||
expect(instructions).toContain("Secret key: signing-secret");
|
||||
expect(instructions).toContain("X-Hub-Signature");
|
||||
expect(instructions).toContain("Authorization: Bearer signing-secret");
|
||||
expect(instructions).toContain("They do not start the routine");
|
||||
expect(instructions).not.toContain("Fireflies");
|
||||
});
|
||||
|
||||
it("keeps legacy bearer setup instructions accurate", () => {
|
||||
const instructions = webhookAgentInstructions("custom", "Meetings", "https://paperclip.example/webhook", "secret", true, "bearer");
|
||||
expect(instructions).toContain("Authorization: Bearer secret");
|
||||
expect(instructions).not.toContain("HMAC-SHA256");
|
||||
});
|
||||
@@ -1,597 +0,0 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import {
|
||||
CalendarClock,
|
||||
Check,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
Globe,
|
||||
GitBranch,
|
||||
Radio,
|
||||
Webhook,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
SetupWizardNavigation,
|
||||
SetupWizardFooter,
|
||||
} from "@/components/SetupWizard";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { AgentInstructions, CopyField } from "./WebhookFields";
|
||||
import { WebhookUrlWarning } from "./WebhookUrlWarning";
|
||||
|
||||
export type TriggerDraft = {
|
||||
kind: "choose" | "schedule" | "webhook";
|
||||
step: number;
|
||||
availableStep: number;
|
||||
sender: "custom" | "github";
|
||||
/** Retained when resuming webhooks created before generic signed-app support. */
|
||||
signingMode?: "bearer" | "app_webhook" | "fireflies_hmac";
|
||||
frequency: string;
|
||||
time: string;
|
||||
weekday: string;
|
||||
timezone: string;
|
||||
created: boolean;
|
||||
};
|
||||
export const defaultTriggerDraft: TriggerDraft = {
|
||||
kind: "choose",
|
||||
step: 0,
|
||||
availableStep: 0,
|
||||
sender: "custom",
|
||||
frequency: "weekdays",
|
||||
time: "09:00",
|
||||
weekday: "Monday",
|
||||
timezone: "America/Chicago",
|
||||
created: false,
|
||||
};
|
||||
export function webhookAgentInstructions(
|
||||
sender: TriggerDraft["sender"],
|
||||
routineTitle: string,
|
||||
webhookUrl: string,
|
||||
webhookSecret: string,
|
||||
setupPending = true,
|
||||
signingMode: TriggerDraft["signingMode"] = "app_webhook",
|
||||
) {
|
||||
const common = [
|
||||
`Connect the sending app to the Paperclip routine ${JSON.stringify(routineTitle)}.`,
|
||||
`Webhook URL: ${webhookUrl}`,
|
||||
"Send an HTTP POST request with a JSON object as the body (not an array or string).",
|
||||
"Content-Type: application/json",
|
||||
];
|
||||
const auth =
|
||||
sender === "github"
|
||||
? [
|
||||
"In GitHub, open your repository → Settings → Webhooks → Add webhook.",
|
||||
"Use the webhook URL above as Payload URL and select application/json as Content type.",
|
||||
`Secret: ${webhookSecret}`,
|
||||
"Paste this value into GitHub’s Secret field. GitHub signs requests with X-Hub-Signature-256; do not use Bearer authentication.",
|
||||
"Select the events that should start this routine, enable the webhook, and save.",
|
||||
"To check the connection, open Recent Deliveries and redeliver an event.",
|
||||
]
|
||||
: [
|
||||
`Secret key: ${webhookSecret}`,
|
||||
...(signingMode === "bearer" ? [] : [
|
||||
`If the app asks for a signing secret, paste the secret key above. Paperclip accepts HMAC-SHA256 over the exact request body in ${signingMode === "fireflies_hmac" ? "X-Hub-Signature" : "X-Hub-Signature or X-Hub-Signature-256"}, formatted sha256=<hex digest>.`,
|
||||
]),
|
||||
...(signingMode === "fireflies_hmac" ? [] : [
|
||||
`For apps with custom headers, use Authorization: Bearer ${webhookSecret}`,
|
||||
]),
|
||||
"Subscribe only to the events that should start this routine. Public services need a publicly reachable HTTPS URL.",
|
||||
"In the sending app, add a webhook using this URL, POST method, JSON body, and headers, then save it.",
|
||||
"Send a unique Idempotency-Key header for each event and reuse it on retries, so retrying a setup test after activation cannot start the routine.",
|
||||
'Example JSON body: {"event":"deployment.completed","environment":"production"}',
|
||||
"To check the connection, send a test event from the app or perform the action that triggers a delivery.",
|
||||
];
|
||||
return [
|
||||
...common,
|
||||
...auth,
|
||||
"Open Check connection in Paperclip to see whether the event arrived and authentication passed.",
|
||||
...(setupPending
|
||||
? [
|
||||
"During setup, deliveries only test the connection. They do not start the routine or create a task.",
|
||||
"Finish setup in Paperclip to enable this webhook for future events. Test events are not replayed.",
|
||||
]
|
||||
: [
|
||||
"This webhook is enabled. Deliveries can start the routine and create tasks.",
|
||||
]),
|
||||
"Store the key securely; do not put it in source control or logs.",
|
||||
].join("\n");
|
||||
}
|
||||
export function describeSchedule(draft: TriggerDraft) {
|
||||
return `${draft.frequency === "daily" ? "Every day" : draft.frequency === "weekly" ? `Every ${draft.weekday}` : "Every weekday"} at ${draft.time}`;
|
||||
}
|
||||
export function RoutineTriggerWizard({
|
||||
initialDraft,
|
||||
onSaveExit,
|
||||
onFinish,
|
||||
onCreateWebhook,
|
||||
onRotateKey,
|
||||
routineTitle,
|
||||
routineId,
|
||||
routineActive = true,
|
||||
webhookUrl = "",
|
||||
webhookSecret = "",
|
||||
checkResult = "waiting",
|
||||
}: {
|
||||
initialDraft: TriggerDraft;
|
||||
routineTitle: string;
|
||||
routineId: string;
|
||||
routineActive?: boolean;
|
||||
webhookUrl?: string;
|
||||
webhookSecret?: string;
|
||||
onCreateWebhook?: (draft: TriggerDraft) => Promise<void>;
|
||||
onRotateKey?: () => Promise<void>;
|
||||
onSaveExit: (draft: TriggerDraft) => void | Promise<void>;
|
||||
onFinish: (draft: TriggerDraft) => void | Promise<void>;
|
||||
checkResult?: "waiting" | "received" | "rejected" | "no_event";
|
||||
}) {
|
||||
const [draft, setDraft] = useState(initialDraft);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [saveError, setSaveError] = useState("");
|
||||
const { setBreadcrumbs } = useBreadcrumbs();
|
||||
const perform = useCallback(
|
||||
async (action: () => void | Promise<void>) => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setSaveError("");
|
||||
try {
|
||||
await action();
|
||||
} catch (error) {
|
||||
setSaveError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Couldn’t save. Please try again.",
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
},
|
||||
[busy],
|
||||
);
|
||||
const saveAndExit = useCallback(() => {
|
||||
void perform(() => onSaveExit(draft));
|
||||
}, [draft, onSaveExit, perform]);
|
||||
useEffect(() => {
|
||||
setBreadcrumbs([
|
||||
{
|
||||
label: routineTitle,
|
||||
href: `/routines/${routineId}/triggers`,
|
||||
onClick: (event) => {
|
||||
if (
|
||||
event.button !== 0 ||
|
||||
event.metaKey ||
|
||||
event.ctrlKey ||
|
||||
event.shiftKey ||
|
||||
event.altKey
|
||||
)
|
||||
return;
|
||||
event.preventDefault();
|
||||
saveAndExit();
|
||||
},
|
||||
},
|
||||
{ label: "Add trigger" },
|
||||
]);
|
||||
}, [saveAndExit, setBreadcrumbs, routineTitle, routineId]);
|
||||
const schedule = draft.kind === "schedule";
|
||||
const github = draft.sender === "github";
|
||||
const labels = schedule
|
||||
? ["Choose trigger", "Set schedule", "Review schedule"]
|
||||
: ["Choose trigger", "Connect your app", "Check connection"];
|
||||
function patch(values: Partial<TriggerDraft>) {
|
||||
setDraft((current) => ({ ...current, ...values }));
|
||||
}
|
||||
function advance() {
|
||||
void perform(async () => {
|
||||
if (draft.kind === "webhook" && draft.step === 0 && !draft.created)
|
||||
await onCreateWebhook?.(draft);
|
||||
const step = draft.step + 1;
|
||||
patch({
|
||||
step,
|
||||
availableStep: Math.max(draft.availableStep, step),
|
||||
created:
|
||||
draft.created || (draft.kind === "webhook" && draft.step === 0),
|
||||
});
|
||||
});
|
||||
}
|
||||
const title =
|
||||
draft.step === 0
|
||||
? "When should this routine run?"
|
||||
: schedule
|
||||
? draft.step === 1
|
||||
? "Set a schedule"
|
||||
: "Review your schedule"
|
||||
: draft.step === 1
|
||||
? `Connect ${github ? "GitHub" : "your app"}`
|
||||
: "Check your connection";
|
||||
const subtitle =
|
||||
draft.step === 0
|
||||
? `Choose how to start “${routineTitle}”. You can add another trigger later.`
|
||||
: schedule
|
||||
? draft.step === 1
|
||||
? "Choose when Paperclip should start this routine automatically."
|
||||
: "This schedule starts the routine automatically. You can pause or change it later."
|
||||
: draft.step === 1
|
||||
? "Copy these details into the sending app, then save its webhook settings."
|
||||
: "Test that events arrive and authentication works. This won’t start the routine.";
|
||||
const selectClass =
|
||||
"w-full rounded-md border border-input bg-background px-3 py-2 text-sm";
|
||||
const goBack = (
|
||||
<Button variant="outline" onClick={() => patch({ step: draft.step - 1 })}>
|
||||
Back
|
||||
</Button>
|
||||
);
|
||||
return (
|
||||
<div className="min-w-0 w-full max-w-2xl space-y-6">
|
||||
<SetupWizardNavigation
|
||||
takeover
|
||||
disabled={busy}
|
||||
ariaLabel="Trigger setup progress"
|
||||
labels={labels}
|
||||
step={draft.step}
|
||||
availableStep={draft.availableStep}
|
||||
onSelect={(step) => patch({ step })}
|
||||
/>
|
||||
<fieldset disabled={busy} className="min-w-0 space-y-6">
|
||||
<div className="space-y-1">
|
||||
<h1 className="text-xl font-bold">{title}</h1>
|
||||
<p className="text-sm text-muted-foreground">{subtitle}</p>
|
||||
</div>
|
||||
{!schedule && draft.step > 0 && <WebhookUrlWarning url={webhookUrl} />}
|
||||
{draft.step === 0 && (
|
||||
<fieldset className="space-y-3">
|
||||
<legend className="sr-only">Trigger type</legend>
|
||||
{(
|
||||
[
|
||||
{
|
||||
kind: "schedule",
|
||||
label: "On a schedule",
|
||||
detail: "Every day, on weekdays, or once a week.",
|
||||
Icon: CalendarClock,
|
||||
},
|
||||
{
|
||||
kind: "webhook",
|
||||
label: "When another app sends a webhook",
|
||||
detail:
|
||||
"When something happens in GitHub, another app, or a script.",
|
||||
Icon: Webhook,
|
||||
},
|
||||
] as const
|
||||
).map(({ kind, label, detail, Icon }) => (
|
||||
<label
|
||||
key={kind}
|
||||
className={cn(
|
||||
"flex cursor-pointer items-start gap-3 rounded-md border p-4 focus-within:ring-2 focus-within:ring-ring",
|
||||
draft.kind === kind
|
||||
? "border-primary bg-accent/30"
|
||||
: "border-border hover:bg-accent/20",
|
||||
)}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="trigger-kind"
|
||||
checked={draft.kind === kind}
|
||||
disabled={draft.created && kind !== draft.kind}
|
||||
onChange={() =>
|
||||
patch({
|
||||
kind,
|
||||
availableStep:
|
||||
kind === draft.kind ? draft.availableStep : 0,
|
||||
})
|
||||
}
|
||||
className="sr-only"
|
||||
/>
|
||||
<Icon className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<span className="flex-1">
|
||||
<span className="block text-sm font-medium">{label}</span>
|
||||
<span className="block text-xs text-muted-foreground">
|
||||
{detail}
|
||||
</span>
|
||||
</span>
|
||||
{draft.kind === kind && <Check className="h-4 w-4" />}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
{schedule && draft.step === 1 && (
|
||||
<div className="space-y-5">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="repeat">Repeat</Label>
|
||||
<select
|
||||
id="repeat"
|
||||
className={selectClass}
|
||||
value={draft.frequency}
|
||||
onChange={(event) => patch({ frequency: event.target.value })}
|
||||
>
|
||||
<option value="daily">Every day</option>
|
||||
<option value="weekdays">Weekdays (Monday–Friday)</option>
|
||||
<option value="weekly">Every week</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="run-time">Time</Label>
|
||||
<Input
|
||||
id="run-time"
|
||||
type="time"
|
||||
value={draft.time}
|
||||
onChange={(event) => patch({ time: event.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{draft.frequency === "weekly" && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="run-day">Day</Label>
|
||||
<select
|
||||
id="run-day"
|
||||
className={selectClass}
|
||||
value={draft.weekday}
|
||||
onChange={(event) => patch({ weekday: event.target.value })}
|
||||
>
|
||||
{[
|
||||
"Monday",
|
||||
"Tuesday",
|
||||
"Wednesday",
|
||||
"Thursday",
|
||||
"Friday",
|
||||
"Saturday",
|
||||
"Sunday",
|
||||
].map((day) => (
|
||||
<option key={day}>{day}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="timezone">Time zone</Label>
|
||||
<select
|
||||
id="timezone"
|
||||
className={selectClass}
|
||||
value={draft.timezone}
|
||||
onChange={(event) => patch({ timezone: event.target.value })}
|
||||
>
|
||||
{Array.from(
|
||||
new Set([
|
||||
draft.timezone,
|
||||
"America/Chicago",
|
||||
"America/New_York",
|
||||
"America/Los_Angeles",
|
||||
"Europe/London",
|
||||
"UTC",
|
||||
]),
|
||||
).map((zone) => (
|
||||
<option key={zone}>{zone}</option>
|
||||
))}
|
||||
</select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
The time follows this zone, including daylight saving changes.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{schedule && draft.step === 2 && (
|
||||
<div className="space-y-5">
|
||||
<div className="flex items-start gap-3 rounded-md bg-muted/40 p-4">
|
||||
<CalendarClock className="h-5 w-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">{describeSchedule(draft)}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{draft.timezone}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Each scheduled run creates a task for the routine’s assigned
|
||||
agent. Any existing webhook triggers will continue to work.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{draft.step === 0 && draft.kind === "webhook" && (
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="mb-2 text-sm font-medium">
|
||||
What’s sending the webhook?
|
||||
</legend>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{(
|
||||
[
|
||||
{
|
||||
sender: "custom",
|
||||
label: "Another app or script",
|
||||
Icon: Globe,
|
||||
},
|
||||
{ sender: "github", label: "GitHub", Icon: GitBranch },
|
||||
] as const
|
||||
).map(({ sender, label, Icon }) => (
|
||||
<label
|
||||
key={sender}
|
||||
className={cn(
|
||||
"flex cursor-pointer items-center gap-3 rounded-md border p-3 focus-within:ring-2 focus-within:ring-ring",
|
||||
draft.sender === sender
|
||||
? "border-primary bg-accent/30"
|
||||
: "border-border",
|
||||
draft.created && "cursor-default",
|
||||
)}
|
||||
>
|
||||
<input
|
||||
className="sr-only"
|
||||
type="radio"
|
||||
name="sender"
|
||||
checked={draft.sender === sender}
|
||||
disabled={draft.created}
|
||||
onChange={() => patch({ sender })}
|
||||
/>
|
||||
<Icon className="h-4 w-4" />
|
||||
<span className="flex-1 text-sm">{label}</span>
|
||||
{draft.sender === sender && <Check className="h-4 w-4" />}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
)}
|
||||
{draft.kind === "webhook" && draft.step === 0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Public services need a publicly reachable HTTPS webhook URL.
|
||||
</p>
|
||||
)}
|
||||
{!schedule && draft.step === 1 && (
|
||||
<div className="space-y-5">
|
||||
{webhookSecret && (
|
||||
<AgentInstructions
|
||||
value={webhookAgentInstructions(
|
||||
draft.sender,
|
||||
routineTitle,
|
||||
webhookUrl,
|
||||
webhookSecret,
|
||||
true,
|
||||
draft.signingMode,
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<CopyField
|
||||
label={github ? "Payload URL" : "Webhook URL"}
|
||||
value={webhookUrl}
|
||||
/>
|
||||
{!github && draft.signingMode !== "bearer" && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Paste this key into your app’s signing secret field.
|
||||
{draft.signingMode !== "fireflies_hmac" && <>
|
||||
{" "}If your app uses custom headers instead, set Authorization to Bearer followed
|
||||
by a space and this key.
|
||||
</>}
|
||||
</p>
|
||||
)}
|
||||
{webhookSecret ? (
|
||||
<CopyField
|
||||
label={github ? "Secret" : draft.signingMode === "bearer" ? "Authorization header value" : "Secret key"}
|
||||
value={!github && draft.signingMode === "bearer" ? `Bearer ${webhookSecret}` : webhookSecret}
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
The key is hidden after leaving setup. If you haven’t saved it
|
||||
in your app, generate a replacement.
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => void perform(() => onRotateKey?.())}
|
||||
>
|
||||
Generate new key
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!schedule && draft.step === 2 && (
|
||||
<div className="space-y-5">
|
||||
<div className="space-y-1 rounded-md border border-border p-4">
|
||||
<p className="text-sm font-medium">Connection test only</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Events received during setup won’t start the routine or create
|
||||
tasks.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">
|
||||
Send an event from {github ? "GitHub" : "your app"}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{github
|
||||
? "Open this webhook in your repository settings. Under Recent Deliveries, choose Redeliver on an event."
|
||||
: "Look for “Send test” in your app’s webhook settings. If it doesn’t have one, do the action that should trigger the webhook—for example, complete a deployment."}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Keep this page open to see the test result.
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
role="status"
|
||||
className="flex items-start gap-3 rounded-md bg-muted/40 p-4"
|
||||
>
|
||||
{checkResult === "received" ? (
|
||||
<CheckCircle2 className="h-5 w-5 shrink-0 text-(--status-task-done)" />
|
||||
) : checkResult === "rejected" ? (
|
||||
<AlertCircle className="h-5 w-5 shrink-0 text-destructive" />
|
||||
) : (
|
||||
<Radio className="h-5 w-5 shrink-0 text-muted-foreground" />
|
||||
)}
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">
|
||||
{checkResult === "received"
|
||||
? "Test event received · Connection working"
|
||||
: checkResult === "rejected"
|
||||
? "Event arrived, but the key was rejected"
|
||||
: checkResult === "no_event"
|
||||
? "No event received yet"
|
||||
: "Waiting for an event from your app…"}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{checkResult === "received"
|
||||
? "Authentication passed. No routine run or task was created."
|
||||
: checkResult === "rejected"
|
||||
? "Go back to Connect your app, update the key in your sending app, and resend. No task was created."
|
||||
: "Waiting to verify delivery and authentication. The routine is not running."}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<details>
|
||||
<summary className="cursor-pointer text-xs text-muted-foreground">
|
||||
Troubleshoot delivery
|
||||
</summary>
|
||||
<div className="space-y-3 pt-3">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Check that the webhook is enabled in your sending app and that
|
||||
its URL matches. Scripts must send POST with a JSON body.
|
||||
</p>
|
||||
<CopyField label="Webhook URL" value={webhookUrl} />
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
)}
|
||||
{!schedule && draft.step === 2 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{routineActive
|
||||
? "Finish setup to enable this webhook. Future events will start the routine; this test event won’t be replayed."
|
||||
: "Finish setup to save this webhook. The routine is paused; enable its automatic triggers when you’re ready. This test event won’t be replayed."}
|
||||
</p>
|
||||
)}
|
||||
{schedule && draft.step === 2 && !routineActive && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
The routine is paused. Enable its automatic triggers when you’re
|
||||
ready to use this schedule.
|
||||
</p>
|
||||
)}
|
||||
{saveError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{saveError}
|
||||
</p>
|
||||
)}
|
||||
<SetupWizardFooter onSaveExit={saveAndExit}>
|
||||
{draft.step > 0 && goBack}
|
||||
{draft.step === 0 ? (
|
||||
<Button disabled={draft.kind === "choose"} onClick={advance}>
|
||||
Continue
|
||||
</Button>
|
||||
) : schedule ? (
|
||||
draft.step === 1 ? (
|
||||
<Button disabled={!draft.time} onClick={advance}>
|
||||
Review schedule
|
||||
</Button>
|
||||
) : (
|
||||
<Button onClick={() => void perform(() => onFinish(draft))}>
|
||||
Add schedule
|
||||
</Button>
|
||||
)
|
||||
) : draft.step === 1 ? (
|
||||
<Button onClick={advance}>Check connection</Button>
|
||||
) : (
|
||||
<Button onClick={() => void perform(() => onFinish(draft))}>
|
||||
{checkResult === "received"
|
||||
? "Finish setup"
|
||||
: "Finish without checking"}
|
||||
</Button>
|
||||
)}
|
||||
</SetupWizardFooter>
|
||||
</fieldset>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { webhookAgentInstructions, webhookInstructionSigningMode } from "./webhook-instructions";
|
||||
|
||||
it("explains both supported app authentication methods", () => {
|
||||
const instructions = webhookAgentInstructions("custom", "Meetings", "https://paperclip.example/webhook", "signing-secret");
|
||||
expect(instructions).toContain("Secret key: signing-secret");
|
||||
expect(instructions).toContain("X-Hub-Signature");
|
||||
expect(instructions).toContain("Authorization: Bearer signing-secret");
|
||||
expect(instructions).toContain("They do not start the routine");
|
||||
expect(instructions).not.toContain("Fireflies");
|
||||
});
|
||||
|
||||
it("keeps legacy bearer setup instructions accurate", () => {
|
||||
const instructions = webhookAgentInstructions("custom", "Meetings", "https://paperclip.example/webhook", "secret", true, "bearer");
|
||||
expect(instructions).toContain("Authorization: Bearer secret");
|
||||
expect(instructions).not.toContain("HMAC-SHA256");
|
||||
});
|
||||
|
||||
it("tells GitHub users to paste the secret instead of using a bearer header", () => {
|
||||
const instructions = webhookAgentInstructions("github", "Deploys", "https://paperclip.example/webhook", "gh-secret", false);
|
||||
expect(instructions).toContain("Secret: gh-secret");
|
||||
expect(instructions).toContain("X-Hub-Signature-256");
|
||||
expect(instructions).toContain("Deliveries can start the routine");
|
||||
});
|
||||
|
||||
it("explains timestamp signing for hmac_sha256 webhooks instead of bearer or X-Hub-Signature", () => {
|
||||
const instructions = webhookAgentInstructions("custom", "Deploys", "https://paperclip.example/webhook", "hmac-secret", false, webhookInstructionSigningMode("hmac_sha256"));
|
||||
expect(instructions).toContain("X-Paperclip-Timestamp");
|
||||
expect(instructions).toContain("X-Paperclip-Signature");
|
||||
expect(instructions).not.toContain("Authorization: Bearer");
|
||||
expect(instructions).not.toContain("X-Hub-Signature");
|
||||
});
|
||||
|
||||
it("gives no key instructions for a webhook without a key", () => {
|
||||
const instructions = webhookAgentInstructions("custom", "Deploys", "https://paperclip.example/webhook", "", false, webhookInstructionSigningMode("none"));
|
||||
expect(instructions).toContain("Its URL is the shared secret");
|
||||
expect(instructions).not.toContain("Secret key:");
|
||||
expect(instructions).toContain("Store the URL securely");
|
||||
expect(instructions).not.toContain("Store the key securely");
|
||||
expect(webhookInstructionSigningMode("something-new")).toBe("app_webhook");
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
export type WebhookInstructionSender = "custom" | "github";
|
||||
export type WebhookInstructionSigningMode = "app_webhook" | "bearer" | "fireflies_hmac" | "hmac_sha256" | "none";
|
||||
|
||||
const SIGNING_MODES: readonly WebhookInstructionSigningMode[] = ["app_webhook", "bearer", "fireflies_hmac", "hmac_sha256", "none"];
|
||||
|
||||
/** The instruction set for a saved webhook's signing mode; unknown modes read as the shared app flow. */
|
||||
export function webhookInstructionSigningMode(mode: string | null | undefined): WebhookInstructionSigningMode {
|
||||
return SIGNING_MODES.includes(mode as WebhookInstructionSigningMode) ? mode as WebhookInstructionSigningMode : "app_webhook";
|
||||
}
|
||||
|
||||
/** Copyable setup instructions for whoever (or whichever agent) connects the sending app. */
|
||||
export function webhookAgentInstructions(
|
||||
sender: WebhookInstructionSender,
|
||||
routineTitle: string,
|
||||
webhookUrl: string,
|
||||
webhookSecret: string,
|
||||
setupPending = true,
|
||||
signingMode: WebhookInstructionSigningMode = "app_webhook",
|
||||
) {
|
||||
const common = [
|
||||
`Connect the sending app to the Paperclip routine ${JSON.stringify(routineTitle)}.`,
|
||||
`Webhook URL: ${webhookUrl}`,
|
||||
"Send an HTTP POST request with a JSON object as the body (not an array or string).",
|
||||
"Content-Type: application/json",
|
||||
];
|
||||
const auth =
|
||||
sender === "github"
|
||||
? [
|
||||
"In GitHub, open your repository → Settings → Webhooks → Add webhook.",
|
||||
"Use the webhook URL above as Payload URL and select application/json as Content type.",
|
||||
`Secret: ${webhookSecret}`,
|
||||
"Paste this value into GitHub’s Secret field. GitHub signs requests with X-Hub-Signature-256; do not use Bearer authentication.",
|
||||
"Select the events that should start this routine, enable the webhook, and save.",
|
||||
"To check the connection, open Recent Deliveries and redeliver an event.",
|
||||
]
|
||||
: signingMode === "none"
|
||||
? [
|
||||
"This webhook has no key. Its URL is the shared secret, so keep it private.",
|
||||
"In the sending app, add a webhook using this URL, POST method and JSON body, then save it.",
|
||||
"Send a unique Idempotency-Key header for each event and reuse it on retries.",
|
||||
]
|
||||
: signingMode === "hmac_sha256"
|
||||
? [
|
||||
`Secret key: ${webhookSecret}`,
|
||||
"Sign each request with HMAC-SHA256 using the secret key. The signed message is the Unix timestamp in seconds, a period, and the exact JSON body.",
|
||||
"Send the timestamp in X-Paperclip-Timestamp and the signature in X-Paperclip-Signature, formatted sha256=<hex digest>.",
|
||||
"Requests with an old timestamp are rejected, so sign each request when you send it. Do not use Bearer authentication.",
|
||||
"Send a unique Idempotency-Key header for each event and reuse it on retries.",
|
||||
]
|
||||
: [
|
||||
`Secret key: ${webhookSecret}`,
|
||||
...(signingMode === "bearer" ? [] : [
|
||||
`If the app asks for a signing secret, paste the secret key above. Paperclip accepts HMAC-SHA256 over the exact request body in ${signingMode === "fireflies_hmac" ? "X-Hub-Signature" : "X-Hub-Signature or X-Hub-Signature-256"}, formatted sha256=<hex digest>.`,
|
||||
]),
|
||||
...(signingMode === "fireflies_hmac" ? [] : [
|
||||
`For apps with custom headers, use Authorization: Bearer ${webhookSecret}`,
|
||||
]),
|
||||
"Subscribe only to the events that should start this routine. Public services need a publicly reachable HTTPS URL.",
|
||||
"In the sending app, add a webhook using this URL, POST method, JSON body, and headers, then save it.",
|
||||
"Send a unique Idempotency-Key header for each event and reuse it on retries, so retrying a setup test after activation cannot start the routine.",
|
||||
'Example JSON body: {"event":"deployment.completed","environment":"production"}',
|
||||
"To check the connection, send a test event from the app or perform the action that triggers a delivery.",
|
||||
];
|
||||
return [
|
||||
...common,
|
||||
...auth,
|
||||
"The webhook in Paperclip shows whether the event arrived and authentication passed.",
|
||||
...(setupPending
|
||||
? [
|
||||
"During setup, deliveries only test the connection. They do not start the routine or create a task.",
|
||||
"Finish in Paperclip to enable this webhook for future events. Test events are not replayed.",
|
||||
]
|
||||
: [
|
||||
"This webhook is enabled. Deliveries can start the routine and create tasks.",
|
||||
]),
|
||||
signingMode === "none"
|
||||
? "Store the URL securely; do not put it in source control or logs."
|
||||
: "Store the key securely; do not put it in source control or logs.",
|
||||
].join("\n");
|
||||
}
|
||||
Reference in new issue
Block a user