import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react"; import type { CompanySecret, EnvBinding, RoutineEnvConfig, RoutineTrigger, RoutineVariable } from "@paperclipai/shared"; import { GitBranch, Plus, Webhook, X } from "lucide-react"; import { AgentAvatar } from "@/components/AgentAvatar"; import { InlineEntitySelector } from "@/components/InlineEntitySelector"; import { MarkdownEditor, type MarkdownEditorRef, type MentionOption } from "@/components/MarkdownEditor"; import { RoutineVariablesEditor } from "@/components/RoutineVariablesEditor"; import { ScheduleEditor } from "@/components/ScheduleEditor"; import { EnvironmentVariablesEditor, type EnvironmentVariablesEditorHandle } from "@/components/environment-variables-editor"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { deriveInitials } from "@/components/Identity"; import { cn } from "@/lib/utils"; import type { RoutinePageAgent, RoutinePageProject, RoutinePerson } from "./RoutinePage"; import { WEBHOOK_HEALTH_LABELS, webhookHealth, webhookTitle } from "./routine-summary"; export type RoutineFormDraft = { title: string; description: string; projectId: string; assigneeAgentId: string; responsibleUserId: string; /** The responsibility this routine is filed under itself; empty for none. */ responsibilityId: string; variables: RoutineVariable[]; env: RoutineEnvConfig | null; schedule: { cronExpression: string; timezone: string } | null; }; export const EMPTY_ROUTINE_FORM_DRAFT: RoutineFormDraft = { title: "", description: "", projectId: "", assigneeAgentId: "", responsibleUserId: "", responsibilityId: "", variables: [], env: null, schedule: null, }; export type RoutineResponsibilityOption = { id: string; title: string; areaTitle?: string | null; /** Projects filed under it. A routine in one of them is already under this responsibility. */ projectIds?: readonly string[]; }; export type RoutineEditDialogProps = { open: boolean; onOpenChange: (open: boolean) => void; mode?: "edit" | "create"; initial: RoutineFormDraft; agents: readonly RoutinePageAgent[]; projects: readonly RoutinePageProject[]; people: readonly RoutinePerson[]; secrets: readonly CompanySecret[]; /** Leave undefined while areas of responsibility are switched off; the field is then hidden. */ responsibilities?: readonly RoutineResponsibilityOption[]; mentions?: MentionOption[]; /** False when this person may not reassign responsibility. */ canChangeResponsibleUser?: boolean; saving?: boolean; /** Someone else saved this routine while the form was open. */ saveConflict?: boolean; error?: string | null; onSave: (draft: RoutineFormDraft) => void; onReloadLatest?: () => void; onCreateSecret: (name: string, value: string) => Promise; /** Saved webhooks. They are created and changed right away, apart from the form's Save. */ webhooks?: readonly RoutineTrigger[]; /** Opens the webhook dialog; `null` starts a new webhook. Omit while creating a routine. */ onOpenWebhook?: (trigger: RoutineTrigger | null) => void; onRemoveWebhook?: (trigger: RoutineTrigger) => void; /** Webhooks removed while this form is open, offered back with Undo. */ removedWebhooks?: readonly RoutineTrigger[]; onRestoreWebhook?: (trigger: RoutineTrigger) => void; /** The webhook dialog, rendered inside this one so both stay open together. */ children?: ReactNode; }; const SCHEDULE_TIMEZONES = ["America/Los_Angeles", "America/Chicago", "America/New_York", "Europe/London", "UTC"]; function localTimezone(): string { try { return Intl.DateTimeFormat().resolvedOptions().timeZone; } catch { return "UTC"; } } export function RoutineEditDialog({ open, onOpenChange, mode = "edit", initial, agents, projects, people, secrets, responsibilities, mentions, canChangeResponsibleUser = true, saving = false, saveConflict = false, error = null, onSave, onReloadLatest, onCreateSecret, webhooks = [], onOpenWebhook, onRemoveWebhook, removedWebhooks = [], onRestoreWebhook, children, }: RoutineEditDialogProps) { const [draft, setDraft] = useState(initial); const [secretsOpen, setSecretsOpen] = useState(() => Object.keys(initial.env ?? {}).length > 0); const [scheduleValid, setScheduleValid] = useState(true); const [confirmingDiscard, setConfirmingDiscard] = useState(false); const editorRef = useRef(null); const secretsRef = useRef(null); /** Secrets rows being typed that the secrets editor has not promoted into the draft yet. */ const [secretsDirty, setSecretsDirty] = useState(false); const titleId = useId(); useEffect(() => { if (!open) return; setDraft(initial); setSecretsOpen(Object.keys(initial.env ?? {}).length > 0); setConfirmingDiscard(false); setSecretsDirty(false); }, [initial, open]); const dirty = useMemo(() => JSON.stringify(draft) !== JSON.stringify(initial), [draft, initial]) || secretsDirty; const patch = (change: Partial) => setDraft((current) => ({ ...current, ...change })); const agentById = useMemo(() => new Map(agents.map((agent) => [agent.id, agent])), [agents]); const projectById = useMemo(() => new Map(projects.map((project) => [project.id, project])), [projects]); const personById = useMemo(() => new Map(people.map((person) => [person.id, person])), [people]); const responsibilityById = useMemo( () => new Map((responsibilities ?? []).map((responsibility) => [responsibility.id, responsibility])), [responsibilities], ); const throughProject = draft.projectId ? (responsibilities ?? []).find( (responsibility) => responsibility.id !== draft.responsibilityId && responsibility.projectIds?.includes(draft.projectId), ) ?? null : null; const canSave = draft.title.trim().length > 0 && scheduleValid && !saving && !saveConflict && (mode === "create" || dirty); /** Saves the draft, including secrets rows still being typed. */ const submit = () => { if (!canSave) return; const flushed = secretsRef.current?.flushPendingDraft() ?? null; onSave(flushed ? { ...draft, env: Object.keys(flushed).length > 0 ? flushed : null } : draft); }; /** Escape, the close button and Cancel all come here. Nothing closes while a save is running, so a failed save keeps the draft and its error. */ const requestClose = () => { if (saving) return; if (dirty) setConfirmingDiscard(true); else onOpenChange(false); }; const personOption = (id: string) => { const person = personById.get(id); if (!person) return null; return ( <> {person.name} ); }; return ( (next ? onOpenChange(true) : requestClose())}> {mode === "create" ? "New routine" : "Edit routine"} {mode === "create" ? "Describe the work, then choose who does it and when." : "Change what this routine does, who does it, and when."}
{ event.preventDefault(); submit(); }} >
patch({ title: event.target.value })} />
{/* The frame owns the border and the drag handle; the editor scrolls inside it. */}
{ if (event.target === event.currentTarget) editorRef.current?.focus(); }} > patch({ description })} placeholder="What should the agent do each time? Type / for skills and routines, @ to mention, {{name}} to ask for a value." contentClassName="text-sm leading-6" mentions={mentions} submitKey="mod-enter" onSubmit={submit} />
patch({ variables })} variant="compact" />
{draft.schedule ? (
setDraft((current) => (current.schedule ? { ...current, schedule: { ...current.schedule, cronExpression } } : current)) } onValidityChange={setScheduleValid} trailing={( )} />
) : ( )}
{onOpenWebhook ? (
{removedWebhooks.map((trigger) => (

{webhookTitle(trigger)} removed.

))} {webhooks.length > 0 ? (
    {webhooks.map((trigger) => { const health = webhookHealth(trigger); const Icon = trigger.signingMode === "github_hmac" ? GitBranch : Webhook; return (
  • {onRemoveWebhook ? ( ) : null}
  • ); })}
) : null}
) : null}
({ id: agent.id, label: agent.name }))} placeholder="Choose an agent" noneLabel="No default agent" searchPlaceholder="Search agents…" emptyMessage="No agents found." disablePortal className="h-9 w-full justify-start" onChange={(assigneeAgentId) => patch({ assigneeAgentId })} renderTriggerValue={(option) => { const agent = option ? agentById.get(option.id) : null; return agent ? ( <> {agent.name} ) : ( Choose an agent ); }} renderOption={(option) => { const agent = agentById.get(option.id); return ( <> {agent ? : null} {option.label} ); }} />
({ id: project.id, label: project.name }))} placeholder="No project" noneLabel="No project" searchPlaceholder="Search projects…" emptyMessage="No projects found." disablePortal className="h-9 w-full justify-start" onChange={(projectId) => patch({ projectId })} renderTriggerValue={(option) => { const project = option ? projectById.get(option.id) : null; return project ? ( <> {project.name} ) : ( No project ); }} renderOption={(option) => { const project = projectById.get(option.id); return ( <> {project ? ( ) : null} {option.label} ); }} />
{responsibilities ? (
({ id: responsibility.id, label: responsibility.title, searchText: responsibility.areaTitle ?? "", }))} placeholder="No responsibility" noneLabel="No responsibility" searchPlaceholder="Search responsibilities…" emptyMessage="No responsibilities found." disablePortal className="h-9 w-full justify-start" onChange={(responsibilityId) => patch({ responsibilityId })} renderTriggerValue={(option) => option?.id ? {option.label} : No responsibility } renderOption={(option) => { const areaTitle = responsibilityById.get(option.id)?.areaTitle; return ( <> {option.label} {areaTitle ? {areaTitle} : null} ); }} /> {throughProject ? (

Already under {throughProject.title} through {projectById.get(draft.projectId)?.name ?? "its project"}.

) : null}
) : null}
({ id: person.id, label: person.name }))} placeholder="Choose a person" noneLabel="No one" // A responsible user can be changed but not cleared; "No one" only shows while there is none. hideNone={Boolean(initial.responsibleUserId)} searchPlaceholder="Find a person…" emptyMessage="No people found." disablePortal disabled={!canChangeResponsibleUser} className="h-9 w-full justify-start" onChange={(responsibleUserId) => patch({ responsibleUserId })} renderTriggerValue={(option) => (option && personOption(option.id)) || Choose a person } renderOption={(option) => personOption(option.id) ?? {option.label}} />
{secretsOpen ? ( } secrets={secrets} onCreateSecret={onCreateSecret} onChange={(env) => patch({ env: env && Object.keys(env).length > 0 ? env : null })} footerHint={null} hideDraftActions startWithEmptyRow addLabel="Add secret" /> ) : ( )}
{children}
); }