From ab4d77c4c1935ba832a64d9daf136d5df349959f Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 9 Jun 2026 22:12:54 +0000 Subject: [PATCH] feat(ui): routine detail variation C polish follow-ups (PAP-10735) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements the five §3.x spec-completion items flagged in PAP-10735: 1. Runs row subtitle (§3.6): rebuild RunsSection on with a subtitle showing inline variable values for successful runs and the failure reason for failed runs; de-dupe the redundant trigger label when label === kind (new ui/src/lib/routine-run-display.ts). 2. Runs filter chips (§3.6): Source/Status/Date selects + active pills + Clear, with a filtered-empty state. 3. Delivery next-5-fires preview (§3.5): new tz-aware ui/src/lib/cron-fires.ts plus a pure previewFirePolicies() that annotates each fire with how the chosen concurrency policy treats it (queued/coalesced/skipped). 4. Secrets (§3.4): extend EnvVarEditor with recentlyUsedSecrets quick-bind chips and replace the native for parity. 5. Triggers (§3.2): convert the always-open add form into a + New trigger expand-on-click drawer. Tests: new cron-fires + routine-run-display unit suites (30 cases); existing routine/EnvVarEditor-consumer tests stay green; tsc clean. Co-Authored-By: Claude Opus 4.8 --- ui/src/components/EnvVarEditor.tsx | 195 +++++++++---- .../routine-sections/editable-sections.tsx | 172 +++++++++++- .../routine-sections/operate-sections.tsx | 204 +++++++++++--- ui/src/lib/cron-fires.test.ts | 88 ++++++ ui/src/lib/cron-fires.ts | 256 ++++++++++++++++++ ui/src/lib/routine-run-display.test.ts | 68 +++++ ui/src/lib/routine-run-display.ts | 54 ++++ .../stories/routine-detail-c.stories.tsx | 42 ++- 8 files changed, 985 insertions(+), 94 deletions(-) create mode 100644 ui/src/lib/cron-fires.test.ts create mode 100644 ui/src/lib/cron-fires.ts create mode 100644 ui/src/lib/routine-run-display.test.ts create mode 100644 ui/src/lib/routine-run-display.ts diff --git a/ui/src/components/EnvVarEditor.tsx b/ui/src/components/EnvVarEditor.tsx index 08c7f58b290..74e161d32ea 100644 --- a/ui/src/components/EnvVarEditor.tsx +++ b/ui/src/components/EnvVarEditor.tsx @@ -1,11 +1,35 @@ import { useEffect, useRef, useState } from "react"; import type { CompanySecret, EnvBinding, SecretVersionSelector } from "@paperclipai/shared"; -import { AlertCircle, X } from "lucide-react"; +import { AlertCircle, KeyRound, X } from "lucide-react"; import { cn } from "../lib/utils"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; const inputClass = "w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40"; +// shadcn Select trigger sized to line up with the mono inputs above. +const selectTriggerClass = + "h-[34px] min-h-[34px] rounded-md border-border bg-transparent px-2.5 text-sm font-mono shadow-none"; + +/** Radix Select forbids empty-string item values; use a sentinel for "unset". */ +const SECRET_UNSET = "__unset__"; + +/** Suggest an env-var-style KEY from a secret name (UPPER_SNAKE). */ +function envKeyFromSecretName(name: string): string { + return name + .trim() + .toUpperCase() + .replace(/[^A-Z0-9_]+/g, "_") + .replace(/^_+|_+$/g, "") + .slice(0, 64); +} + type Row = { key: string; source: "plain" | "secret"; @@ -69,11 +93,17 @@ export function EnvVarEditor({ secrets, onCreateSecret, onChange, + recentlyUsedSecrets, }: { value: Record; secrets: CompanySecret[]; onCreateSecret: (name: string, value: string) => Promise; onChange: (env: Record | undefined) => void; + /** + * Optional project-scoped secrets to surface as one-tap "quick bind" chips + * below the editor (§3.4). Already-bound secrets are filtered out. + */ + recentlyUsedSecrets?: CompanySecret[]; }) { const [rows, setRows] = useState(() => toRows(value)); const [sealError, setSealError] = useState(null); @@ -140,6 +170,27 @@ export function EnvVarEditor({ emit(next); } + function bindRecentSecret(secret: CompanySecret) { + // Fill the trailing empty row (or append one) with this secret bound. + const next = rows.map((row) => ({ ...row })); + const trailing = next[next.length - 1]; + const target = + trailing && !trailing.key && !trailing.plainValue && !trailing.secretId + ? trailing + : (() => { + const fresh = emptyRow(); + next.push(fresh); + return fresh; + })(); + target.source = "secret"; + target.secretId = secret.id; + target.version = "latest"; + if (!target.key) target.key = envKeyFromSecretName(secret.name); + next.push(emptyRow()); + setRows(next); + emit(next); + } + function defaultSecretName(key: string) { return key .trim() @@ -185,62 +236,86 @@ export function EnvVarEditor({ value={row.key} onChange={(event) => updateRow(index, { key: event.target.value })} /> - + + + + + Plain + Secret + + {row.source === "secret" ? ( <> - + updateRow(index, { secretId: next === SECRET_UNSET ? "" : next }) + } > - - {row.secretId && !secrets.some((s) => s.id === row.secretId) ? ( - - ) : null} - {secrets.map((secret) => ( - - ))} - - + + + + + + latest + {(() => { + const selected = secrets.find((s) => s.id === row.secretId); + if (!selected) return null; + return Array.from({ length: Math.max(0, selected.latestVersion) }, (_, idx) => { + const version = selected.latestVersion - idx; + if (version <= 0) return null; + return ( + + v{version} + + ); + }); + })()} + + + ))} + + ); + })()} {sealError &&

{sealError}

} {(() => { const issues: { key: string; reason: string }[] = []; diff --git a/ui/src/components/routine-sections/editable-sections.tsx b/ui/src/components/routine-sections/editable-sections.tsx index c1cc6371a7b..0ab24040612 100644 --- a/ui/src/components/routine-sections/editable-sections.tsx +++ b/ui/src/components/routine-sections/editable-sections.tsx @@ -1,4 +1,4 @@ -import { useMemo } from "react"; +import { useMemo, useState } from "react"; import { ArrowRight, Braces, @@ -6,6 +6,8 @@ import { Edit3, KeyRound, Play, + Plus, + X, } from "lucide-react"; import { Card, CardContent } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; @@ -20,6 +22,8 @@ import { 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"; @@ -30,7 +34,7 @@ import { RoutineVariablesEditor, RoutineVariablesHint } from "../RoutineVariable import { RoutineTriggerCard } from "../RoutineTriggerCard"; import { EnvVarEditor } from "../EnvVarEditor"; import { useRoutineDetail } from "./context"; -import type { EnvBinding } from "@paperclipai/shared"; +import type { EnvBinding, RoutineDetail as RoutineDetailType } from "@paperclipai/shared"; const concurrencyPolicyOptions = [ { @@ -336,10 +340,39 @@ function SummaryCard({ export function TriggersSection() { const ctx = useRoutineDetail(); const { routine, newTrigger, setNewTrigger, createTrigger, updateTrigger, deleteTrigger, rotateTrigger } = ctx; + const [addOpen, setAddOpen] = useState(false); return (
- {/* Add trigger form */} + {/* Add-trigger drawer header (§3.2) */} +
+

+ {routine.triggers.length === 0 + ? "No triggers yet" + : `${routine.triggers.length} trigger${routine.triggers.length === 1 ? "" : "s"}`} +

+ +
+ + {/* Add trigger form — expand-on-click drawer */} + {addOpen ? (

Add trigger

@@ -412,16 +445,29 @@ export function TriggersSection() { )}
-
- +
+ ) : null} {/* Existing triggers */} {routine.triggers.length === 0 ? ( - + setAddOpen(true)} + /> ) : (
{routine.triggers.map((trigger) => ( @@ -481,6 +527,21 @@ export function SecretsSection() { const ctx = useRoutineDetail(); const { editDraft, setEditDraft, availableSecrets, createSecret, secretMessage, copySecretValue } = 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 (
@@ -520,6 +581,7 @@ export function SecretsSection() { } secrets={availableSecrets} + recentlyUsedSecrets={recentlyUsedSecrets} onCreateSecret={async (name, value) => createSecret.mutateAsync({ name, value })} onChange={(env) => setEditDraft((current) => ({ ...current, env: env ?? null }))} /> @@ -529,7 +591,7 @@ export function SecretsSection() { export function DeliverySection() { const ctx = useRoutineDetail(); - const { editDraft, setEditDraft } = ctx; + const { editDraft, setEditDraft, routine } = ctx; return (
@@ -559,6 +621,102 @@ export function DeliverySection() { options={catchUpPolicyOptions} />
+
); } + +const dispositionToneClass: Record = { + 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 ( +
+

+ Next 5 fires +

+ {preview ? ( + <> +
+ {preview.entries.map((entry, index) => ( +
+ · + {formatFireTime(entry.at, preview.timeZone)} + + + {entry.label} + + {entry.note ? ( + ({entry.note}) + ) : null} +
+ ))} +
+

+ Preview assumes the previous run is still in flight when the next fires. Times shown in{" "} + {preview.timeZone}. +

+ + ) : ( +

+ No enabled schedule trigger to preview. Add a schedule in Triggers to see how this policy + treats upcoming fires. +

+ )} +
+ ); +} + +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(); + } +} diff --git a/ui/src/components/routine-sections/operate-sections.tsx b/ui/src/components/routine-sections/operate-sections.tsx index 2edd4fb4b98..0bf55441a93 100644 --- a/ui/src/components/routine-sections/operate-sections.tsx +++ b/ui/src/components/routine-sections/operate-sections.tsx @@ -1,24 +1,90 @@ -import { useMemo } from "react"; -import { Activity as ActivityIcon, Play } from "lucide-react"; -import { Link } from "@/lib/router"; +import { useMemo, useState } from "react"; +import { Activity as ActivityIcon, Play, SlidersHorizontal } from "lucide-react"; import { Badge } from "@/components/ui/badge"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; import { timeAgo } from "../../lib/timeAgo"; +import { runRowSubtitle, dedupedTriggerLabel } from "../../lib/routine-run-display"; import { EmptyState } from "../EmptyState"; +import { EntityRow } from "../EntityRow"; +import { FilterBar, type FilterValue } from "../FilterBar"; import { LiveRunWidget } from "../LiveRunWidget"; import { RoutineHistoryTab } from "../RoutineHistoryTab"; import { RoutineActivityRow } from "../RoutineActivityRow"; import { useRoutineDetail } from "./context"; +const DATE_WINDOW_OPTIONS: { value: string; label: string; ms: number | null }[] = [ + { value: "any", label: "Any time", ms: null }, + { value: "24h", label: "Last 24h", ms: 24 * 60 * 60 * 1000 }, + { value: "7d", label: "Last 7d", ms: 7 * 24 * 60 * 60 * 1000 }, + { value: "30d", label: "Last 30d", ms: 30 * 24 * 60 * 60 * 1000 }, +]; + export function RunsSection() { const ctx = useRoutineDetail(); const { routine, routineRuns, hasLiveRun, activeIssueId, onOpenRunDialog } = ctx; - const runs = routineRuns ?? []; + const runs = useMemo(() => routineRuns ?? [], [routineRuns]); + + const [sourceFilter, setSourceFilter] = useState("any"); + const [statusFilter, setStatusFilter] = useState("any"); + const [dateFilter, setDateFilter] = useState("any"); + + const sourceOptions = useMemo( + () => [...new Set(runs.map((run) => run.source))].sort(), + [runs], + ); + const statusOptions = useMemo( + () => [...new Set(runs.map((run) => run.status))].sort(), + [runs], + ); + + const filtered = useMemo(() => { + const windowMs = DATE_WINDOW_OPTIONS.find((option) => option.value === dateFilter)?.ms ?? null; + const cutoff = windowMs == null ? null : Date.now() - windowMs; + return runs.filter((run) => { + if (sourceFilter !== "any" && run.source !== sourceFilter) return false; + if (statusFilter !== "any" && run.status !== statusFilter) return false; + if (cutoff != null && new Date(run.triggeredAt).getTime() < cutoff) return false; + return true; + }); + }, [runs, sourceFilter, statusFilter, dateFilter]); + + const activeFilters = useMemo(() => { + const list: FilterValue[] = []; + if (sourceFilter !== "any") list.push({ key: "source", label: "Source", value: sourceFilter }); + if (statusFilter !== "any") { + list.push({ key: "status", label: "Status", value: statusFilter.replaceAll("_", " ") }); + } + if (dateFilter !== "any") { + const label = DATE_WINDOW_OPTIONS.find((option) => option.value === dateFilter)?.label ?? dateFilter; + list.push({ key: "date", label: "Date", value: label }); + } + return list; + }, [sourceFilter, statusFilter, dateFilter]); + + function clearFilters() { + setSourceFilter("any"); + setStatusFilter("any"); + setDateFilter("any"); + } + + function removeFilter(key: string) { + if (key === "source") setSourceFilter("any"); + if (key === "status") setStatusFilter("any"); + if (key === "date") setDateFilter("any"); + } return (
{hasLiveRun && activeIssueId ? ( ) : null} + {runs.length === 0 ? ( ) : ( -
- {runs.map((run) => ( -
-
- - {run.source} - - - {run.status.replaceAll("_", " ")} - - {run.trigger ? ( - - {run.trigger.label ?? run.trigger.kind} - - ) : null} - {run.linkedIssue ? ( - - {run.linkedIssue.identifier ?? run.linkedIssue.id.slice(0, 8)} - - ) : null} -
- - {timeAgo(run.triggeredAt)} - + <> + {/* Filter chips row (§3.6) */} +
+
+ + +
- ))} -
+ +
+ + {filtered.length === 0 ? ( + + ) : ( +
+ {filtered.map((run) => { + const label = dedupedTriggerLabel(run.trigger); + const title = run.linkedIssue?.title ?? label ?? "Run"; + return ( + + + {run.source} + + + {run.status.replaceAll("_", " ")} + + + } + identifier={ + run.linkedIssue + ? run.linkedIssue.identifier ?? run.linkedIssue.id.slice(0, 8) + : undefined + } + title={title} + subtitle={runRowSubtitle(run, routine.variables)} + reserveSubtitleSpace + trailing={ + {timeAgo(run.triggeredAt)} + } + to={ + run.linkedIssue + ? `/issues/${run.linkedIssue.identifier ?? run.linkedIssue.id}` + : undefined + } + /> + ); + })} +
+ )} + )}
); diff --git a/ui/src/lib/cron-fires.test.ts b/ui/src/lib/cron-fires.test.ts new file mode 100644 index 00000000000..1fb7b41fda8 --- /dev/null +++ b/ui/src/lib/cron-fires.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from "vitest"; +import { nextCronFires, parseCronExpression, previewFirePolicies } from "./cron-fires"; + +describe("parseCronExpression", () => { + it("parses a standard 5-field expression", () => { + const parsed = parseCronExpression("0 14 * * 1-5"); + expect(parsed).not.toBeNull(); + expect(parsed?.minutes).toEqual([0]); + expect(parsed?.hours).toEqual([14]); + expect(parsed?.daysOfWeek).toEqual([1, 2, 3, 4, 5]); + }); + + it("returns null for malformed expressions", () => { + expect(parseCronExpression("not a cron")).toBeNull(); + expect(parseCronExpression("0 14 * *")).toBeNull(); + expect(parseCronExpression("")).toBeNull(); + expect(parseCronExpression(null)).toBeNull(); + }); +}); + +describe("nextCronFires", () => { + it("computes the next N daily fires in UTC", () => { + const after = new Date("2026-06-09T10:00:00Z"); + const fires = nextCronFires("0 14 * * *", 3, { after, timeZone: "UTC" }); + expect(fires.map((d) => d.toISOString())).toEqual([ + "2026-06-09T14:00:00.000Z", + "2026-06-10T14:00:00.000Z", + "2026-06-11T14:00:00.000Z", + ]); + }); + + it("skips weekends for a weekday schedule", () => { + // 2026-06-12 is a Friday; the next weekday fire after Fri is Mon 2026-06-15. + const after = new Date("2026-06-12T15:00:00Z"); + const fires = nextCronFires("0 14 * * 1-5", 2, { after, timeZone: "UTC" }); + expect(fires.map((d) => d.toISOString())).toEqual([ + "2026-06-15T14:00:00.000Z", + "2026-06-16T14:00:00.000Z", + ]); + }); + + it("interprets cron fields in the trigger timezone", () => { + // 14:00 in New York (EDT, UTC-4 in June) is 18:00 UTC. + const after = new Date("2026-06-09T10:00:00Z"); + const fires = nextCronFires("0 14 * * *", 1, { after, timeZone: "America/New_York" }); + expect(fires[0]?.toISOString()).toBe("2026-06-09T18:00:00.000Z"); + }); + + it("returns an empty list for an unparseable expression", () => { + expect(nextCronFires("garbage", 5)).toEqual([]); + expect(nextCronFires("0 14 * * *", 0)).toEqual([]); + }); +}); + +describe("previewFirePolicies", () => { + const fires = [ + new Date("2026-06-09T14:00:00Z"), + new Date("2026-06-10T14:00:00Z"), + new Date("2026-06-11T14:00:00Z"), + ]; + + it("always queues the first fire regardless of policy", () => { + for (const policy of ["coalesce_if_active", "always_enqueue", "skip_if_active"]) { + expect(previewFirePolicies(fires, policy)[0]?.disposition).toBe("queued"); + } + }); + + it("coalesces subsequent fires under coalesce_if_active", () => { + const preview = previewFirePolicies(fires, "coalesce_if_active"); + expect(preview.map((e) => e.disposition)).toEqual(["queued", "coalesced", "coalesced"]); + expect(preview[1]?.label).toBe("would be coalesced"); + }); + + it("skips subsequent fires under skip_if_active", () => { + const preview = previewFirePolicies(fires, "skip_if_active"); + expect(preview.map((e) => e.disposition)).toEqual(["queued", "skipped", "skipped"]); + }); + + it("queues every fire under always_enqueue", () => { + const preview = previewFirePolicies(fires, "always_enqueue"); + expect(preview.every((e) => e.disposition === "queued")).toBe(true); + }); + + it("defaults unknown policies to coalesce", () => { + const preview = previewFirePolicies(fires, "mystery"); + expect(preview[1]?.disposition).toBe("coalesced"); + }); +}); diff --git a/ui/src/lib/cron-fires.ts b/ui/src/lib/cron-fires.ts new file mode 100644 index 00000000000..553e4cee78e --- /dev/null +++ b/ui/src/lib/cron-fires.ts @@ -0,0 +1,256 @@ +/** + * Client-side "next N schedule fires" helper for the routine Delivery preview (§3.5). + * + * Mirrors the server's timezone-aware cron tick (server/src/services/routines.ts + * `nextCronTickInTimeZone`) closely enough for an illustrative preview: it parses + * the same 5-field cron grammar and walks minute-by-minute, matching the cron + * fields against wall-clock parts in the trigger's timezone via `Intl.DateTimeFormat`. + * + * This is preview-only — the authoritative `nextRunAt` is still computed server-side. + */ + +const WEEKDAY_INDEX: Record = { + Sun: 0, + Mon: 1, + Tue: 2, + Wed: 3, + Thu: 4, + Fri: 5, + Sat: 6, +}; + +interface ParsedCron { + minutes: number[]; + hours: number[]; + daysOfMonth: number[]; + months: number[]; + daysOfWeek: number[]; +} + +interface FieldSpec { + min: number; + max: number; +} + +const FIELD_SPECS: FieldSpec[] = [ + { min: 0, max: 59 }, // minute + { min: 0, max: 23 }, // hour + { min: 1, max: 31 }, // day of month + { min: 1, max: 12 }, // month + { min: 0, max: 6 }, // day of week (Sun = 0) +]; + +function parseField(token: string, spec: FieldSpec): number[] { + const values = new Set(); + for (const rawPart of token.split(",")) { + const part = rawPart.trim(); + if (part === "") throw new Error("Empty cron field element"); + + const slashIdx = part.indexOf("/"); + if (slashIdx !== -1) { + const base = part.slice(0, slashIdx); + const step = Number.parseInt(part.slice(slashIdx + 1), 10); + if (!Number.isInteger(step) || step <= 0) throw new Error("Invalid cron step"); + let start = spec.min; + let end = spec.max; + if (base === "*") { + // every `step` from min + } else if (base.includes("-")) { + const [a, b] = base.split("-").map((s) => Number.parseInt(s, 10)); + if (!Number.isInteger(a) || !Number.isInteger(b)) throw new Error("Invalid cron range"); + start = a; + end = b; + } else { + const s = Number.parseInt(base, 10); + if (!Number.isInteger(s)) throw new Error("Invalid cron start"); + start = s; + } + assertBounds(start, spec); + assertBounds(end, spec); + for (let i = start; i <= end; i += step) values.add(i); + continue; + } + + if (part.includes("-")) { + const [a, b] = part.split("-").map((s) => Number.parseInt(s, 10)); + if (!Number.isInteger(a) || !Number.isInteger(b)) throw new Error("Invalid cron range"); + assertBounds(a, spec); + assertBounds(b, spec); + if (a > b) throw new Error("Invalid cron range (start > end)"); + for (let i = a; i <= b; i++) values.add(i); + continue; + } + + if (part === "*" || part === "?") { + for (let i = spec.min; i <= spec.max; i++) values.add(i); + continue; + } + + const val = Number.parseInt(part, 10); + if (!Number.isInteger(val)) throw new Error("Invalid cron value"); + assertBounds(val, spec); + values.add(val); + } + if (values.size === 0) throw new Error("Empty cron field"); + return [...values].sort((a, b) => a - b); +} + +function assertBounds(value: number, spec: FieldSpec): void { + if (value < spec.min || value > spec.max) { + throw new Error(`Cron value ${value} out of range`); + } +} + +/** Parse a 5-field cron expression. Returns null when it can't be parsed. */ +export function parseCronExpression(expression: string | null | undefined): ParsedCron | null { + if (!expression) return null; + const tokens = expression.trim().split(/\s+/); + if (tokens.length !== 5) return null; + try { + return { + minutes: parseField(tokens[0]!, FIELD_SPECS[0]!), + hours: parseField(tokens[1]!, FIELD_SPECS[1]!), + daysOfMonth: parseField(tokens[2]!, FIELD_SPECS[2]!), + months: parseField(tokens[3]!, FIELD_SPECS[3]!), + daysOfWeek: parseField(tokens[4]!, FIELD_SPECS[4]!), + }; + } catch { + return null; + } +} + +interface ZonedParts { + month: number; + day: number; + hour: number; + minute: number; + weekday: number; +} + +function getZonedMinuteParts(date: Date, timeZone: string): ZonedParts { + const formatter = new Intl.DateTimeFormat("en-US", { + timeZone, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + weekday: "short", + hourCycle: "h23", + }); + const map: Record = {}; + for (const part of formatter.formatToParts(date)) { + if (part.type !== "literal") map[part.type] = part.value; + } + const weekday = WEEKDAY_INDEX[map.weekday ?? ""]; + if (weekday === undefined) throw new Error(`Unable to resolve weekday for ${timeZone}`); + return { + month: Number(map.month), + day: Number(map.day), + hour: Number(map.hour), + minute: Number(map.minute), + weekday, + }; +} + +function matches(cron: ParsedCron, parts: ZonedParts): boolean { + return ( + cron.minutes.includes(parts.minute) && + cron.hours.includes(parts.hour) && + cron.daysOfMonth.includes(parts.day) && + cron.months.includes(parts.month) && + cron.daysOfWeek.includes(parts.weekday) + ); +} + +/** + * Compute up to `count` upcoming fire instants for a cron expression, strictly + * after `after`, interpreting the cron fields in `timeZone`. + */ +export function nextCronFires( + expression: string | null | undefined, + count: number, + options: { after?: Date; timeZone?: string } = {}, +): Date[] { + const cron = parseCronExpression(expression); + if (!cron || count <= 0) return []; + const timeZone = options.timeZone ?? "UTC"; + const after = options.after ?? new Date(); + + const cursor = new Date(after.getTime()); + cursor.setUTCSeconds(0, 0); + cursor.setUTCMinutes(cursor.getUTCMinutes() + 1); + + const fires: Date[] = []; + // Search window: 5 years of minutes is plenty and bounds impossible schedules. + const maxIterations = 5 * 366 * 24 * 60; + for (let i = 0; i < maxIterations && fires.length < count; i++) { + let parts: ZonedParts; + try { + parts = getZonedMinuteParts(cursor, timeZone); + } catch { + return fires; + } + if (matches(cron, parts)) fires.push(new Date(cursor.getTime())); + cursor.setUTCMinutes(cursor.getUTCMinutes() + 1); + } + return fires; +} + +export type FireDisposition = "queued" | "coalesced" | "skipped"; + +export interface FirePreviewEntry { + at: Date; + disposition: FireDisposition; + /** Short human label for the disposition (e.g. "queued", "would be coalesced"). */ + label: string; + note: string | null; +} + +const DISPOSITION_LABEL: Record = { + queued: "queued", + coalesced: "would be coalesced", + skipped: "would be skipped", +}; + +/** + * Annotate a list of upcoming fires with how the chosen concurrency policy would + * treat each, assuming the previous run is still in flight when the next fires — + * the worst case that makes the policy's behaviour legible (§3.5). + * + * Pure + deterministic so it can be unit-tested without a clock. + */ +export function previewFirePolicies( + fires: Date[], + concurrencyPolicy: string, +): FirePreviewEntry[] { + return fires.map((at, index) => { + if (index === 0) { + return { + at, + disposition: "queued", + label: DISPOSITION_LABEL.queued, + note: "runs immediately", + }; + } + let disposition: FireDisposition; + switch (concurrencyPolicy) { + case "always_enqueue": + disposition = "queued"; + break; + case "skip_if_active": + disposition = "skipped"; + break; + case "coalesce_if_active": + default: + disposition = "coalesced"; + break; + } + return { + at, + disposition, + label: DISPOSITION_LABEL[disposition], + note: disposition === "queued" ? null : "if the previous run is still active", + }; + }); +} diff --git a/ui/src/lib/routine-run-display.test.ts b/ui/src/lib/routine-run-display.test.ts new file mode 100644 index 00000000000..758b69b1477 --- /dev/null +++ b/ui/src/lib/routine-run-display.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from "vitest"; +import type { RoutineVariable } from "@paperclipai/shared"; +import { dedupedTriggerLabel, runRowSubtitle } from "./routine-run-display"; + +const variables: RoutineVariable[] = [ + { name: "customer", label: null, type: "text", defaultValue: null, required: true, options: [] }, + { name: "retries", label: null, type: "number", defaultValue: null, required: false, options: [] }, +]; + +describe("runRowSubtitle", () => { + it("shows inline variable values for successful runs", () => { + const subtitle = runRowSubtitle( + { + status: "succeeded", + failureReason: null, + triggerPayload: { customer: "Acme", retries: 3, PAPERCLIP_RUN_ID: "ignored" }, + }, + variables, + ); + expect(subtitle).toBe('customer="Acme", retries=3'); + }); + + it("only includes declared routine variables, not builtin payload keys", () => { + const subtitle = runRowSubtitle( + { status: "succeeded", failureReason: null, triggerPayload: { PAPERCLIP_RUN_ID: "x" } }, + variables, + ); + expect(subtitle).toBe(""); + }); + + it("shows the failure reason for failed runs", () => { + const subtitle = runRowSubtitle( + { status: "failed", failureReason: "Cron timed out", triggerPayload: { customer: "Acme" } }, + variables, + ); + expect(subtitle).toBe("Cron timed out"); + }); + + it("falls back to a generic label when a failed run has no reason", () => { + const subtitle = runRowSubtitle( + { status: "failed", failureReason: null, triggerPayload: null }, + variables, + ); + expect(subtitle).toBe("Run failed"); + }); + + it("returns empty when there is no payload", () => { + expect( + runRowSubtitle({ status: "succeeded", failureReason: null, triggerPayload: null }, variables), + ).toBe(""); + }); +}); + +describe("dedupedTriggerLabel", () => { + it("drops the label when it merely restates the kind", () => { + expect(dedupedTriggerLabel({ kind: "schedule", label: "schedule" })).toBeNull(); + }); + + it("keeps a meaningful custom label", () => { + expect(dedupedTriggerLabel({ kind: "schedule", label: "Nightly sync" })).toBe("Nightly sync"); + }); + + it("returns null for missing labels or triggers", () => { + expect(dedupedTriggerLabel({ kind: "webhook", label: null })).toBeNull(); + expect(dedupedTriggerLabel({ kind: "webhook", label: " " })).toBeNull(); + expect(dedupedTriggerLabel(null)).toBeNull(); + }); +}); diff --git a/ui/src/lib/routine-run-display.ts b/ui/src/lib/routine-run-display.ts new file mode 100644 index 00000000000..188d1ceffbd --- /dev/null +++ b/ui/src/lib/routine-run-display.ts @@ -0,0 +1,54 @@ +import type { RoutineRunSummary, RoutineVariable } from "@paperclipai/shared"; + +/** + * Format a single resolved variable value for the runs-row subtitle (§3.6). + * Strings are quoted (`customer="Acme"`); numbers/booleans rendered bare. + */ +function formatVariableValue(value: unknown): string { + if (typeof value === "string") return `"${value}"`; + if (typeof value === "number" || typeof value === "boolean") return String(value); + if (value == null) return "—"; + try { + return JSON.stringify(value); + } catch { + return String(value); + } +} + +/** + * The de-duped trigger label for a run. The kind chip already states the kind, + * so when a trigger has no custom label (`label` falls back to `kind`) we drop + * the redundant text rather than re-stating it. + */ +export function dedupedTriggerLabel( + trigger: Pick | null | undefined, +): string | null { + if (!trigger) return null; + const label = trigger.label?.trim(); + if (!label) return null; + if (label === trigger.kind) return null; + return label; +} + +/** + * Subtitle line for a run row (§3.6): + * - failed runs show the failure reason ("why" without clicking through); + * - other runs show the inline resolved variable values (e.g. `customer="Acme"`). + * Returns an empty string when there is nothing meaningful to show. + */ +export function runRowSubtitle( + run: Pick, + variables: readonly RoutineVariable[] | null | undefined, +): string { + if (run.status === "failed") { + return run.failureReason?.trim() || "Run failed"; + } + const payload = run.triggerPayload; + if (!payload || typeof payload !== "object") return ""; + const parts: string[] = []; + for (const variable of variables ?? []) { + if (!(variable.name in payload)) continue; + parts.push(`${variable.name}=${formatVariableValue((payload as Record)[variable.name])}`); + } + return parts.join(", "); +} diff --git a/ui/storybook/stories/routine-detail-c.stories.tsx b/ui/storybook/stories/routine-detail-c.stories.tsx index 82d61ae19dc..733e0bb4106 100644 --- a/ui/storybook/stories/routine-detail-c.stories.tsx +++ b/ui/storybook/stories/routine-detail-c.stories.tsx @@ -83,7 +83,7 @@ const routine: RoutineDetailType = { concurrencyPolicy: "coalesce_if_active", catchUpPolicy: "skip_missed", variables, - env: { DATABASE_URL: { kind: "secret", secretId: "secret-prod-db", version: "latest" } } as never, + env: { DATABASE_URL: { type: "secret_ref", secretId: "secret-prod-db", version: "latest" } } as never, latestRevisionId: "rev-17", latestRevisionNumber: 17, createdByAgentId: null, @@ -104,9 +104,41 @@ const routine: RoutineDetailType = { }; const routineRuns = [ - { id: "run-1", source: "manual", status: "succeeded", triggeredAt: new Date("2026-06-09T11:48:00Z"), trigger: { label: "manual", kind: "manual" }, linkedIssue: { id: "issue-1", identifier: "PAP-99221" } }, - { id: "run-2", source: "schedule", status: "failed", triggeredAt: new Date("2026-06-08T14:00:00Z"), trigger: { label: "schedule", kind: "schedule" }, linkedIssue: { id: "issue-2", identifier: "PAP-99220" } }, - { id: "run-3", source: "schedule", status: "succeeded", triggeredAt: new Date("2026-06-07T14:00:00Z"), trigger: { label: "schedule", kind: "schedule" }, linkedIssue: { id: "issue-3", identifier: "PAP-99219" } }, + { id: "run-1", source: "manual", status: "succeeded", triggeredAt: new Date("2026-06-09T11:48:00Z"), failureReason: null, triggerPayload: { customer_name: "Acme", deadline: "Fri" }, trigger: { label: "manual", kind: "manual" }, linkedIssue: { id: "issue-1", identifier: "PAP-99221", title: "Weekly digest for Acme" } }, + { id: "run-2", source: "schedule", status: "failed", triggeredAt: new Date("2026-06-08T14:00:00Z"), failureReason: "Cron timed out after 600s", triggerPayload: { customer_name: "Acme" }, trigger: { label: "schedule", kind: "schedule" }, linkedIssue: { id: "issue-2", identifier: "PAP-99220", title: "Weekly digest for Acme" } }, + { id: "run-3", source: "schedule", status: "succeeded", triggeredAt: new Date("2026-06-07T14:00:00Z"), failureReason: null, triggerPayload: { customer_name: "Globex" }, trigger: { label: "schedule", kind: "schedule" }, linkedIssue: { id: "issue-3", identifier: "PAP-99219", title: "Weekly digest for Globex" } }, +] as never; + +function stubSecret(id: string, name: string, latestVersion: number, referenceCount: number) { + return { + id, + companyId: COMPANY_ID, + key: name.toLowerCase(), + name, + provider: "paperclip", + status: "active", + managedMode: "managed", + externalRef: null, + providerConfigId: null, + providerMetadata: null, + latestVersion, + description: null, + lastResolvedAt: now, + lastRotatedAt: null, + deletedAt: null, + createdByAgentId: null, + createdByUserId: null, + referenceCount, + createdAt: now, + updatedAt: now, + }; +} + +const availableSecrets = [ + stubSecret("secret-prod-db", "prod-db", 3, 5), + stubSecret("secret-gh-token", "gh-token", 2, 4), + stubSecret("secret-openai", "openai-key", 1, 2), + stubSecret("secret-stripe", "stripe-key", 1, 1), ] as never; const activity = [ @@ -172,7 +204,7 @@ function makeContext(dirty: boolean, navigate: (s: RoutineSectionKey) => void): secretMessage: null, setSecretMessage: () => {}, copySecretValue: () => {}, - availableSecrets: [], + availableSecrets, createSecret: stubMutation(), agents: storybookAgents, projects: storybookProjects,