import { useId, useState, type ReactNode } from "react";
import type { Issue, RoutineDetail, RoutineTrigger } from "@paperclipai/shared";
import {
ArrowLeft,
CalendarClock,
Check,
ChevronDown,
Copy,
GitBranch,
History,
KeyRound,
MessageSquare,
MoreHorizontal,
Pencil,
Radar,
ScrollText,
Sparkles,
Terminal,
Trash2,
Webhook,
} from "lucide-react";
import { AgentAvatar, type AvatarAgent } from "@/components/AgentAvatar";
import { RunButton } from "@/components/AgentActionButtons";
import { MarkdownBody } from "@/components/MarkdownBody";
import { ScheduleEditor } from "@/components/ScheduleEditor";
import { TaskSummaryList } from "@/components/TaskSummaryList";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { ToggleSwitch } from "@/components/ui/toggle-switch";
import { deriveInitials } from "@/components/Identity";
import { copyTextToClipboard } from "@/lib/clipboard";
import { Link } from "@/lib/router";
import { cn } from "@/lib/utils";
import {
ROUTINE_STATE_LABELS,
WEBHOOK_HEALTH_LABELS,
customRunRules,
describeScheduleTrigger,
formatNextRun,
instructionsPreview,
nextScheduledRun,
routineAutomationState,
routinePausedNotice,
routineStatusDetail,
webhookHealth,
webhookTitle,
} from "./routine-summary";
export type RoutinePerson = { id: string; name: string; avatarUrl?: string | null };
export type RoutinePageAgent = AvatarAgent & { id: string; name: string; urlKey?: string | null };
export type RoutinePageProject = { id: string; name: string; color?: string | null; urlKey?: string | null };
/** A responsibility this routine is under: linked itself, or through its project. */
export type RoutineResponsibility = {
id: string;
title: string;
areaTitle?: string | null;
via: "direct" | "project";
};
export type RoutineScheduleChange = { cronExpression: string; timezone: string };
export type RoutinePageProps = {
routine: RoutineDetail;
agent: RoutinePageAgent | null;
project: RoutinePageProject | null;
responsibleUser: RoutinePerson | null;
/** Leave undefined while areas of responsibility are switched off; the field is then hidden. */
responsibilities?: readonly RoutineResponsibility[];
/** Tasks this routine created, newest first. Pass the pages loaded so far. */
history: readonly Issue[];
historyLoading?: boolean;
/** Shown in place of the task list when History could not be loaded. */
historyError?: ReactNode;
/** More tasks exist beyond the loaded pages. */
hasMoreHistory?: boolean;
loadingMoreHistory?: boolean;
onLoadMoreHistory?: () => void;
/** Recent runs that made no task because an earlier run was still working. */
skippedRunCount?: number;
/** Open comments on the instructions. */
instructionCommentCount?: number;
statusPending?: boolean;
onToggleActive: (active: boolean) => void;
onEdit: () => void;
onSaveSchedule: (triggerId: string, change: RoutineScheduleChange) => void;
onRemoveSchedule: (triggerId: string) => void;
onOpenWebhook: (trigger: RoutineTrigger) => void;
/** Pauses or resumes one schedule, standing check or API trigger. Omit to hide Pause/Resume. */
onSetTriggerPaused?: (triggerId: string, paused: boolean) => void;
/** Removes a standing check or API trigger. Omit to keep those rows read-only. */
onRemoveTrigger?: (trigger: RoutineTrigger) => void;
/** Triggers removed from this page, offered back with Undo under Repeats. */
removedTriggers?: readonly RoutineTrigger[];
onRestoreTrigger?: (trigger: RoutineTrigger) => void;
onOpenInstructionComments?: () => void;
/** Show the whole instructions, e.g. while their comments are open. */
instructionsExpanded?: boolean;
/** Wraps the rendered instructions, e.g. with the comment layer that anchors to them. */
renderInstructionsBody?: (body: ReactNode) => ReactNode;
/** Router state for task links in History, so a task can lead back here. */
historyLinkState?: unknown;
};
function Field({ label, children, action }: { label: string; children: ReactNode; action?: ReactNode }) {
const headingId = useId();
return (
{label}
{action}
{children}
);
}
function PersonAvatar({ person }: { person: RoutinePerson }) {
return (
{person.avatarUrl ? : null}
{deriveInitials(person.name)}
);
}
function localTimezone(): string {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
} catch {
return "UTC";
}
}
const rowButtonClass =
"group -mx-2 flex min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-accent/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
function ScheduleRow({
trigger,
routineActive,
onSave,
onRemove,
onSetPaused,
}: {
trigger: RoutineTrigger;
routineActive: boolean;
onSave: (change: RoutineScheduleChange) => void;
onRemove: () => void;
onSetPaused?: (paused: boolean) => void;
}) {
const [open, setOpen] = useState(false);
const [cron, setCron] = useState(trigger.cronExpression ?? "0 9 * * 1-5");
const [valid, setValid] = useState(true);
const timezone = trigger.timezone ?? localTimezone();
const dimmed = !trigger.enabled || !routineActive;
return (
{
setOpen(next);
if (next) setCron(trigger.cronExpression ?? "0 9 * * 1-5");
}}
>
{describeScheduleTrigger(trigger)}
{trigger.enabled ? timezone : "Paused"}
{/* Wider when Pause/Resume joins Remove and Save, so the footer stays on one row. */}
Times are in {timezone}.
{
setOpen(false);
onRemove();
}}
>
Remove schedule
{onSetPaused ? (
{
setOpen(false);
onSetPaused(trigger.enabled);
}}
>
{trigger.enabled ? "Pause" : "Resume"}
) : null}
{
setOpen(false);
onSave({ cronExpression: cron, timezone });
}}
>
Save schedule
);
}
function WebhookRow({
trigger,
routineActive,
onOpen,
}: {
trigger: RoutineTrigger;
routineActive: boolean;
onOpen: () => void;
}) {
const health = webhookHealth(trigger);
const ignored = !routineActive && health !== "setup" && health !== "testing";
const Icon = trigger.signingMode === "github_hmac" ? GitBranch : Webhook;
return (
{webhookTitle(trigger)}
{ignored ? "Ignoring events" : WEBHOOK_HEALTH_LABELS[health]}
);
}
/** A standing check or API trigger: nothing to configure, but it can be paused or removed. */
function StaticTriggerRow({
icon: Icon,
title,
detail,
description,
trigger,
routineActive,
onSetPaused,
onRemove,
}: {
icon: typeof Radar;
title: string;
detail: string;
description: string;
trigger: RoutineTrigger;
routineActive: boolean;
onSetPaused?: (paused: boolean) => void;
onRemove?: () => void;
}) {
const [open, setOpen] = useState(false);
const dimmed = !trigger.enabled || !routineActive;
const content = (
<>
{title}
{trigger.enabled ? detail : "Paused"}
>
);
if (!onSetPaused && !onRemove) {
return {content}
;
}
return (
{content}
{description}
{onRemove ? (
{
setOpen(false);
onRemove();
}}
>
Remove
) : }
{onSetPaused ? (
{
setOpen(false);
onSetPaused(trigger.enabled);
}}
>
{trigger.enabled ? "Pause" : "Resume"}
) : null}
);
}
/** How a removed trigger is named in its "removed. Undo" line. */
export function triggerTitle(trigger: RoutineTrigger): string {
if (trigger.kind === "schedule") return describeScheduleTrigger(trigger);
if (trigger.kind === "webhook") return webhookTitle(trigger);
if (trigger.kind === "heartbeat") return "Standing check";
return "API trigger";
}
function Instructions({
markdown,
commentCount = 0,
onOpenComments,
onEdit,
forceExpanded = false,
renderBody = (body) => body,
}: {
markdown: string;
commentCount?: number;
onOpenComments?: () => void;
onEdit: () => void;
forceExpanded?: boolean;
renderBody?: (body: ReactNode) => ReactNode;
}) {
const [expandedState, setExpanded] = useState(false);
const expanded = expandedState || forceExpanded;
const [copied, setCopied] = useState(false);
const { preview, truncated } = instructionsPreview(markdown);
const empty = markdown.trim().length === 0;
return (
{commentCount > 0 ? (
{commentCount} {commentCount === 1 ? "comment" : "comments"}
) : null}
{
await copyTextToClipboard(markdown);
setCopied(true);
window.setTimeout(() => setCopied(false), 1500);
}}
>
{copied ? : }
)}
>
{empty ? (
No instructions yet. The agent only gets the title.
Add instructions
) : (
<>
{/* Comments anchor to the full text, so the comment layer only wraps it when the whole text shows. */}
{expanded || !truncated
? renderBody(
{markdown}
,
)
: (
{preview}
)}
{truncated && !forceExpanded ? (
setExpanded((value) => !value)}
>
{expanded ? "Show less" : "Show all"}
) : null}
>
)}
);
}
export function RoutinePage({
routine,
agent,
project,
responsibleUser,
responsibilities,
history,
historyLoading = false,
historyError,
hasMoreHistory = false,
loadingMoreHistory = false,
onLoadMoreHistory,
skippedRunCount = 0,
instructionCommentCount,
statusPending = false,
onToggleActive,
onEdit,
onSaveSchedule,
onRemoveSchedule,
onSetTriggerPaused,
onRemoveTrigger,
removedTriggers = [],
onRestoreTrigger,
onOpenWebhook,
onOpenInstructionComments,
instructionsExpanded = false,
renderInstructionsBody,
historyLinkState,
}: RoutinePageProps) {
const state = routineAutomationState(routine);
const schedules = routine.triggers.filter((trigger) => trigger.kind === "schedule");
const webhooks = routine.triggers.filter((trigger) => trigger.kind === "webhook");
const standingCheck = routine.triggers.find((trigger) => trigger.kind === "heartbeat");
const apiTrigger = routine.triggers.find((trigger) => trigger.kind === "api");
const nextRun = state === "active" ? nextScheduledRun(routine.triggers) : null;
const hasEnabledWebhook = webhooks.some((trigger) => trigger.enabled && !trigger.setupPending);
const runRules = customRunRules(routine);
const secretNames = Object.keys(routine.env ?? {});
const archived = state === "archived";
const active = state === "active";
const hasSchedule = schedules.some((trigger) => trigger.enabled);
const pausedNotice = routinePausedNotice({ state, hasWebhooks: webhooks.length > 0, hasSchedule });
const statusDetail = routineStatusDetail({ state, nextRun, hasEnabledWebhook, hasStandingCheck: Boolean(standingCheck) });
return (
{routine.title}
{routine.managedByPlugin ? (
Managed by {routine.managedByPlugin.pluginDisplayName}
) : null}
{ROUTINE_STATE_LABELS[state]}
{statusDetail ? {statusDetail} : null}
{pausedNotice ? {pausedNotice}
: null}
{state === "draft" ? (
Choose a default agent
{" "}
to turn this routine on.
) : null}
{schedules.map((trigger) => (
onSaveSchedule(trigger.id, change)}
onRemove={() => onRemoveSchedule(trigger.id)}
onSetPaused={onSetTriggerPaused ? (paused) => onSetTriggerPaused(trigger.id, paused) : undefined}
/>
))}
{webhooks.map((trigger) => (
onOpenWebhook(trigger)} />
))}
{standingCheck ? (
onSetTriggerPaused(standingCheck.id, paused) : undefined}
onRemove={onRemoveTrigger ? () => onRemoveTrigger(standingCheck) : undefined}
/>
) : null}
{apiTrigger ? (
onSetTriggerPaused(apiTrigger.id, paused) : undefined}
onRemove={onRemoveTrigger ? () => onRemoveTrigger(apiTrigger) : undefined}
/>
) : null}
{removedTriggers.map((trigger) => (
{triggerTitle(trigger)} removed.
{onRestoreTrigger ? (
onRestoreTrigger(trigger)}>Undo
) : null}
))}
{routine.triggers.length === 0 && removedTriggers.length === 0 ? (
Doesn’t repeat. Runs only when you start it.
) : null}
{agent ? (
{agent.name}
) : (
Choose an agent
)}
{responsibleUser ? (
{responsibleUser.name}
) : (
No one yet
)}
{project ? (
{project.name}
) : (
No project
)}
{responsibilities ? (
{responsibilities.length === 0 ? (
None
) : (
{responsibilities.map((responsibility) => (
{responsibility.title}
{responsibility.via === "project" && project
? `Through ${project.name}`
: responsibility.areaTitle ?? ""}
))}
)}
) : null}
{routine.variables.length > 0 ? (
{routine.variables.map((variable) => (
{variable.label || variable.name}
{variable.defaultValue != null && variable.defaultValue !== ""
? `Usually ${String(variable.defaultValue)}`
: variable.required
? "Required"
: "Optional"}
))}
) : null}
{secretNames.length > 0 ? (
{secretNames.map((name) => (
{name}
))}
) : null}
{runRules.length > 0 ? (
{runRules.map((rule) => {rule} )}
) : null}
{historyError && history.length === 0 ? (
historyError
) : historyLoading ? (
Loading tasks…
) : history.length === 0 ? (
{state === "active" && nextRun
? `No tasks yet. The first one starts ${formatNextRun(nextRun)}.`
: "No tasks yet. Each run creates a task here."}
) : (
)}
{historyError && history.length > 0 ? historyError : null}
{hasMoreHistory && history.length > 0 ? (
{loadingMoreHistory ? "Loading…" : "Load more"}
) : null}
{skippedRunCount > 0 ? (
{skippedRunCount === 1 ? "1 run was" : `${skippedRunCount} runs were`} folded into a task that was still in
progress.
) : null}
);
}
/** Version history and the audit log open as their own view, with a way back to the routine. */
export function RoutineSubpage({
routineTitle,
title,
onBack,
children,
}: {
routineTitle: string;
title: string;
onBack: () => void;
children: ReactNode;
}) {
return (
);
}
export type RoutinePageActionsProps = {
archived?: boolean;
runPending?: boolean;
/** Start with the menu open, for review. */
defaultMenuOpen?: boolean;
onEdit: () => void;
onRunNow: () => void;
onOpenVersionHistory: () => void;
onOpenAuditLog: () => void;
onArchive: () => void;
onRestore?: () => void;
};
/** Header controls for the routine page: edit, a short overflow menu, and Run now. */
export function RoutinePageActions({
archived = false,
runPending = false,
defaultMenuOpen = false,
onEdit,
onRunNow,
onOpenVersionHistory,
onOpenAuditLog,
onArchive,
onRestore,
}: RoutinePageActionsProps) {
return (
{archived ? null : (
)}
Version history
Audit log
{archived && onRestore ? (
Restore routine
) : (
Archive routine
)}
{archived ? null :
}
);
}