[codex] Polish routine layout follow-ups (#7858)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Routines are the recurring-work surface that lets a company keep
operating without a human manually kicking off every task
> - The base routine detail Variation C shell already landed in #7848,
but the follow-up branch still had polish work for scheduling, section
ergonomics, and the list layout
> - Operators need routine edit screens to explain trigger behavior
clearly, keep long detail pages usable on mobile/touch devices, and make
grouped routine lists easier to scan
> - This pull request rebases the remaining branch work onto current
`master`, drops the duplicate commits already merged through #7848, and
keeps only the new routine UI follow-ups
> - The benefit is a cleaner routines workflow without reopening the
already-merged shell work or carrying unrelated lockfile, workflow, or
screenshot changes

## Linked Issues or Issue Description

Refs #7848

Feature follow-up: polish the routines UI after the Variation C
routine-detail shell landed.

Problem / motivation:

- Routine trigger configuration needs clearer previews for manual,
schedule, API, and webhook execution modes.
- Routine detail sections need better responsive spacing and touch
ergonomics.
- The routines list grouping should scan like grouped records instead of
a table with heavy row dividers.
- The routine tests need a React 19-compatible render helper so the
focused routine suite can run in this workspace.

Proposed solution:

- Add cron-fire preview helpers and routine-run display helpers with
focused tests.
- Expand the routine editable and operate sections with richer trigger,
variable, run, activity, and history presentation.
- Adjust the routine detail shell and sub-sidebar spacing for
mobile/touch layout.
- Update grouped routine list presentation to use bordered group headers
with borderless rows.
- Switch affected routine tests to the repo's `flushSync` render-helper
pattern.

Alternatives considered:

- Leaving the duplicate pre-#7848 commits in the branch would recreate
conflicts and make the PR review much larger than the remaining change.
- Keeping grouped routine rows inside one bordered table was simpler,
but made the grouping hierarchy less legible.

Roadmap alignment:

- ROADMAP.md lists Scheduled Routines as a core shipped capability and
Output/Enforced Outcomes as ongoing priorities. This is polish on that
existing routines capability, not a new roadmap-level feature.

## What Changed

- Added routine scheduling preview helpers and tests for
cron/manual/API/webhook fire-policy display.
- Added routine run display helpers and tests for deduped trigger labels
and run-row subtitles.
- Polished routine detail sections, including trigger summaries, operate
views, and env/variable editing ergonomics.
- Adjusted routine detail page and sub-sidebar spacing so the
title/header area is less pinned and touch layouts center better.
- Reworked the routines list grouped layout so group headers are
bordered cards and routine rows are borderless inside each group.
- Added Storybook coverage for the routines list grouped layout and
updated the existing routine detail story.
- Repaired routine tests to use `flushSync` helpers compatible with the
installed React 19 runtime.

## Verification

- `pnpm exec vitest run ui/src/lib/cron-fires.test.ts
ui/src/lib/routine-run-display.test.ts ui/src/pages/Routines.test.tsx
ui/src/components/RoutineSubSidebar.test.tsx
ui/src/components/RoutineSaveBar.test.tsx`
  - Result: 5 test files passed, 37 tests passed.
- Confirmed the rebased PR diff does not include `pnpm-lock.yaml`,
`.github/workflows/*`, or committed screenshots.
- Confirmed `origin/master` is an ancestor of the pushed branch head
after rebase.

## Risks

- Medium UI risk: this touches the routine detail and routine list
surfaces, so visual regressions are possible in edge cases not covered
by the focused tests.
- Low data risk: no schema, migration, server API, or lockfile changes
are included.
- Review note: the branch intentionally force-pushed after rebasing
because the original first three commits were already merged through
#7848.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI Codex, GPT-5-based coding agent runtime, with repository
shell/tool access. Exact hosted runtime model identifier and
context-window size were not exposed in the execution environment.

## 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 run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Dotta
2026-06-09 18:55:01 -05:00
committed by GitHub
parent e3aada1df2
commit fae7e920a9
17 changed files with 1207 additions and 152 deletions
+148 -46
View File
@@ -1,11 +1,35 @@
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import type { CompanySecret, EnvBinding, SecretVersionSelector } from "@paperclipai/shared"; 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 { cn } from "../lib/utils";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
const inputClass = 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"; "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 = { type Row = {
key: string; key: string;
source: "plain" | "secret"; source: "plain" | "secret";
@@ -69,11 +93,17 @@ export function EnvVarEditor({
secrets, secrets,
onCreateSecret, onCreateSecret,
onChange, onChange,
recentlyUsedSecrets,
}: { }: {
value: Record<string, EnvBinding>; value: Record<string, EnvBinding>;
secrets: CompanySecret[]; secrets: CompanySecret[];
onCreateSecret: (name: string, value: string) => Promise<CompanySecret>; onCreateSecret: (name: string, value: string) => Promise<CompanySecret>;
onChange: (env: Record<string, EnvBinding> | undefined) => void; onChange: (env: Record<string, EnvBinding> | 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<Row[]>(() => toRows(value)); const [rows, setRows] = useState<Row[]>(() => toRows(value));
const [sealError, setSealError] = useState<string | null>(null); const [sealError, setSealError] = useState<string | null>(null);
@@ -140,6 +170,26 @@ export function EnvVarEditor({
emit(next); 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];
let target: Row;
if (trailing && !trailing.key && !trailing.plainValue && !trailing.secretId) {
target = trailing;
} else {
target = emptyRow();
next.push(target);
}
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) { function defaultSecretName(key: string) {
return key return key
.trim() .trim()
@@ -185,62 +235,86 @@ export function EnvVarEditor({
value={row.key} value={row.key}
onChange={(event) => updateRow(index, { key: event.target.value })} onChange={(event) => updateRow(index, { key: event.target.value })}
/> />
<select <Select
className={cn(inputClass, "flex-[1] bg-background")}
value={row.source} value={row.source}
onChange={(event) => onValueChange={(next) =>
updateRow(index, { updateRow(index, {
source: event.target.value === "secret" ? "secret" : "plain", source: next === "secret" ? "secret" : "plain",
...(event.target.value === "plain" ? { secretId: "" } : {}), ...(next === "plain" ? { secretId: "" } : {}),
}) })
} }
> >
<option value="plain">Plain</option> <SelectTrigger className={cn(selectTriggerClass, "flex-[1]")} aria-label="Binding mode">
<option value="secret">Secret</option> <SelectValue />
</select> </SelectTrigger>
<SelectContent>
<SelectItem value="plain">Plain</SelectItem>
<SelectItem value="secret">Secret</SelectItem>
</SelectContent>
</Select>
{row.source === "secret" ? ( {row.source === "secret" ? (
<> <>
<select <Select
className={cn(inputClass, "flex-[3] bg-background", row.secretId && !secrets.some((s) => s.id === row.secretId) && "border-destructive text-destructive")} value={row.secretId || SECRET_UNSET}
value={row.secretId} onValueChange={(next) =>
onChange={(event) => updateRow(index, { secretId: event.target.value })} updateRow(index, { secretId: next === SECRET_UNSET ? "" : next })
}
> >
<option value="">Select secret...</option> <SelectTrigger
{row.secretId && !secrets.some((s) => s.id === row.secretId) ? ( aria-label="Secret"
<option value={row.secretId}>Missing ({row.secretId.slice(0, 8)})</option> className={cn(
) : null} selectTriggerClass,
{secrets.map((secret) => ( "flex-[3]",
<option key={secret.id} value={secret.id}> row.secretId &&
{secret.name} !secrets.some((s) => s.id === row.secretId) &&
{secret.status !== "active" ? ` (${secret.status})` : ""} "border-destructive text-destructive",
</option> )}
))} >
</select> <SelectValue placeholder="Select secret..." />
<select </SelectTrigger>
className={cn(inputClass, "flex-[1] bg-background")} <SelectContent>
{row.secretId && !secrets.some((s) => s.id === row.secretId) ? (
<SelectItem value={row.secretId}>
Missing ({row.secretId.slice(0, 8)})
</SelectItem>
) : null}
{secrets.map((secret) => (
<SelectItem key={secret.id} value={secret.id}>
{secret.name}
{secret.status !== "active" ? ` (${secret.status})` : ""}
</SelectItem>
))}
</SelectContent>
</Select>
<Select
value={row.version === "latest" ? "latest" : String(row.version)} value={row.version === "latest" ? "latest" : String(row.version)}
onChange={(event) => { onValueChange={(raw) =>
const raw = event.target.value; updateRow(index, {
updateRow(index, { version: raw === "latest" ? "latest" : Number.parseInt(raw, 10) }); version: raw === "latest" ? "latest" : Number.parseInt(raw, 10),
}} })
}
disabled={!row.secretId} disabled={!row.secretId}
aria-label="Version"
> >
<option value="latest">latest</option> <SelectTrigger className={cn(selectTriggerClass, "flex-[1]")} aria-label="Version">
{(() => { <SelectValue />
const selected = secrets.find((s) => s.id === row.secretId); </SelectTrigger>
if (!selected) return null; <SelectContent>
return Array.from({ length: Math.max(0, selected.latestVersion) }, (_, idx) => { <SelectItem value="latest">latest</SelectItem>
const version = selected.latestVersion - idx; {(() => {
if (version <= 0) return null; const selected = secrets.find((s) => s.id === row.secretId);
return ( if (!selected) return null;
<option key={version} value={version}> return Array.from({ length: Math.max(0, selected.latestVersion) }, (_, idx) => {
v{version} const version = selected.latestVersion - idx;
</option> if (version <= 0) return null;
); return (
}); <SelectItem key={version} value={String(version)}>
})()} v{version}
</select> </SelectItem>
);
});
})()}
</SelectContent>
</Select>
<button <button
type="button" type="button"
className="inline-flex items-center rounded-md border border-border px-2 py-0.5 text-xs text-muted-foreground hover:bg-accent/50 transition-colors shrink-0" className="inline-flex items-center rounded-md border border-border px-2 py-0.5 text-xs text-muted-foreground hover:bg-accent/50 transition-colors shrink-0"
@@ -284,6 +358,34 @@ export function EnvVarEditor({
</div> </div>
); );
})} })}
{(() => {
const boundIds = new Set(
rows.filter((row) => row.source === "secret" && row.secretId).map((row) => row.secretId),
);
const quick = (recentlyUsedSecrets ?? [])
.filter((secret) => secret.status === "active" && !boundIds.has(secret.id))
.slice(0, 8);
if (quick.length === 0) return null;
return (
<div className="flex flex-wrap items-center gap-1.5 pt-0.5">
<span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground/70">
<KeyRound className="h-3 w-3" />
Recently used:
</span>
{quick.map((secret) => (
<button
key={secret.id}
type="button"
onClick={() => bindRecentSecret(secret)}
className="inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-mono text-[11px] text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
title={`Bind ${secret.name}`}
>
+ {secret.name}
</button>
))}
</div>
);
})()}
{sealError && <p className="text-[11px] text-destructive">{sealError}</p>} {sealError && <p className="text-[11px] text-destructive">{sealError}</p>}
{(() => { {(() => {
const issues: { key: string; reason: string }[] = []; const issues: { key: string; reason: string }[] = [];
+6 -1
View File
@@ -63,6 +63,7 @@ export function RoutineListRow<TRoutine extends RoutineListRowItem>({
disableRunNow = false, disableRunNow = false,
disableToggle = false, disableToggle = false,
hideArchiveAction = false, hideArchiveAction = false,
divider = true,
onRunNow, onRunNow,
onToggleEnabled, onToggleEnabled,
onToggleArchived, onToggleArchived,
@@ -80,6 +81,8 @@ export function RoutineListRow<TRoutine extends RoutineListRowItem>({
disableRunNow?: boolean; disableRunNow?: boolean;
disableToggle?: boolean; disableToggle?: boolean;
hideArchiveAction?: boolean; hideArchiveAction?: boolean;
/** Render a bottom divider between consecutive rows. Off when the group is its own card. */
divider?: boolean;
onRunNow: (routine: TRoutine) => void; onRunNow: (routine: TRoutine) => void;
onToggleEnabled: (routine: TRoutine, enabled: boolean) => void; onToggleEnabled: (routine: TRoutine, enabled: boolean) => void;
onToggleArchived?: (routine: TRoutine) => void; onToggleArchived?: (routine: TRoutine) => void;
@@ -95,7 +98,9 @@ export function RoutineListRow<TRoutine extends RoutineListRowItem>({
return ( return (
<Link <Link
to={href} to={href}
className="group flex flex-col gap-3 border-b border-border px-3 py-3 transition-colors hover:bg-accent/50 last:border-b-0 sm:flex-row sm:items-center no-underline text-inherit" className={`group flex flex-col gap-3 px-3 py-3 transition-colors hover:bg-accent/50 sm:flex-row sm:items-center no-underline text-inherit${
divider ? " border-b border-border last:border-b-0" : ""
}`}
> >
<div className="min-w-0 flex-1 space-y-1.5"> <div className="min-w-0 flex-1 space-y-1.5">
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
+6 -1
View File
@@ -1,11 +1,16 @@
// @vitest-environment jsdom // @vitest-environment jsdom
import { act } from "react"; import type React from "react";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { RoutineSaveBar } from "./RoutineSaveBar"; import { RoutineSaveBar } from "./RoutineSaveBar";
import type { RoutineHistoryDirtyFieldDescriptor } from "./RoutineHistoryTab"; import type { RoutineHistoryDirtyFieldDescriptor } from "./RoutineHistoryTab";
function act(callback: () => void) {
flushSync(callback);
}
let container: HTMLDivElement; let container: HTMLDivElement;
let root: ReturnType<typeof createRoot>; let root: ReturnType<typeof createRoot>;
+6 -1
View File
@@ -1,6 +1,7 @@
// @vitest-environment jsdom // @vitest-environment jsdom
import { act, type AnchorHTMLAttributes, type ReactNode } from "react"; import type { AnchorHTMLAttributes, ReactNode } from "react";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -22,6 +23,10 @@ vi.mock("@/lib/router", () => ({
import { RoutineSubSidebar } from "./RoutineSubSidebar"; import { RoutineSubSidebar } from "./RoutineSubSidebar";
import type { RoutineSectionKey } from "./routine-sections/context"; import type { RoutineSectionKey } from "./routine-sections/context";
function act(callback: () => void) {
flushSync(callback);
}
let container: HTMLDivElement; let container: HTMLDivElement;
let root: ReturnType<typeof createRoot>; let root: ReturnType<typeof createRoot>;
+2 -2
View File
@@ -110,7 +110,7 @@ export function RoutineSubSidebar({
return ( return (
<nav <nav
aria-label="Routine sections" aria-label="Routine sections"
className="sticky top-14 hidden max-h-[calc(100dvh-3.5rem)] w-52 shrink-0 flex-col gap-4 self-start overflow-y-auto border-r border-border bg-sidebar/30 px-3 py-4 md:flex" className="sticky top-0 hidden max-h-[100dvh] w-52 shrink-0 flex-col gap-4 self-start overflow-y-auto border-r border-border bg-sidebar/30 px-3 py-4 md:flex"
> >
{NAV_GROUPS.map((group) => ( {NAV_GROUPS.map((group) => (
<div key={group.label} className="flex flex-col gap-0.5"> <div key={group.label} className="flex flex-col gap-0.5">
@@ -174,7 +174,7 @@ export function RoutineSectionPicker({
isSectionDirty: (section: RoutineSectionKey) => boolean; isSectionDirty: (section: RoutineSectionKey) => boolean;
}) { }) {
return ( return (
<div className="sticky top-14 z-10 border-b border-border bg-background px-4 py-2 md:hidden"> <div className="sticky top-0 z-10 border-b border-border bg-background px-4 py-2 md:hidden">
<Select <Select
value={activeSection} value={activeSection}
onValueChange={(value) => { onValueChange={(value) => {
@@ -1,4 +1,4 @@
import { useMemo } from "react"; import { useMemo, useState } from "react";
import { import {
ArrowRight, ArrowRight,
Braces, Braces,
@@ -6,6 +6,8 @@ import {
Edit3, Edit3,
KeyRound, KeyRound,
Play, Play,
Plus,
X,
} from "lucide-react"; } from "lucide-react";
import { Card, CardContent } from "@/components/ui/card"; import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
@@ -20,6 +22,8 @@ import {
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { RadioCardGroup } from "@/components/ui/radio-card"; 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 { timeAgo } from "../../lib/timeAgo";
import { EmptyState } from "../EmptyState"; import { EmptyState } from "../EmptyState";
import { InlineEntitySelector } from "../InlineEntitySelector"; import { InlineEntitySelector } from "../InlineEntitySelector";
@@ -30,7 +34,7 @@ import { RoutineVariablesEditor, RoutineVariablesHint } from "../RoutineVariable
import { RoutineTriggerCard } from "../RoutineTriggerCard"; import { RoutineTriggerCard } from "../RoutineTriggerCard";
import { EnvVarEditor } from "../EnvVarEditor"; import { EnvVarEditor } from "../EnvVarEditor";
import { useRoutineDetail } from "./context"; import { useRoutineDetail } from "./context";
import type { EnvBinding } from "@paperclipai/shared"; import type { EnvBinding, RoutineDetail as RoutineDetailType } from "@paperclipai/shared";
const concurrencyPolicyOptions = [ const concurrencyPolicyOptions = [
{ {
@@ -336,10 +340,39 @@ function SummaryCard({
export function TriggersSection() { export function TriggersSection() {
const ctx = useRoutineDetail(); const ctx = useRoutineDetail();
const { routine, newTrigger, setNewTrigger, createTrigger, updateTrigger, deleteTrigger, rotateTrigger } = ctx; const { routine, newTrigger, setNewTrigger, createTrigger, updateTrigger, deleteTrigger, rotateTrigger } = ctx;
const [addOpen, setAddOpen] = useState(false);
return ( return (
<div className="space-y-4"> <div className="space-y-4">
{/* Add trigger form */} {/* 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"> <div className="space-y-3 rounded-lg border border-border p-4">
<p className="text-sm font-medium">Add trigger</p> <p className="text-sm font-medium">Add trigger</p>
<div className="grid gap-3 md:grid-cols-2"> <div className="grid gap-3 md:grid-cols-2">
@@ -412,16 +445,29 @@ export function TriggersSection() {
</> </>
)} )}
</div> </div>
<div className="flex items-center justify-end"> <div className="flex items-center justify-end gap-2">
<Button size="sm" onClick={() => createTrigger.mutate()} disabled={createTrigger.isPending}> <Button size="sm" variant="ghost" onClick={() => setAddOpen(false)}>
Cancel
</Button>
<Button
size="sm"
onClick={() => createTrigger.mutate(undefined, { onSuccess: () => setAddOpen(false) })}
disabled={createTrigger.isPending}
>
{createTrigger.isPending ? "Adding..." : "Add trigger"} {createTrigger.isPending ? "Adding..." : "Add trigger"}
</Button> </Button>
</div> </div>
</div> </div>
) : null}
{/* Existing triggers */} {/* Existing triggers */}
{routine.triggers.length === 0 ? ( {routine.triggers.length === 0 ? (
<EmptyState icon={Clock3} message="No triggers yet." /> <EmptyState
icon={Clock3}
message="No triggers yet."
action="Add a schedule"
onAction={() => setAddOpen(true)}
/>
) : ( ) : (
<div className="space-y-3"> <div className="space-y-3">
{routine.triggers.map((trigger) => ( {routine.triggers.map((trigger) => (
@@ -481,6 +527,21 @@ export function SecretsSection() {
const ctx = useRoutineDetail(); const ctx = useRoutineDetail();
const { editDraft, setEditDraft, availableSecrets, createSecret, secretMessage, copySecretValue } = ctx; 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 ( return (
<div className="space-y-4"> <div className="space-y-4">
<div className="rounded-md border border-border bg-muted/20 px-4 py-3 text-xs text-muted-foreground"> <div className="rounded-md border border-border bg-muted/20 px-4 py-3 text-xs text-muted-foreground">
@@ -520,6 +581,7 @@ export function SecretsSection() {
<EnvVarEditor <EnvVarEditor
value={(editDraft.env ?? {}) as Record<string, EnvBinding>} value={(editDraft.env ?? {}) as Record<string, EnvBinding>}
secrets={availableSecrets} secrets={availableSecrets}
recentlyUsedSecrets={recentlyUsedSecrets}
onCreateSecret={async (name, value) => createSecret.mutateAsync({ name, value })} onCreateSecret={async (name, value) => createSecret.mutateAsync({ name, value })}
onChange={(env) => setEditDraft((current) => ({ ...current, env: env ?? null }))} onChange={(env) => setEditDraft((current) => ({ ...current, env: env ?? null }))}
/> />
@@ -529,7 +591,7 @@ export function SecretsSection() {
export function DeliverySection() { export function DeliverySection() {
const ctx = useRoutineDetail(); const ctx = useRoutineDetail();
const { editDraft, setEditDraft } = ctx; const { editDraft, setEditDraft, routine } = ctx;
return ( return (
<div className="space-y-6"> <div className="space-y-6">
@@ -559,6 +621,102 @@ export function DeliverySection() {
options={catchUpPolicyOptions} options={catchUpPolicyOptions}
/> />
</div> </div>
<NextFiresPreview
triggers={routine.triggers}
concurrencyPolicy={editDraft.concurrencyPolicy}
/>
</div> </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-[0.18em] 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-[11px] 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,24 +1,90 @@
import { useMemo } from "react"; import { useMemo, useState } from "react";
import { Activity as ActivityIcon, Play } from "lucide-react"; import { Activity as ActivityIcon, Play, SlidersHorizontal } from "lucide-react";
import { Link } from "@/lib/router";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { timeAgo } from "../../lib/timeAgo"; import { timeAgo } from "../../lib/timeAgo";
import { runRowSubtitle, dedupedTriggerLabel } from "../../lib/routine-run-display";
import { EmptyState } from "../EmptyState"; import { EmptyState } from "../EmptyState";
import { EntityRow } from "../EntityRow";
import { FilterBar, type FilterValue } from "../FilterBar";
import { LiveRunWidget } from "../LiveRunWidget"; import { LiveRunWidget } from "../LiveRunWidget";
import { RoutineHistoryTab } from "../RoutineHistoryTab"; import { RoutineHistoryTab } from "../RoutineHistoryTab";
import { RoutineActivityRow } from "../RoutineActivityRow"; import { RoutineActivityRow } from "../RoutineActivityRow";
import { useRoutineDetail } from "./context"; 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() { export function RunsSection() {
const ctx = useRoutineDetail(); const ctx = useRoutineDetail();
const { routine, routineRuns, hasLiveRun, activeIssueId, onOpenRunDialog } = ctx; 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<FilterValue[]>(() => {
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 ( return (
<div className="space-y-4"> <div className="space-y-4">
{hasLiveRun && activeIssueId ? ( {hasLiveRun && activeIssueId ? (
<LiveRunWidget issueId={activeIssueId} companyId={routine.companyId} /> <LiveRunWidget issueId={activeIssueId} companyId={routine.companyId} />
) : null} ) : null}
{runs.length === 0 ? ( {runs.length === 0 ? (
<EmptyState <EmptyState
icon={Play} icon={Play}
@@ -27,39 +93,105 @@ export function RunsSection() {
onAction={onOpenRunDialog} onAction={onOpenRunDialog}
/> />
) : ( ) : (
<div className="divide-y divide-border rounded-lg border border-border"> <>
{runs.map((run) => ( {/* Filter chips row (§3.6) */}
<div key={run.id} className="flex items-center justify-between px-3 py-2 text-sm"> <div className="space-y-2">
<div className="flex min-w-0 items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
<Badge variant="outline" className="shrink-0"> <Select value={sourceFilter} onValueChange={setSourceFilter}>
{run.source} <SelectTrigger size="sm" className="h-8 w-auto gap-1.5 text-xs" aria-label="Filter by source">
</Badge> <span className="text-muted-foreground">Source:</span>
<Badge <SelectValue />
variant={run.status === "failed" ? "destructive" : "secondary"} </SelectTrigger>
className="shrink-0" <SelectContent>
> <SelectItem value="any">any</SelectItem>
{run.status.replaceAll("_", " ")} {sourceOptions.map((source) => (
</Badge> <SelectItem key={source} value={source}>
{run.trigger ? ( {source}
<span className="truncate text-muted-foreground"> </SelectItem>
{run.trigger.label ?? run.trigger.kind} ))}
</span> </SelectContent>
) : null} </Select>
{run.linkedIssue ? ( <Select value={statusFilter} onValueChange={setStatusFilter}>
<Link <SelectTrigger size="sm" className="h-8 w-auto gap-1.5 text-xs" aria-label="Filter by status">
to={`/issues/${run.linkedIssue.identifier ?? run.linkedIssue.id}`} <span className="text-muted-foreground">Status:</span>
className="truncate text-muted-foreground hover:underline" <SelectValue />
> </SelectTrigger>
{run.linkedIssue.identifier ?? run.linkedIssue.id.slice(0, 8)} <SelectContent>
</Link> <SelectItem value="any">any</SelectItem>
) : null} {statusOptions.map((status) => (
</div> <SelectItem key={status} value={status}>
<span className="ml-2 shrink-0 text-xs text-muted-foreground"> {status.replaceAll("_", " ")}
{timeAgo(run.triggeredAt)} </SelectItem>
</span> ))}
</SelectContent>
</Select>
<Select value={dateFilter} onValueChange={setDateFilter}>
<SelectTrigger size="sm" className="h-8 w-auto gap-1.5 text-xs" aria-label="Filter by date">
<span className="text-muted-foreground">Date:</span>
<SelectValue />
</SelectTrigger>
<SelectContent>
{DATE_WINDOW_OPTIONS.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div> </div>
))} <FilterBar filters={activeFilters} onRemove={removeFilter} onClear={clearFilters} />
</div> </div>
{filtered.length === 0 ? (
<EmptyState
icon={SlidersHorizontal}
message="No runs match these filters."
action="Clear filters"
onAction={clearFilters}
/>
) : (
<div className="rounded-lg border border-border">
{filtered.map((run) => {
const label = dedupedTriggerLabel(run.trigger);
const title = run.linkedIssue?.title ?? label ?? "Run";
return (
<EntityRow
key={run.id}
leading={
<>
<Badge variant="outline" className="shrink-0">
{run.source}
</Badge>
<Badge
variant={run.status === "failed" ? "destructive" : "secondary"}
className="shrink-0"
>
{run.status.replaceAll("_", " ")}
</Badge>
</>
}
identifier={
run.linkedIssue
? run.linkedIssue.identifier ?? run.linkedIssue.id.slice(0, 8)
: undefined
}
title={title}
subtitle={runRowSubtitle(run, routine.variables)}
reserveSubtitleSpace
trailing={
<span className="text-xs text-muted-foreground">{timeAgo(run.triggeredAt)}</span>
}
to={
run.linkedIssue
? `/issues/${run.linkedIssue.identifier ?? run.linkedIssue.id}`
: undefined
}
/>
);
})}
</div>
)}
</>
)} )}
</div> </div>
); );
+5 -1
View File
@@ -222,7 +222,11 @@
[data-size="icon-xs"], [data-size="icon-xs"],
[data-size="icon-sm"], [data-size="icon-sm"],
input[type="checkbox"], input[type="checkbox"],
input[type="radio"] { input[type="radio"],
/* Auto-resizing title fields are vertically centered inside their own bar,
which already provides the touch area; the 44px floor would top-align the
single line of text and push it too high (notably on mobile Safari). */
textarea[data-autosize-title] {
min-height: 0; min-height: 0;
} }
} }
+98
View File
@@ -0,0 +1,98 @@
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("uses OR semantics when day-of-month and day-of-week are both restricted", () => {
const after = new Date("2026-06-09T10:00:00Z");
const fires = nextCronFires("0 9 15 * 5", 3, { after, timeZone: "UTC" });
expect(fires.map((d) => d.toISOString())).toEqual([
"2026-06-12T09:00:00.000Z",
"2026-06-15T09:00:00.000Z",
"2026-06-19T09: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");
});
});
+272
View File
@@ -0,0 +1,272 @@
/**
* 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<string, number> = {
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[];
daysOfMonthWildcard: boolean;
daysOfWeekWildcard: boolean;
}
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<number>();
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`);
}
}
function coversEntireField(values: number[], spec: FieldSpec): boolean {
return values.length === spec.max - spec.min + 1 && values[0] === spec.min && values.at(-1) === spec.max;
}
/** 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 {
const daysOfMonth = parseField(tokens[2]!, FIELD_SPECS[2]!);
const daysOfWeek = parseField(tokens[4]!, FIELD_SPECS[4]!);
return {
minutes: parseField(tokens[0]!, FIELD_SPECS[0]!),
hours: parseField(tokens[1]!, FIELD_SPECS[1]!),
daysOfMonth,
months: parseField(tokens[3]!, FIELD_SPECS[3]!),
daysOfWeek,
daysOfMonthWildcard: coversEntireField(daysOfMonth, FIELD_SPECS[2]!),
daysOfWeekWildcard: coversEntireField(daysOfWeek, 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<string, string> = {};
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 {
const dayOfMonthMatches = cron.daysOfMonth.includes(parts.day);
const dayOfWeekMatches = cron.daysOfWeek.includes(parts.weekday);
const dayMatches =
!cron.daysOfMonthWildcard && !cron.daysOfWeekWildcard
? dayOfMonthMatches || dayOfWeekMatches
: dayOfMonthMatches && dayOfWeekMatches;
return (
cron.minutes.includes(parts.minute) &&
cron.hours.includes(parts.hour) &&
cron.months.includes(parts.month) &&
dayMatches
);
}
/**
* 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[] = [];
// Preview-only bound: cap sparse or impossible schedules before they can stall the UI.
const maxIterations = 2 * 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<FireDisposition, string> = {
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",
};
});
}
+68
View File
@@ -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();
});
});
+54
View File
@@ -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<RoutineRunSummary["trigger"] & object, "kind" | "label"> | 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<RoutineRunSummary, "status" | "failureReason" | "triggerPayload">,
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<string, unknown>)[variable.name])}`);
}
return parts.join(", ");
}
+5 -4
View File
@@ -782,12 +782,13 @@ export function RoutineDetail() {
</a> </a>
<div className="-m-4 flex min-h-full flex-col md:-m-6"> <div className="-m-4 flex min-h-full flex-col md:-m-6">
{/* Slim page header */} {/* Slim page header — scrolls with the page (not sticky) */}
<header className="sticky top-0 z-20 flex h-14 shrink-0 items-center gap-3 border-b border-border bg-background px-6"> <header className="flex h-14 shrink-0 items-center gap-3 border-b border-border bg-background px-6">
<div className="flex min-w-0 flex-1 items-center gap-3"> <div className="flex min-w-0 flex-1 items-center gap-3">
<textarea <textarea
ref={titleInputRef} ref={titleInputRef}
className="min-w-0 flex-1 resize-none overflow-hidden bg-transparent text-base font-semibold outline-none placeholder:text-muted-foreground/50" data-autosize-title
className="min-w-0 flex-1 resize-none overflow-hidden bg-transparent text-base font-semibold leading-7 outline-none placeholder:text-muted-foreground/50"
placeholder="Routine title" placeholder="Routine title"
rows={1} rows={1}
value={editDraft.title} value={editDraft.title}
@@ -848,7 +849,7 @@ export function RoutineDetail() {
<main <main
id="routine-section" id="routine-section"
role="main" role="main"
className="min-w-0 flex-1 px-4 py-6 md:px-8" className="min-w-0 flex-1 px-4 pb-6 pt-10 md:px-8"
> >
<section <section
aria-labelledby="routine-section-title" aria-labelledby="routine-section-title"
+10 -1
View File
@@ -1,6 +1,7 @@
// @vitest-environment jsdom // @vitest-environment jsdom
import { act, type AnchorHTMLAttributes, type ReactNode } from "react"; import type { AnchorHTMLAttributes, ReactNode } from "react";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Issue, RoutineListItem } from "@paperclipai/shared"; import type { Issue, RoutineListItem } from "@paperclipai/shared";
@@ -9,6 +10,14 @@ import { Routines, buildRoutineGroups, sortRoutines } from "./Routines";
let currentSearch = ""; let currentSearch = "";
async function act(callback: () => void | Promise<void>) {
let result: void | Promise<void> = undefined;
flushSync(() => {
result = callback();
});
await result;
}
const navigateMock = vi.fn(); const navigateMock = vi.fn();
const routinesListMock = vi.fn<(companyId: string) => Promise<RoutineListItem[]>>(); const routinesListMock = vi.fn<(companyId: string) => Promise<RoutineListItem[]>>();
const issuesListMock = vi.fn<(companyId: string, filters?: Record<string, unknown>) => Promise<Issue[]>>(); const issuesListMock = vi.fn<(companyId: string, filters?: Record<string, unknown>) => Promise<Issue[]>>();
+52 -44
View File
@@ -885,51 +885,59 @@ export function Routines() {
/> />
</div> </div>
) : ( ) : (
<div className="rounded-lg border border-border"> <div className="flex flex-col gap-3">
{routineGroups.map((group) => ( {routineGroups.map((group) => {
<Collapsible const isOpen = !routineViewState.collapsedGroups.includes(group.key);
key={group.key} return (
open={!routineViewState.collapsedGroups.includes(group.key)} <Collapsible
onOpenChange={(open) => { key={group.key}
updateRoutineView({ open={isOpen}
collapsedGroups: open onOpenChange={(open) => {
? routineViewState.collapsedGroups.filter((item) => item !== group.key) updateRoutineView({
: [...routineViewState.collapsedGroups, group.key], collapsedGroups: open
}); ? routineViewState.collapsedGroups.filter((item) => item !== group.key)
}} : [...routineViewState.collapsedGroups, group.key],
> });
{group.label ? ( }}
<div className="flex items-center gap-2 border-b border-border px-3 py-2"> >
<CollapsibleTrigger className="flex items-center gap-1.5"> {group.label ? (
<ChevronRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform [[data-state=open]>&]:rotate-90" /> <div
<span className="text-sm font-semibold uppercase tracking-wide"> className={`flex items-center gap-2 rounded-lg border border-border px-3 py-2${
{group.label} isOpen ? " mb-1" : ""
}`}
>
<CollapsibleTrigger className="flex items-center gap-1.5">
<ChevronRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform [[data-state=open]>&]:rotate-90" />
<span className="text-sm font-semibold uppercase tracking-wide">
{group.label}
</span>
</CollapsibleTrigger>
<span className="text-xs text-muted-foreground">
{group.items.length}
</span> </span>
</CollapsibleTrigger> </div>
<span className="text-xs text-muted-foreground"> ) : null}
{group.items.length} <CollapsibleContent>
</span> {group.items.map((routine) => (
</div> <RoutineListRow
) : null} key={routine.id}
<CollapsibleContent> routine={routine}
{group.items.map((routine) => ( projectById={projectById}
<RoutineListRow agentById={agentById}
key={routine.id} runningRoutineId={runningRoutineId}
routine={routine} statusMutationRoutineId={statusMutationRoutineId}
projectById={projectById} href={`/routines/${routine.id}`}
agentById={agentById} runNowButton
runningRoutineId={runningRoutineId} divider={false}
statusMutationRoutineId={statusMutationRoutineId} onRunNow={handleRunNow}
href={`/routines/${routine.id}`} onToggleEnabled={handleToggleEnabled}
runNowButton onToggleArchived={handleToggleArchived}
onRunNow={handleRunNow} />
onToggleEnabled={handleToggleEnabled} ))}
onToggleArchived={handleToggleArchived} </CollapsibleContent>
/> </Collapsible>
))} );
</CollapsibleContent> })}
</Collapsible>
))}
</div> </div>
)} )}
</div> </div>
@@ -83,7 +83,7 @@ const routine: RoutineDetailType = {
concurrencyPolicy: "coalesce_if_active", concurrencyPolicy: "coalesce_if_active",
catchUpPolicy: "skip_missed", catchUpPolicy: "skip_missed",
variables, 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", latestRevisionId: "rev-17",
latestRevisionNumber: 17, latestRevisionNumber: 17,
createdByAgentId: null, createdByAgentId: null,
@@ -104,9 +104,41 @@ const routine: RoutineDetailType = {
}; };
const routineRuns = [ 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-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"), trigger: { label: "schedule", kind: "schedule" }, linkedIssue: { id: "issue-2", identifier: "PAP-99220" } }, { 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"), trigger: { label: "schedule", kind: "schedule" }, linkedIssue: { id: "issue-3", identifier: "PAP-99219" } }, { 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; ] as never;
const activity = [ const activity = [
@@ -172,7 +204,7 @@ function makeContext(dirty: boolean, navigate: (s: RoutineSectionKey) => void):
secretMessage: null, secretMessage: null,
setSecretMessage: () => {}, setSecretMessage: () => {},
copySecretValue: () => {}, copySecretValue: () => {},
availableSecrets: [], availableSecrets,
createSecret: stubMutation(), createSecret: stubMutation(),
agents: storybookAgents, agents: storybookAgents,
projects: storybookProjects, projects: storybookProjects,
@@ -238,8 +270,8 @@ function RoutineCShell({ initialSection = "overview", dirty = false }: { initial
return ( return (
<RoutineDetailContext.Provider value={ctx}> <RoutineDetailContext.Provider value={ctx}>
<div className="flex h-[900px] flex-col bg-background text-foreground"> <div className="flex h-[900px] flex-col overflow-y-auto bg-background text-foreground">
<header className="sticky top-0 z-20 flex h-14 shrink-0 items-center gap-3 border-b border-border bg-background px-6"> <header className="flex h-14 shrink-0 items-center gap-3 border-b border-border bg-background px-6">
<div className="flex min-w-0 flex-1 items-center gap-3"> <div className="flex min-w-0 flex-1 items-center gap-3">
<span className="truncate text-base font-semibold">{routine.title}</span> <span className="truncate text-base font-semibold">{routine.title}</span>
<Badge variant="outline" className="hidden shrink-0 gap-1.5 text-xs text-muted-foreground sm:inline-flex"> <Badge variant="outline" className="hidden shrink-0 gap-1.5 text-xs text-muted-foreground sm:inline-flex">
@@ -265,7 +297,7 @@ function RoutineCShell({ initialSection = "overview", dirty = false }: { initial
hasLiveRun={false} hasLiveRun={false}
onNavigate={setSection} onNavigate={setSection}
/> />
<main className="min-w-0 flex-1 overflow-y-auto px-4 py-6 md:px-8"> <main className="min-w-0 flex-1 px-4 pb-6 pt-10 md:px-8">
<section className={isEditable ? "mx-auto w-full max-w-3xl" : "w-full"}> <section className={isEditable ? "mx-auto w-full max-w-3xl" : "w-full"}>
<h2 className="mb-4 text-lg font-semibold">{SECTION_TITLES[section]}</h2> <h2 className="mb-4 text-lg font-semibold">{SECTION_TITLES[section]}</h2>
<SectionBody section={section} /> <SectionBody section={section} />
@@ -0,0 +1,102 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { useState } from "react";
import { ChevronRight } from "lucide-react";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import {
RoutineListRow,
type RoutineListAgentSummary,
type RoutineListProjectSummary,
type RoutineListRowItem,
} from "@/components/RoutineList";
const projectById = new Map<string, RoutineListProjectSummary>([
["p1", { name: "Board UI", color: "#6366f1" }],
["p2", { name: "Growth", color: "#10b981" }],
]);
const agentById = new Map<string, RoutineListAgentSummary>([
["a1", { name: "CodexCoder", icon: null }],
["a2", { name: "Digest Bot", icon: null }],
]);
type Group = { key: string; label: string | null; items: RoutineListRowItem[] };
const GROUPS: Group[] = [
{
key: "p1",
label: "Board UI",
items: [
{ id: "r1", title: "Weekly digest", status: "active", projectId: "p1", assigneeAgentId: "a2", lastRun: { triggeredAt: "2026-06-09T08:00:00Z", status: "succeeded" } },
{ id: "r2", title: "Triage stale issues", status: "active", projectId: "p1", assigneeAgentId: "a1", lastRun: { triggeredAt: "2026-06-08T08:00:00Z", status: "succeeded" } },
{ id: "r3", title: "Nightly changelog draft", status: "paused", projectId: "p1", assigneeAgentId: "a1", lastRun: null },
],
},
{
key: "p2",
label: "Growth",
items: [
{ id: "r4", title: "Lead enrichment sweep", status: "active", projectId: "p2", assigneeAgentId: "a1", lastRun: { triggeredAt: "2026-06-09T06:00:00Z", status: "running" } },
{ id: "r5", title: "Outbound follow-ups", status: "active", projectId: "p2", assigneeAgentId: "a2", lastRun: { triggeredAt: "2026-06-07T06:00:00Z", status: "failed" } },
],
},
];
function GroupedList() {
const [collapsed, setCollapsed] = useState<string[]>([]);
return (
<div className="mx-auto max-w-4xl p-6">
<div className="flex flex-col gap-3">
{GROUPS.map((group) => {
const isOpen = !collapsed.includes(group.key);
return (
<Collapsible
key={group.key}
open={isOpen}
onOpenChange={(open) =>
setCollapsed((prev) => (open ? prev.filter((k) => k !== group.key) : [...prev, group.key]))
}
>
{group.label ? (
<div className={`flex items-center gap-2 rounded-lg border border-border px-3 py-2${isOpen ? " mb-1" : ""}`}>
<CollapsibleTrigger className="flex items-center gap-1.5">
<ChevronRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform [[data-state=open]>&]:rotate-90" />
<span className="text-sm font-semibold uppercase tracking-wide">{group.label}</span>
</CollapsibleTrigger>
<span className="text-xs text-muted-foreground">{group.items.length}</span>
</div>
) : null}
<CollapsibleContent>
{group.items.map((routine) => (
<RoutineListRow
key={routine.id}
routine={routine}
projectById={projectById}
agentById={agentById}
runningRoutineId={null}
statusMutationRoutineId={null}
href={`#${routine.id}`}
runNowButton
divider={false}
onRunNow={() => {}}
onToggleEnabled={() => {}}
onToggleArchived={() => {}}
/>
))}
</CollapsibleContent>
</Collapsible>
);
})}
</div>
</div>
);
}
const meta: Meta<typeof GroupedList> = {
title: "Product/Routines · List (grouped cards)",
component: GroupedList,
parameters: { layout: "fullscreen" },
};
export default meta;
type Story = StoryObj<typeof GroupedList>;
export const GroupedCards: Story = {};