@tickernelz/paperclip-pro-ui 2026.927.2 → 2026.927.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{Agents.production-BZi6klJA.js → Agents.production-DmAeIRUO.js} +2 -2
- package/dist/assets/{CompanyActivity.production-hUjwDlzb.js → CompanyActivity.production-BHajCPR3.js} +1 -1
- package/dist/assets/{CompanyExport-BQmo7amJ.js → CompanyExport-B-SFGdV7.js} +1 -1
- package/dist/assets/{CompanySkills.production-HqWy0fEs.js → CompanySkills.production-CuwwxUVf.js} +1 -1
- package/dist/assets/{Costs.production-CdRBCdli.js → Costs.production-51LUilni.js} +1 -1
- package/dist/assets/{OrgChart.production-C_I93OQO.js → OrgChart.production-CD4WHR5p.js} +1 -1
- package/dist/assets/{RoutineDetail.production-BF19HlVi.js → RoutineDetail.production-CRLOTbjy.js} +1 -1
- package/dist/assets/{Routines.production-BN-xoFb_.js → Routines.production-zXFYwdPi.js} +1 -1
- package/dist/assets/{definition-Ds8jy0r3.js → definition-D3MqX5GE.js} +1 -1
- package/dist/assets/{index-zttiya6r.js → index-BF7JM92C.js} +4 -4
- package/dist/index.html +1 -1
- package/dist/sw.js +1 -1
- package/package.json +1 -1
package/dist/assets/{RoutineDetail.production-BF19HlVi.js → RoutineDetail.production-CRLOTbjy.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var ot=Object.defineProperty;var i=(s,a)=>ot(s,"name",{value:a,configurable:!0});import{i as Le}from"./rolldown-runtime-ZpX3ckPj.js";import{Fr as ct,Lr as lt,Pr as dt,S as ut,U as mt,Y as p,Yn as pt,nr as L,tr as U}from"./createLucideIcon-r3v6fbGz.js";import{Z as Ee,o as ht,r as oe,st as gt}from"./router-DyZkoSkG.js";import{Ct as xt,bt as yt,lr as vt,t as ft,vt as Oe,wt as bt,xt as jt,yt as wt}from"./RoutineRunVariablesDialog-IRX4TLng.js";import{Q as Nt}from"./mention-chips-DXumPrOR.js";import{s as kt,t as St}from"./zap-P-cXfK28.js";import{l as T,t as De}from"./MarkdownEditor-Pip4OXiJ.js";import{v as It}from"./sheet-DeCxNmfl.js";import{t as _e}from"./AgentAvatar-PT82VwmU.js";import{k as Ct}from"./checkbox-CmMbs2PZ.js";import{_ as At,s as Pt,t as O}from"./label-C2ddSDJj.js";import{t as Rt}from"./agents-BlSzFh-1.js";import{g as Tt}from"./StatusIcon-BuUYMqqU.js";import{r as Et,t as te}from"./EmptyState-DPcc0zYh.js";import{c as de,i as ue,n as me,s as pe,t as he}from"./select-mS22eY6T.js";import{r as Ot,t as Dt}from"./save-DUnPDT6R.js";import{k as _t,t as E}from"./button-CAPbz11u.js";import{n as Mt,t as qt}from"./clipboard-CYJ5Q78m.js";import{t as Ft}from"./heartbeats-CK_aXmx5.js";import{t as xe}from"./badge-Cf7ihb3q.js";import{t as V}from"./input-DpsS9it-.js";import{i as Kt,o as Lt}from"./company-members-BcZm1g8Q.js";import{r as Ut,t as Wt}from"./card-dmVcp3AX.js";import{t as $t}from"./PageSkeleton-DHjTwRT3.js";import{A as Vt,B as Gt,Cn as Qt,F as zt,G as Q,H as Bt,Ht,I as Jt,K as Ue,L as Yt,M as We,N as Zt,P as Xt,Qt as Me,R as es,Rn as ye,Tt as ts,U as qe,Un as ve,V as ss,Vn as is,Vt as ns,W as $e,Xt as X,fn as as,j as rs,k as os,pn as cs,q as ls,qt as ds,z as us}from"./index-zttiya6r.js";var u=Le(lt(),1);function ms(s,a,n){const c={label:a.label.trim()||null};return s.kind==="schedule"&&(c.cronExpression=a.cronExpression.trim(),c.timezone=s.timezone??n),s.kind==="webhook"&&(c.signingMode=a.signingMode,c.replayWindowSec=Number(a.replayWindowSec||"300")),c}i(ms,"buildRoutineTriggerPatch");var e=Le(ct(),1),ps=["app_webhook","bearer","hmac_sha256","github_hmac","none"],hs=new Set(["app_webhook","bearer","github_hmac","fireflies_hmac","none"]);function gs(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}i(gs,"getLocalTimezone$1");function xs({trigger:s,onSave:a,onRotate:n,onDelete:c,disabled:r}){const[m,l]=(0,u.useState)({label:s.label??"",cronExpression:s.cronExpression??"",signingMode:s.signingMode??"bearer",replayWindowSec:String(s.replayWindowSec??300)});(0,u.useEffect)(()=>{l({label:s.label??"",cronExpression:s.cronExpression??"",signingMode:s.signingMode??"bearer",replayWindowSec:String(s.replayWindowSec??300)})},[s]);const k=s.kind==="schedule"?ye:s.kind==="webhook"?cs:St,I=s.kind==="schedule"?Xt(m.cronExpression):null,M=/fail|error/i.test(s.lastResult??""),C=s.lastResult?.startsWith("Created execution issue ")?"Task created":s.lastResult;return(0,e.jsxs)("form",{"aria-label":`Trigger: ${s.label??s.kind}`,className:"space-y-4 rounded-lg border border-border p-4",onSubmit:i(x=>x.preventDefault(),"onSubmit"),children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium",children:[(0,e.jsx)(k,{className:"h-3.5 w-3.5 shrink-0"}),(0,e.jsx)("span",{className:"truncate",children:s.label??s.kind})]}),I?(0,e.jsx)("p",{id:`cron-readable-${s.id}`,className:"text-xs text-muted-foreground",children:I}):null]}),(0,e.jsxs)("div",{className:"flex shrink-0 items-center gap-2",children:[s.lastResult?(0,e.jsx)(xe,{variant:M?"destructive":"secondary",children:C}):null,(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:s.kind==="schedule"&&s.nextRunAt?`Next: ${new Date(s.nextRunAt).toLocaleString()}`:s.kind==="webhook"?"Webhook":"API"})]})]}),s.kind==="webhook"&&s.webhookUrl&&(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{htmlFor:`webhook-url-${s.id}`,className:"text-xs",children:"Webhook URL"}),(0,e.jsx)(V,{id:`webhook-url-${s.id}`,value:s.webhookUrl,readOnly:!0,onFocus:i(x=>x.target.select(),"onFocus")}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"Send a POST request with Content-Type: application/json. Keep this URL private when signing is disabled."})]}),(0,e.jsxs)("div",{className:"grid gap-3 md:grid-cols-2",children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Label"}),(0,e.jsx)(V,{value:m.label,disabled:r,onChange:i(x=>l(S=>({...S,label:x.target.value})),"onChange")})]}),s.kind==="schedule"&&(0,e.jsxs)("div",{className:"space-y-1.5 md:col-span-2",children:[(0,e.jsx)(O,{className:"text-xs",children:"Schedule"}),(0,e.jsx)(We,{value:m.cronExpression,onChange:i(x=>l(S=>({...S,cronExpression:x})),"onChange")})]}),s.kind==="webhook"&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Signing mode"}),(0,e.jsxs)(he,{value:m.signingMode,onValueChange:i(x=>l(S=>({...S,signingMode:x})),"onValueChange"),disabled:r,children:[(0,e.jsx)(pe,{children:(0,e.jsx)(de,{})}),(0,e.jsx)(me,{children:ps.map(x=>(0,e.jsx)(ue,{value:x,children:x},x))})]})]}),!hs.has(m.signingMode)&&(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Replay window (seconds)"}),(0,e.jsx)(V,{value:m.replayWindowSec,disabled:r,onChange:i(x=>l(S=>({...S,replayWindowSec:x.target.value})),"onChange")})]})]})]}),!r&&(0,e.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[(0,e.jsxs)(E,{variant:"ghost",size:"sm",className:"mr-auto text-muted-foreground hover:text-destructive",onClick:i(()=>c(s.id),"onClick"),children:[(0,e.jsx)(Ct,{className:"mr-1.5 h-3.5 w-3.5"}),"Delete"]}),s.kind==="webhook"&&(0,e.jsxs)(E,{variant:"outline",size:"sm",onClick:i(()=>n(s.id),"onClick"),children:[(0,e.jsx)(It,{className:"mr-1.5 h-3.5 w-3.5"}),"Rotate secret"]}),(0,e.jsxs)(E,{variant:"outline",size:"sm",onClick:i(()=>a(s.id,ms(s,m,gs())),"onClick"),children:[(0,e.jsx)(Dt,{className:"mr-1.5 h-3.5 w-3.5"}),"Save trigger"]})]})]})}i(xs,"RoutineTriggerCard");var ys=[{value:"coalesce_if_active",title:"Coalesce if active",description:"Keep one follow-up run queued while an active run is still working."},{value:"always_enqueue",title:"Always enqueue",description:"Queue every trigger occurrence, even if several runs stack up."},{value:"skip_if_active",title:"Skip if active",description:"Drop overlapping trigger occurrences while the routine is already active."}],vs=[{value:"skip_missed",title:"Skip missed",description:"Ignore schedule windows that were missed while paused."},{value:"enqueue_missed_with_cap",title:"Enqueue missed with cap",description:"Catch up missed schedule windows after recovery; sub-hourly schedules are combined into one catch-up run, slower schedules replay each missed window up to a cap."}],fs=[{value:"always",title:"Run on every scheduled tick",description:"Fire on the schedule no matter what — the default behavior."},{value:"require_external_activity",title:"Skip when there's been no activity since the last run",description:"On a scheduled tick, only run if something happened since the last run that finished. Lets a watcher-style routine stay asleep while the system is settled instead of burning tokens."}],bs=[{value:"company",title:"Company-wide",description:"Any activity across the company counts as a reason to run."},{value:"project",title:"This project",description:"Only activity in the routine's project counts as a reason to run."}],js=["schedule","webhook"],ws=["app_webhook","bearer","hmac_sha256","github_hmac","none"],Ns={bearer:"Send Authorization: Bearer <secret> with each request.",hmac_sha256:"Send X-Paperclip-Timestamp and X-Paperclip-Signature: sha256=<hex>, signing timestamp + a dot + the exact JSON body.",github_hmac:"Accept GitHub-style X-Hub-Signature-256 header (HMAC over raw body, no timestamp).",app_webhook:"Accept a bearer token or an HMAC-SHA256 signature over the exact request body in X-Hub-Signature or X-Hub-Signature-256.",fireflies_hmac:"Signed webhook (legacy).",none:"No authentication — the webhook URL itself acts as a shared secret."},ks=new Set(["app_webhook","bearer","github_hmac","fireflies_hmac","none"]);function Ss({defaultDescriptionAnnotationsOpen:s=!1}={}){const{routine:a,editDraft:n,setEditDraft:c,assigneeOptions:r,projectOptions:m,recentAssigneeIds:l,recentProjectIds:k,agentById:I,projectById:M,currentAssignee:C,currentProject:x,mentionOptions:S,assigneeSelectorRef:D,projectSelectorRef:q,descriptionEditorRef:A,routineRuns:g,activity:b,saveRoutine:j,saveConflict:se,isSectionDirty:f,navigateToSection:P}=Q(),[w,_]=(0,u.useState)(s),o=a.triggers.length,z=(0,u.useMemo)(()=>{const d=a.triggers.filter(y=>y.kind==="schedule"&&y.nextRunAt).map(y=>new Date(y.nextRunAt)).sort((y,G)=>y.getTime()-G.getTime())[0];return d?d.toLocaleString():null},[a.triggers]),W=n.env?Object.keys(n.env).length:0,R=(g??[])[0]??null,B=(b??[]).slice(0,5);return(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsx)("div",{className:"overflow-x-auto overscroll-x-contain",children:(0,e.jsxs)("div",{className:"inline-flex min-w-full flex-wrap items-center gap-2 text-sm text-muted-foreground sm:min-w-max sm:flex-nowrap",children:[(0,e.jsx)("span",{children:"For"}),(0,e.jsx)(Oe,{ref:D,value:n.assigneeAgentId,options:r,recentOptionIds:l,placeholder:"Responsible",noneLabel:"No responsible",searchPlaceholder:"Search responsible...",emptyMessage:"No responsible found.",onChange:i(d=>c(y=>({...y,assigneeAgentId:d})),"onChange"),onConfirm:i(()=>{n.projectId?A.current?.focus():q.current?.focus()},"onConfirm"),renderTriggerValue:i(d=>d?C?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(_e,{agent:C,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,e.jsx)("span",{className:"truncate",children:d.label})]}):(0,e.jsx)("span",{className:"truncate",children:d.label}):(0,e.jsx)("span",{className:"text-muted-foreground",children:"Responsible"}),"renderTriggerValue"),renderOption:i(d=>{if(!d.id)return(0,e.jsx)("span",{className:"truncate",children:d.label});const y=I.get(d.id);return(0,e.jsxs)(e.Fragment,{children:[y?(0,e.jsx)(_e,{agent:y,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,(0,e.jsx)("span",{className:"truncate",children:d.label})]})},"renderOption")}),(0,e.jsx)("span",{children:"in"}),(0,e.jsx)(Oe,{ref:q,value:n.projectId,options:m,recentOptionIds:k,placeholder:"Project",noneLabel:"No project",searchPlaceholder:"Search projects...",emptyMessage:"No projects found.",onChange:i(d=>c(y=>({...y,projectId:d})),"onChange"),onConfirm:i(()=>A.current?.focus(),"onConfirm"),renderTriggerValue:i(d=>d&&x?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:x.color??"var(--project-none)"}}),(0,e.jsx)("span",{className:"truncate",children:d.label})]}):(0,e.jsx)("span",{className:"text-muted-foreground",children:"Project"}),"renderTriggerValue"),renderOption:i(d=>{if(!d.id)return(0,e.jsx)("span",{className:"truncate",children:d.label});const y=M.get(d.id);return(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:y?.color??"var(--project-none)"}}),(0,e.jsx)("span",{className:"truncate",children:d.label})]})},"renderOption")})]})}),a.assigneeAgentId?null:(0,e.jsx)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 p-4 text-sm text-amber-900 dark:text-amber-200",children:"Default agent required. This routine can stay as a draft and still run manually, but automation stays paused until you assign a default agent."}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("div",{className:"flex items-center justify-end",children:a.descriptionDocument?(0,e.jsx)(ns,{issueId:a.id,docKey:"description",target:{kind:"routine",routineId:a.id,documentKey:"description"},panelOpen:w,onToggle:i(()=>_(d=>!d),"onToggle")}):null}),a.descriptionDocument?(0,e.jsx)(Ht,{issueId:a.id,doc:a.descriptionDocument,target:{kind:"routine",routineId:a.id,documentKey:"description"},bodyMarkdown:n.description,draftDirty:f("overview")||j.isPending,draftConflicted:se,historicalPreview:!1,locationHash:typeof window>"u"?"":window.location.hash,panelOpen:w,onPanelOpenChange:_,children:(0,e.jsx)(De,{ref:A,value:n.description,onChange:i(d=>c(y=>({...y,description:d})),"onChange"),placeholder:"Add instructions...",bordered:!1,contentClassName:"min-h-(--sz-120px) text-sm leading-7",mentions:S,onSubmit:i(()=>{!j.isPending&&n.title.trim()&&j.mutate()},"onSubmit")})}):(0,e.jsx)(De,{ref:A,value:n.description,onChange:i(d=>c(y=>({...y,description:d})),"onChange"),placeholder:"Add instructions...",bordered:!1,contentClassName:"min-h-(--sz-120px) text-sm leading-7",mentions:S,onSubmit:i(()=>{!j.isPending&&n.title.trim()&&j.mutate()},"onSubmit")})]}),(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)(ls,{}),(0,e.jsx)(Ue,{title:n.title,description:n.description,value:n.variables,onChange:i(d=>c(y=>({...y,variables:d})),"onChange")})]}),(0,e.jsxs)("div",{className:"grid gap-3 sm:grid-cols-3",children:[(0,e.jsx)(ce,{icon:ye,label:"Triggers",value:o===0?"None":`${o} active`,hint:z?`Next fire ${z}`:"No schedule",to:i(()=>P("triggers"),"to"),ariaLabel:`${o} triggers. Open triggers.`}),(0,e.jsx)(ce,{icon:Mt,label:"Secrets",value:W===0?"None":`${W} bound`,hint:"Manage bound secrets",to:i(()=>P("secrets"),"to"),ariaLabel:`${W} secrets bound. Open secrets.`}),(0,e.jsx)(ce,{icon:At,label:"Last run",value:R?R.status.replaceAll("_"," "):"No runs",hint:R?Ee(R.triggeredAt):"Trigger a run",to:i(()=>P("runs"),"to"),ariaLabel:R?`Last run ${R.status}. Open runs.`:"No runs. Open runs."})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Recent activity"}),B.length===0?(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"No activity yet."}):(0,e.jsxs)("div",{className:"divide-y divide-border/60",children:[B.map(d=>(0,e.jsxs)("div",{className:"flex items-center gap-2 py-1.5 text-xs",children:[(0,e.jsx)(xe,{variant:"outline",className:"shrink-0 font-mono",children:d.action}),(0,e.jsx)("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:d.details&&Object.keys(d.details).length>0?Object.keys(d.details).slice(0,3).join(" · "):""}),(0,e.jsx)("span",{className:"shrink-0 text-muted-foreground/60",children:Ee(d.createdAt)})]},d.id)),(0,e.jsxs)("button",{type:"button",onClick:i(()=>P("activity"),"onClick"),className:"flex items-center gap-1 pt-2 text-xs text-muted-foreground hover:text-foreground",children:["View all activity ",(0,e.jsx)(ve,{className:"h-3 w-3"})]})]})]})]})}i(Ss,"OverviewSection");function ce({icon:s,label:a,value:n,hint:c,to:r,ariaLabel:m}){return(0,e.jsx)("button",{type:"button",onClick:r,"aria-label":m,className:"text-left",children:(0,e.jsx)(Wt,{className:"gap-2 p-4 transition-colors hover:border-border hover:bg-accent/30",children:(0,e.jsxs)(Ut,{className:"space-y-1 p-0",children:[(0,e.jsxs)("div",{className:"flex items-center gap-1.5 text-xs uppercase tracking-wide text-muted-foreground",children:[(0,e.jsx)(s,{className:"h-3.5 w-3.5"}),a,(0,e.jsx)(ve,{className:"ml-auto h-3.5 w-3.5 text-muted-foreground/60"})]}),(0,e.jsx)("p",{className:"text-lg font-semibold",children:n}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:c})]})})})}i(ce,"SummaryCard");function Is(){const{routine:s,newTrigger:a,setNewTrigger:n,createTrigger:c,updateTrigger:r,deleteTrigger:m,rotateTrigger:l,secretMessage:k,copySecretValue:I,setSecretMessage:M}=Q(),[C,x]=(0,u.useState)(!1),[S,D]=(0,u.useState)(!0),q=(0,u.useMemo)(()=>a.kind==="schedule"?Zt(a.cronExpression):null,[a.cronExpression,a.kind]),A=c.isPending||(q?!q.valid||!S:!1);return(0,u.useEffect)(()=>{a.kind!=="schedule"&&D(!0)},[a.kind]),(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsx)("p",{className:"text-sm font-medium text-muted-foreground",children:s.triggers.length===0?"No triggers yet":`${s.triggers.length} trigger${s.triggers.length===1?"":"s"}`}),(0,e.jsx)(E,{size:"sm",variant:C?"secondary":"default",onClick:i(()=>x(g=>!g),"onClick"),"aria-expanded":C,children:C?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(Nt,{className:"mr-1.5 h-3.5 w-3.5"}),"Cancel"]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(_t,{className:"mr-1.5 h-3.5 w-3.5"}),"New trigger"]})})]}),C?(0,e.jsxs)("div",{className:"space-y-3 rounded-lg border border-border p-4",children:[(0,e.jsx)("p",{className:"text-sm font-medium",children:"Add trigger"}),(0,e.jsxs)("div",{className:"grid gap-3 md:grid-cols-2",children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Kind"}),(0,e.jsxs)(he,{value:a.kind,onValueChange:i(g=>n(b=>({...b,kind:g})),"onValueChange"),children:[(0,e.jsx)(pe,{children:(0,e.jsx)(de,{})}),(0,e.jsx)(me,{children:js.map(g=>(0,e.jsx)(ue,{value:g,children:g},g))})]})]}),a.kind==="schedule"&&(0,e.jsxs)("div",{className:"space-y-1.5 md:col-span-2",children:[(0,e.jsx)(O,{className:"text-xs",children:"Schedule"}),(0,e.jsx)(We,{value:a.cronExpression,onChange:i(g=>n(b=>({...b,cronExpression:g})),"onChange"),onValidityChange:D})]}),a.kind==="webhook"&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Signing mode"}),(0,e.jsxs)(he,{value:a.signingMode,onValueChange:i(g=>n(b=>({...b,signingMode:g})),"onValueChange"),children:[(0,e.jsx)(pe,{children:(0,e.jsx)(de,{})}),(0,e.jsx)(me,{children:ws.map(g=>(0,e.jsx)(ue,{value:g,children:g},g))})]}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:Ns[a.signingMode]})]}),!ks.has(a.signingMode)&&(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Replay window (seconds)"}),(0,e.jsx)(V,{value:a.replayWindowSec,onChange:i(g=>n(b=>({...b,replayWindowSec:g.target.value})),"onChange")})]})]})]}),(0,e.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[(0,e.jsx)(E,{size:"sm",variant:"ghost",onClick:i(()=>x(!1),"onClick"),children:"Cancel"}),(0,e.jsx)(E,{size:"sm",onClick:i(()=>c.mutate(void 0,{onSuccess:i(()=>{n($e()),x(!1)},"onSuccess")}),"onClick"),disabled:A,children:c.isPending?"Adding...":"Add trigger"})]})]}):null,k?(0,e.jsxs)("div",{className:"space-y-3 rounded-lg border border-border bg-muted/20 p-4 text-sm",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"font-medium",children:k.title}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"Save this now. Paperclip will not show the secret value again."})]}),(0,e.jsx)("div",{className:"space-y-3",children:k.entries.map((g,b)=>(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(V,{"aria-label":"New webhook URL",value:g.webhookUrl,readOnly:!0,className:"flex-1"}),(0,e.jsx)(E,{variant:"outline",size:"sm",onClick:i(()=>I("Webhook URL",g.webhookUrl),"onClick"),children:"URL"})]}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(V,{"aria-label":"New webhook secret",value:g.webhookSecret,readOnly:!0,className:"flex-1"}),(0,e.jsx)(E,{variant:"outline",size:"sm",onClick:i(()=>I("Webhook secret",g.webhookSecret),"onClick"),children:"Secret"})]})]},`${g.webhookUrl}-${b}`))}),(0,e.jsx)(E,{variant:"outline",size:"sm",onClick:i(()=>M(null),"onClick"),children:"Done"})]}):null,s.triggers.length===0?(0,e.jsx)(te,{icon:ye,message:"No triggers yet.",action:"Add a trigger",onAction:i(()=>x(!0),"onAction")}):(0,e.jsx)("div",{className:"space-y-3",children:s.triggers.map(g=>(0,e.jsx)(xs,{trigger:g,onSave:i((b,j)=>r.mutate({id:b,patch:j}),"onSave"),onRotate:i(b=>l.mutate(b),"onRotate"),onDelete:i(b=>m.mutate(b),"onDelete")},g.id))})]})}i(Is,"TriggersSection");function Cs(){const{editDraft:s,setEditDraft:a,navigateToSection:n}=Q(),c=s.variables.length>0;return(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"flex items-center gap-3 rounded-md border border-border bg-muted/20 px-4 py-3 text-xs",children:[(0,e.jsxs)("span",{className:"flex-1 text-muted-foreground",children:["Variables are auto-detected from ",(0,e.jsx)("code",{className:"font-mono",children:"{{placeholders}}"})," in the title & instructions. The variable name is read-only — rename by editing the placeholder."]}),(0,e.jsxs)(E,{variant:"secondary",size:"sm",onClick:i(()=>n("overview"),"onClick"),children:[(0,e.jsx)(Qt,{className:"mr-1.5 h-3.5 w-3.5"}),"Edit instructions"]})]}),c?(0,e.jsx)(Ue,{title:s.title,description:s.description,value:s.variables,onChange:i(r=>a(m=>({...m,variables:r})),"onChange")}):(0,e.jsx)(te,{icon:is,message:"No variables yet. Add a {{placeholder}} in the title or instructions to create one.",action:"Edit instructions",onAction:i(()=>n("overview"),"onAction")})]})}i(Cs,"VariablesSection");function As(){const{editDraft:s,setEditDraft:a,availableSecrets:n,createSecret:c}=Q(),r=(0,u.useMemo)(()=>[...n].filter(m=>m.status==="active").sort((m,l)=>{const k=(l.referenceCount??0)-(m.referenceCount??0);return k!==0?k:new Date(l.updatedAt).getTime()-new Date(m.updatedAt).getTime()}).slice(0,8),[n]);return(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"rounded-md border border-border bg-muted/20 px-4 py-3 text-xs text-muted-foreground",children:["Routine secrets apply to every task this routine creates. They override matching keys in project and agent env. ",(0,e.jsx)("span",{className:"font-mono",children:"PAPERCLIP_*"})," names are reserved."]}),(0,e.jsx)(ds,{value:s.env??{},secrets:n,recentlyUsedSecrets:r,onCreateSecret:i(async(m,l)=>c.mutateAsync({name:m,value:l}),"onCreateSecret"),onChange:i(m=>a(l=>({...l,env:m??null})),"onChange")})]})}i(As,"SecretsSection");function Ps(){const{editDraft:s,setEditDraft:a,routine:n}=Q(),c=n.triggers.some(m=>m.kind==="schedule"),r=s.activityGatePolicy==="require_external_activity";return(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Concurrency"}),(0,e.jsx)(X,{ariaLabel:"Concurrency policy",value:s.concurrencyPolicy,onValueChange:i(m=>a(l=>({...l,concurrencyPolicy:m})),"onValueChange"),options:ys})]}),(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Catch-up"}),(0,e.jsx)(X,{ariaLabel:"Catch-up policy",value:s.catchUpPolicy,onValueChange:i(m=>a(l=>({...l,catchUpPolicy:m})),"onValueChange"),options:vs})]}),(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Advanced run policy"}),(0,e.jsx)(X,{ariaLabel:"Advanced run policy",value:s.activityGatePolicy,onValueChange:i(m=>a(l=>({...l,activityGatePolicy:m})),"onValueChange"),options:fs,disabled:!c}),c?r?(0,e.jsxs)("div",{className:"space-y-2 rounded-lg border border-border p-3",children:[(0,e.jsx)(O,{className:"text-xs font-medium",children:"Activity scope"}),(0,e.jsx)(X,{ariaLabel:"Activity gate scope",value:s.activityGateScope,onValueChange:i(m=>a(l=>({...l,activityGateScope:m})),"onValueChange"),options:bs})]}):null:(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"Add a schedule trigger to gate runs on activity. Webhook, manual, and API fires always run."})]}),(0,e.jsx)(Ts,{triggers:n.triggers,concurrencyPolicy:s.concurrencyPolicy})]})}i(Ps,"DeliverySection");var Rs={queued:"text-emerald-600 dark:text-emerald-400",coalesced:"text-amber-600 dark:text-amber-400",skipped:"text-muted-foreground"};function Ts({triggers:s,concurrencyPolicy:a}){const n=(0,u.useMemo)(()=>{const c=s.filter(r=>r.kind==="schedule"&&r.enabled&&r.cronExpression).map(r=>({trigger:r,fires:zt(r.cronExpression,5,{timeZone:r.timezone??"UTC"})})).filter(r=>r.fires.length>0).sort((r,m)=>r.fires[0].getTime()-m.fires[0].getTime())[0];return c?{timeZone:c.trigger.timezone??"UTC",entries:Jt(c.fires,a)}:null},[s,a]);return(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Next 5 fires"}),n?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"space-y-1.5 rounded-lg border border-border p-3 font-mono text-xs",children:n.entries.map((c,r)=>(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("span",{className:"text-muted-foreground/40",children:"·"}),(0,e.jsx)("span",{className:"tabular-nums",children:Es(c.at,n.timeZone)}),(0,e.jsx)(ve,{className:"h-3 w-3 shrink-0 text-muted-foreground/50"}),(0,e.jsx)("span",{className:ut("font-medium",Rs[c.disposition]),children:c.label}),c.note?(0,e.jsxs)("span",{className:"truncate text-muted-foreground/60",children:["(",c.note,")"]}):null]},r))}),(0,e.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground/60",children:["Preview assumes the previous run is still in flight when the next fires. Times shown in"," ",n.timeZone,"."]})]}):(0,e.jsx)("p",{className:"rounded-lg border border-dashed border-border p-3 text-xs text-muted-foreground",children:"No enabled schedule trigger to preview. Add a schedule in Triggers to see how this policy treats upcoming fires."})]})}i(Ts,"NextFiresPreview");function Es(s,a){try{return new Intl.DateTimeFormat(void 0,{timeZone:a,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(s).replace(",","")}catch{return s.toISOString()}}i(Es,"formatFireTime");var ge="paperclip.routineLastSection";function Os(s){return s.filter(a=>!a.archivedAt).map(a=>({id:a.id,label:a.name,searchText:a.description??""}))}i(Os,"buildRoutineProjectOptions");var Ds={overview:"Overview",triggers:"Triggers",variables:"Variables",secrets:"Secrets",delivery:"Delivery",runs:"Runs",activity:"Activity",history:"History"};function ee(s){return s!=null&&ss.includes(s)}i(ee,"isRoutineSection");function _s(s){try{const a=localStorage.getItem(ge);if(!a)return null;const n=JSON.parse(a)[s];return ee(n)?n:null}catch{return null}}i(_s,"readLastSection");function le(s,a){try{const n=localStorage.getItem(ge),c=n?JSON.parse(n):{};c[s]=a,localStorage.setItem(ge,JSON.stringify(c))}catch{}}i(le,"writeLastSection");var Fe={triggers:"triggers",runs:"runs",activity:"activity",secrets:"secrets",history:"history"};function Ke(s){s&&(s.style.height="auto",s.style.height=`${s.scrollHeight}px`)}i(Ke,"autoResizeTextarea");function Ms(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}i(Ms,"getLocalTimezone");function qs(s){return{...s,description:s.description.trim()||null,projectId:s.projectId||null,assigneeAgentId:s.assigneeAgentId||null,env:s.env&&Object.keys(s.env).length>0?s.env:null}}i(qs,"buildRoutineMutationPayload");function di(){const{routineId:s,section:a}=gt(),{selectedCompanyId:n}=mt(),{setBreadcrumbs:c}=Et(),r=dt(),m=ht(),{pushToast:l}=as(),k=(0,u.useRef)(null),I=(0,u.useRef)(null),M=(0,u.useRef)(null),C=(0,u.useRef)(null),x=(0,u.useRef)(null),[S,D]=(0,u.useState)(null),[q,A]=(0,u.useState)(!1),[g,b]=(0,u.useState)(!1),[j,se]=(0,u.useState)($e),[f,P]=(0,u.useState)({title:"",description:"",projectId:"",assigneeAgentId:"",priority:"medium",concurrencyPolicy:"coalesce_if_active",catchUpPolicy:"skip_missed",activityGatePolicy:"always",activityGateScope:"company",variables:[],env:null}),w=ee(a)?a:"overview",_=(0,u.useCallback)((t,h)=>{s&&(le(s,t),m(`/routines/${s}/${t}`,{replace:h?.replace??!0}))},[m,s]),{data:o,isLoading:z,error:W}=L({queryKey:p.routines.detail(s),queryFn:i(()=>T.get(s),"queryFn"),enabled:!!s}),R=o?.activeIssue?.id,{data:B}=L({queryKey:p.issues.liveRuns(R),queryFn:i(()=>Ft.liveRunsForIssue(R),"queryFn"),enabled:!!R,refetchInterval:3e3}),d=(B??[]).length>0,{data:y}=L({queryKey:p.routines.runs(s),queryFn:i(()=>T.listRuns(s),"queryFn"),enabled:!!s,refetchInterval:d?3e3:!1}),G=(0,u.useMemo)(()=>({triggerIds:o?.triggers.map(t=>t.id)??[],runIds:y?.map(t=>t.id)??[]}),[o?.triggers,y]),{data:Ve}=L({queryKey:[...p.routines.activity(n,s),G.triggerIds.join(","),G.runIds.join(",")],queryFn:i(()=>T.activity(n,s,G),"queryFn"),enabled:!!n&&!!s&&!!o}),{data:F}=L({queryKey:p.agents.list(n),queryFn:i(()=>Rt.list(n),"queryFn"),enabled:!!n}),{data:K}=L({queryKey:p.projects.list(n,{includeArchived:!0}),queryFn:i(()=>Tt.list(n,{includeArchived:!0}),"queryFn"),enabled:!!n}),{data:fe}=L({queryKey:p.access.companyUserDirectory(n),queryFn:i(()=>Lt.listUserDirectory(n),"queryFn"),enabled:!!n}),{data:Ge=[]}=L({queryKey:n?p.secrets.list(n):["secrets","none"],queryFn:i(()=>Me.list(n),"queryFn"),enabled:!!n}),Qe=U({mutationFn:i(t=>{if(!n)throw new Error("Select a company to create secrets");return Me.create(n,t)},"mutationFn"),onSuccess:i(()=>{n&&r.invalidateQueries({queryKey:p.secrets.list(n)})},"onSuccess")}),v=(0,u.useMemo)(()=>o?{title:o.title,description:o.description??"",projectId:o.projectId??"",assigneeAgentId:o.assigneeAgentId??"",priority:o.priority,concurrencyPolicy:o.concurrencyPolicy,catchUpPolicy:o.catchUpPolicy,activityGatePolicy:o.activityGatePolicy,activityGateScope:o.activityGateScope,variables:o.variables,env:o.env??null}:null,[o]),H=(0,u.useMemo)(()=>{if(!v)return[];const t=[];return f.title!==v.title&&t.push({key:"title",label:"the title"}),f.description!==v.description&&t.push({key:"description",label:"the description"}),f.projectId!==v.projectId&&t.push({key:"projectId",label:"the project"}),f.assigneeAgentId!==v.assigneeAgentId&&t.push({key:"assigneeAgentId",label:"the default agent"}),f.priority!==v.priority&&t.push({key:"priority",label:"the priority"}),f.concurrencyPolicy!==v.concurrencyPolicy&&t.push({key:"concurrencyPolicy",label:"the concurrency policy"}),f.catchUpPolicy!==v.catchUpPolicy&&t.push({key:"catchUpPolicy",label:"the catch-up policy"}),f.activityGatePolicy!==v.activityGatePolicy&&t.push({key:"activityGatePolicy",label:"the advanced run policy"}),f.activityGateScope!==v.activityGateScope&&t.push({key:"activityGateScope",label:"the activity gate scope"}),JSON.stringify(f.variables)!==JSON.stringify(v.variables)&&t.push({key:"variables",label:"the variables"}),JSON.stringify(f.env??null)!==JSON.stringify(v.env??null)&&t.push({key:"env",label:"the secrets"}),t},[f,v]),ie=H.length>0,J=(0,u.useCallback)(t=>{const h=qe[t];return h?H.filter(N=>h.includes(N.key)):[]},[H]),ne=(0,u.useCallback)(t=>J(t).length>0,[J]),be=(0,u.useCallback)(t=>{if(!v)return;const h=qe[t];h&&P(N=>{const Re={...N};for(const Te of h)Re[Te]=v[Te];return Re})},[v]);(0,u.useEffect)(()=>{o&&(c([{label:"Routines",href:"/routines"},{label:o.title}]),v&&(k.current!==o.id||!ie)&&(P(v),k.current=o.id))},[o,v,ie,c]),(0,u.useEffect)(()=>{Ke(I.current)},[f.title,o?.id]),(0,u.useEffect)(()=>{s&&ee(a)&&le(s,a)},[s,a]);const ze=(0,u.useCallback)(async(t,h)=>{try{await qt(h),l({title:`${t} copied`,tone:"success"})}catch(N){l({title:`Failed to copy ${t.toLowerCase()}`,body:N instanceof Error?N.message:"Clipboard access was denied.",tone:"error"})}},[l]),Y=U({mutationFn:i(()=>{const t=qs(f),h=o?.latestRevisionId??null;return T.update(s,{...t,...h?{baseRevisionId:h}:{}})},"mutationFn"),onSuccess:i(async()=>{A(!1),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)}),r.invalidateQueries({queryKey:p.routines.revisions(s)})])},"onSuccess"),onError:i(t=>{if(t instanceof pt&&t.status===409){A(!0),l({title:"Routine changed",body:"Someone else updated this routine. Reload to see the latest revision.",tone:"warn"});return}l({title:"Failed to save routine",body:t instanceof Error?t.message:"Paperclip could not save the routine.",tone:"error"})},"onError")}),Z=U({mutationFn:i(t=>T.run(s,{...t?.variables&&Object.keys(t.variables).length>0?{variables:t.variables}:{},...t?.assigneeAgentId!==void 0?{assigneeAgentId:t.assigneeAgentId}:{},...t?.projectId!==void 0?{projectId:t.projectId}:{},...t?.executionWorkspaceId!==void 0?{executionWorkspaceId:t.executionWorkspaceId}:{},...t?.executionWorkspacePreference!==void 0?{executionWorkspacePreference:t.executionWorkspacePreference}:{},...t?.executionWorkspaceSettings!==void 0?{executionWorkspaceSettings:t.executionWorkspaceSettings}:{}}),"mutationFn"),onSuccess:i(async()=>{l({title:"Routine run started",tone:"success"}),b(!1),_("runs"),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.runs(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Routine run failed",body:t instanceof Error?t.message:"Paperclip could not start the routine run.",tone:"error"})},"onError")}),je=U({mutationFn:i(t=>T.update(s,{status:t}),"mutationFn"),onSuccess:i(async(t,h)=>{l({title:"Routine saved",body:h==="paused"?"Automation paused.":"Automation enabled.",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to update routine",body:t instanceof Error?t.message:"Paperclip could not update the routine.",tone:"error"})},"onError")}),Be=U({mutationFn:i(async()=>{const t=(o?.triggers??[]).filter(N=>N.kind===j.kind).length,h=t>0?`${j.kind}-${t+1}`:j.kind;return T.createTrigger(s,{kind:j.kind,label:h,...j.kind==="schedule"?{cronExpression:j.cronExpression.trim(),timezone:Ms()}:{},...j.kind==="webhook"?{signingMode:j.signingMode,replayWindowSec:Number(j.replayWindowSec||"300")}:{}})},"mutationFn"),onSuccess:i(async t=>{t.secretMaterial?D({title:"Webhook trigger created",entries:[{webhookUrl:t.secretMaterial.webhookUrl,webhookSecret:t.secretMaterial.webhookSecret}]}):l({title:"Trigger added",body:"The routine schedule was saved.",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to add trigger",body:t instanceof Error?t.message:"Paperclip could not create the trigger.",tone:"error"})},"onError")}),He=U({mutationFn:i(({id:t,patch:h})=>T.updateTrigger(t,h),"mutationFn"),onSuccess:i(async()=>{l({title:"Trigger saved",body:"The routine cadence update was saved.",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to update trigger",body:t instanceof Error?t.message:"Paperclip could not update the trigger.",tone:"error"})},"onError")}),Je=U({mutationFn:i(t=>T.deleteTrigger(t),"mutationFn"),onSuccess:i(async()=>{l({title:"Trigger deleted",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to delete trigger",body:t instanceof Error?t.message:"Paperclip could not delete the trigger.",tone:"error"})},"onError")}),Ye=U({mutationFn:i(t=>T.rotateTriggerSecret(t),"mutationFn"),onSuccess:i(async t=>{D({title:"Webhook secret rotated",entries:[{webhookUrl:t.secretMaterial.webhookUrl,webhookSecret:t.secretMaterial.webhookSecret}]}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to rotate webhook secret",body:t instanceof Error?t.message:"Paperclip could not rotate the webhook secret.",tone:"error"})},"onError")}),we=(0,u.useMemo)(()=>new Map((F??[]).map(t=>[t.id,t])),[F]),Ne=(0,u.useMemo)(()=>new Map((K??[]).map(t=>[t.id,t])),[K]),ae=(0,u.useMemo)(()=>jt(),[o?.id]),Ze=(0,u.useMemo)(()=>wt(),[o?.id]),Xe=(0,u.useMemo)(()=>xt((F??[]).filter(t=>t.status!=="terminated"),ae).map(t=>({id:t.id,label:t.name,searchText:`${t.name} ${t.role} ${t.title??""}`})),[F,ae]),et=(0,u.useMemo)(()=>Os(K??[]),[K]),tt=(0,u.useMemo)(()=>Kt({agents:F,projects:(K??[]).filter(t=>!t.archivedAt),members:fe?.users}),[F,fe?.users,K]),st=(0,u.useCallback)(t=>{P(h=>{const N=typeof t=="function"?t(h):t;return N.assigneeAgentId&&N.assigneeAgentId!==h.assigneeAgentId&&bt(N.assigneeAgentId),N.projectId&&N.projectId!==h.projectId&&yt(N.projectId),N})},[]),it=f.assigneeAgentId?we.get(f.assigneeAgentId)??null:null,nt=f.projectId?Ne.get(f.projectId)??null:null,ke=(0,u.useCallback)(()=>{A(!1),v&&P(v),r.invalidateQueries({queryKey:p.routines.detail(s)})},[r,v,s]),at=(0,u.useCallback)(t=>{t.secretMaterials.length>0&&(_("triggers"),D({title:t.secretMaterials.length===1?"Webhook trigger restored":`${t.secretMaterials.length} webhook triggers restored`,entries:t.secretMaterials.map(h=>({webhookUrl:h.webhookUrl,webhookSecret:h.webhookSecret}))}))},[_]),rt=(0,u.useCallback)(t=>{A(!1),r.setQueryData(p.routines.detail(s),h=>h&&{...h,...t.routine,latestRevisionId:t.revision.id,latestRevisionNumber:t.revision.revisionNumber}),P({title:t.routine.title,description:t.routine.description??"",projectId:t.routine.projectId??"",assigneeAgentId:t.routine.assigneeAgentId??"",priority:t.routine.priority,concurrencyPolicy:t.routine.concurrencyPolicy,catchUpPolicy:t.routine.catchUpPolicy,activityGatePolicy:t.routine.activityGatePolicy,activityGateScope:t.routine.activityGateScope,variables:t.routine.variables,env:t.routine.env??null}),k.current=t.routine.id},[r,s]);if(!n)return(0,e.jsx)(te,{icon:vt,message:"Select a company to view routines."});const re=new URLSearchParams(window.location.search).get("tab");if(s&&re&&Fe[re])return(0,e.jsx)(oe,{to:`/routines/${s}/${Fe[re]}`,replace:!0});if(s&&!a){const t=_s(s)??"overview";return(0,e.jsx)(oe,{to:`/routines/${s}/${t}`,replace:!0})}if(s&&a&&!ee(a))return(0,e.jsx)(oe,{to:`/routines/${s}/overview`,replace:!0});if(z)return(0,e.jsx)($t,{variant:"issues-list"});if(W||!o||!v)return(0,e.jsx)(te,{icon:Ot,message:W instanceof Error?W.message:"We couldn't load this routine."});const $=o.status==="active",Se=je.isPending||o.status==="archived",Ie=o.status==="archived"?"Archived":o.assigneeAgentId?$?"Active":"Paused":"Draft",Ce=o.status==="archived"?"text-muted-foreground":$?"text-emerald-400":"text-muted-foreground",Ae={routine:o,routineId:s,companyId:o.companyId,editDraft:f,setEditDraft:st,routineDefaults:v,dirtyFields:H,isEditDirty:ie,sectionDirtyFields:J,isSectionDirty:ne,discardSection:be,saveRoutine:Y,saveConflict:q,reloadLatest:ke,automationEnabled:$,automationLabel:Ie,automationLabelClassName:Ce,automationToggleDisabled:Se,onToggleAutomation:i(()=>{if(!$&&!o.assigneeAgentId){l({title:"Default agent required",body:"Set a default agent before enabling routine automation.",tone:"warn"});return}je.mutate($?"paused":"active")},"onToggleAutomation"),onOpenRunDialog:i(()=>b(!0),"onOpenRunDialog"),runRoutinePending:Z.isPending,newTrigger:j,setNewTrigger:se,createTrigger:Be,updateTrigger:He,deleteTrigger:Je,rotateTrigger:Ye,secretMessage:S,setSecretMessage:D,copySecretValue:ze,availableSecrets:Ge,createSecret:Qe,agents:F??[],projects:K??[],agentById:we,projectById:Ne,assigneeOptions:Xe,projectOptions:et,recentAssigneeIds:ae,recentProjectIds:Ze,mentionOptions:tt,currentAssignee:it,currentProject:nt,routineRuns:y,activity:Ve,hasLiveRun:d,activeIssueId:R,titleInputRef:I,descriptionEditorRef:M,assigneeSelectorRef:C,projectSelectorRef:x,onHistoryRestoreSecretMaterials:at,onHistoryRestored:rt,navigateToSection:_},Pe=Gt.includes(w);return(0,e.jsxs)(Bt.Provider,{value:Ae,children:[(0,e.jsx)("a",{href:"#routine-section",className:"sr-only focus:not-sr-only focus:absolute focus:left-2 focus:top-2 focus:z-20 focus:rounded focus:bg-background focus:px-3 focus:py-1.5 focus:text-sm",children:"Skip to section"}),(0,e.jsxs)("div",{className:"-m-4 flex h-full min-h-0 flex-col overflow-hidden md:-m-6",children:[(0,e.jsxs)("header",{className:"flex h-14 shrink-0 items-center gap-3 border-b border-border bg-background px-6",children:[(0,e.jsxs)("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[(0,e.jsx)("textarea",{ref:I,"data-autosize-title":!0,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",rows:1,value:f.title,onChange:i(t=>{P(h=>({...h,title:t.target.value})),Ke(t.target)},"onChange"),onKeyDown:i(t=>{t.key==="Enter"&&!t.metaKey&&!t.ctrlKey&&!t.nativeEvent.isComposing&&(t.preventDefault(),w==="overview"?M.current?.focus():_("overview"))},"onKeyDown")}),o.managedByPlugin?(0,e.jsxs)(xe,{variant:"outline",className:"hidden shrink-0 gap-1.5 text-xs text-muted-foreground sm:inline-flex",children:[(0,e.jsx)(kt,{className:"h-3 w-3"}),o.managedByPlugin.pluginDisplayName,(0,e.jsx)("span",{className:"font-mono text-(length:--text-nano)",children:o.managedByPlugin.resourceKey})]}):null]}),(0,e.jsxs)("div",{className:"ml-auto flex shrink-0 items-center gap-3",children:[(0,e.jsx)(ts,{onClick:i(()=>b(!0),"onClick"),disabled:Z.isPending}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(Pt,{size:"default",checked:$,onCheckedChange:Ae.onToggleAutomation,disabled:Se,"aria-label":$?"Pause automatic triggers":"Enable automatic triggers"}),(0,e.jsx)("span",{className:`text-sm font-medium ${Ce}`,children:Ie})]})]})]}),(0,e.jsx)(es,{activeSection:w,onNavigate:_,isSectionDirty:ne}),(0,e.jsxs)("div",{className:"flex min-h-0 flex-1",children:[(0,e.jsx)(us,{activeSection:w,hrefFor:i(t=>`/routines/${s}/${t}`,"hrefFor"),isSectionDirty:ne,hasLiveRun:d,onNavigate:i(t=>le(s,t),"onNavigate")}),(0,e.jsx)("main",{id:"routine-section",role:"main",className:"min-h-0 min-w-0 flex-1 overflow-y-auto px-4 pb-6 pt-10 md:px-8",children:(0,e.jsxs)("section",{"aria-labelledby":"routine-section-title",className:Pe?"mx-auto w-full max-w-3xl":"w-full",children:[(0,e.jsx)("h2",{id:"routine-section-title",className:"mb-4 text-lg font-semibold",children:Ds[w]}),w==="overview"&&(0,e.jsx)(Ss,{}),w==="triggers"&&(0,e.jsx)(Is,{}),w==="variables"&&(0,e.jsx)(Cs,{}),w==="secrets"&&(0,e.jsx)(As,{}),w==="delivery"&&(0,e.jsx)(Ps,{}),w==="runs"&&(0,e.jsx)(rs,{}),w==="activity"&&(0,e.jsx)(os,{}),w==="history"&&(0,e.jsx)(Vt,{}),Pe?(0,e.jsx)(Yt,{dirtyFields:J(w),isSaving:Y.isPending,saveConflict:q,onSave:i(()=>{!Y.isPending&&f.title.trim()&&Y.mutate()},"onSave"),onDiscard:i(()=>be(w),"onDiscard"),onReload:ke}):null]})})]})]}),(0,e.jsx)(ft,{open:g,onOpenChange:b,companyId:o.companyId,routineName:o.title,agents:F??[],projects:K??[],defaultProjectId:o.projectId,defaultAssigneeAgentId:o.assigneeAgentId,variables:o.variables??[],isPending:Z.isPending,onSubmit:i(t=>Z.mutate(t),"onSubmit")})]})}i(di,"RoutineDetail");export{di as RoutineDetail};
|
|
1
|
+
var ot=Object.defineProperty;var i=(s,a)=>ot(s,"name",{value:a,configurable:!0});import{i as Le}from"./rolldown-runtime-ZpX3ckPj.js";import{Fr as ct,Lr as lt,Pr as dt,S as ut,U as mt,Y as p,Yn as pt,nr as L,tr as U}from"./createLucideIcon-r3v6fbGz.js";import{Z as Ee,o as ht,r as oe,st as gt}from"./router-DyZkoSkG.js";import{Ct as xt,bt as yt,lr as vt,t as ft,vt as Oe,wt as bt,xt as jt,yt as wt}from"./RoutineRunVariablesDialog-IRX4TLng.js";import{Q as Nt}from"./mention-chips-DXumPrOR.js";import{s as kt,t as St}from"./zap-P-cXfK28.js";import{l as T,t as De}from"./MarkdownEditor-Pip4OXiJ.js";import{v as It}from"./sheet-DeCxNmfl.js";import{t as _e}from"./AgentAvatar-PT82VwmU.js";import{k as Ct}from"./checkbox-CmMbs2PZ.js";import{_ as At,s as Pt,t as O}from"./label-C2ddSDJj.js";import{t as Rt}from"./agents-BlSzFh-1.js";import{g as Tt}from"./StatusIcon-BuUYMqqU.js";import{r as Et,t as te}from"./EmptyState-DPcc0zYh.js";import{c as de,i as ue,n as me,s as pe,t as he}from"./select-mS22eY6T.js";import{r as Ot,t as Dt}from"./save-DUnPDT6R.js";import{k as _t,t as E}from"./button-CAPbz11u.js";import{n as Mt,t as qt}from"./clipboard-CYJ5Q78m.js";import{t as Ft}from"./heartbeats-CK_aXmx5.js";import{t as xe}from"./badge-Cf7ihb3q.js";import{t as V}from"./input-DpsS9it-.js";import{i as Kt,o as Lt}from"./company-members-BcZm1g8Q.js";import{r as Ut,t as Wt}from"./card-dmVcp3AX.js";import{t as $t}from"./PageSkeleton-DHjTwRT3.js";import{A as Vt,B as Gt,Cn as Qt,F as zt,G as Q,H as Bt,Ht,I as Jt,K as Ue,L as Yt,M as We,N as Zt,P as Xt,Qt as Me,R as es,Rn as ye,Tt as ts,U as qe,Un as ve,V as ss,Vn as is,Vt as ns,W as $e,Xt as X,fn as as,j as rs,k as os,pn as cs,q as ls,qt as ds,z as us}from"./index-BF7JM92C.js";var u=Le(lt(),1);function ms(s,a,n){const c={label:a.label.trim()||null};return s.kind==="schedule"&&(c.cronExpression=a.cronExpression.trim(),c.timezone=s.timezone??n),s.kind==="webhook"&&(c.signingMode=a.signingMode,c.replayWindowSec=Number(a.replayWindowSec||"300")),c}i(ms,"buildRoutineTriggerPatch");var e=Le(ct(),1),ps=["app_webhook","bearer","hmac_sha256","github_hmac","none"],hs=new Set(["app_webhook","bearer","github_hmac","fireflies_hmac","none"]);function gs(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}i(gs,"getLocalTimezone$1");function xs({trigger:s,onSave:a,onRotate:n,onDelete:c,disabled:r}){const[m,l]=(0,u.useState)({label:s.label??"",cronExpression:s.cronExpression??"",signingMode:s.signingMode??"bearer",replayWindowSec:String(s.replayWindowSec??300)});(0,u.useEffect)(()=>{l({label:s.label??"",cronExpression:s.cronExpression??"",signingMode:s.signingMode??"bearer",replayWindowSec:String(s.replayWindowSec??300)})},[s]);const k=s.kind==="schedule"?ye:s.kind==="webhook"?cs:St,I=s.kind==="schedule"?Xt(m.cronExpression):null,M=/fail|error/i.test(s.lastResult??""),C=s.lastResult?.startsWith("Created execution issue ")?"Task created":s.lastResult;return(0,e.jsxs)("form",{"aria-label":`Trigger: ${s.label??s.kind}`,className:"space-y-4 rounded-lg border border-border p-4",onSubmit:i(x=>x.preventDefault(),"onSubmit"),children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium",children:[(0,e.jsx)(k,{className:"h-3.5 w-3.5 shrink-0"}),(0,e.jsx)("span",{className:"truncate",children:s.label??s.kind})]}),I?(0,e.jsx)("p",{id:`cron-readable-${s.id}`,className:"text-xs text-muted-foreground",children:I}):null]}),(0,e.jsxs)("div",{className:"flex shrink-0 items-center gap-2",children:[s.lastResult?(0,e.jsx)(xe,{variant:M?"destructive":"secondary",children:C}):null,(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:s.kind==="schedule"&&s.nextRunAt?`Next: ${new Date(s.nextRunAt).toLocaleString()}`:s.kind==="webhook"?"Webhook":"API"})]})]}),s.kind==="webhook"&&s.webhookUrl&&(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{htmlFor:`webhook-url-${s.id}`,className:"text-xs",children:"Webhook URL"}),(0,e.jsx)(V,{id:`webhook-url-${s.id}`,value:s.webhookUrl,readOnly:!0,onFocus:i(x=>x.target.select(),"onFocus")}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"Send a POST request with Content-Type: application/json. Keep this URL private when signing is disabled."})]}),(0,e.jsxs)("div",{className:"grid gap-3 md:grid-cols-2",children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Label"}),(0,e.jsx)(V,{value:m.label,disabled:r,onChange:i(x=>l(S=>({...S,label:x.target.value})),"onChange")})]}),s.kind==="schedule"&&(0,e.jsxs)("div",{className:"space-y-1.5 md:col-span-2",children:[(0,e.jsx)(O,{className:"text-xs",children:"Schedule"}),(0,e.jsx)(We,{value:m.cronExpression,onChange:i(x=>l(S=>({...S,cronExpression:x})),"onChange")})]}),s.kind==="webhook"&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Signing mode"}),(0,e.jsxs)(he,{value:m.signingMode,onValueChange:i(x=>l(S=>({...S,signingMode:x})),"onValueChange"),disabled:r,children:[(0,e.jsx)(pe,{children:(0,e.jsx)(de,{})}),(0,e.jsx)(me,{children:ps.map(x=>(0,e.jsx)(ue,{value:x,children:x},x))})]})]}),!hs.has(m.signingMode)&&(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Replay window (seconds)"}),(0,e.jsx)(V,{value:m.replayWindowSec,disabled:r,onChange:i(x=>l(S=>({...S,replayWindowSec:x.target.value})),"onChange")})]})]})]}),!r&&(0,e.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[(0,e.jsxs)(E,{variant:"ghost",size:"sm",className:"mr-auto text-muted-foreground hover:text-destructive",onClick:i(()=>c(s.id),"onClick"),children:[(0,e.jsx)(Ct,{className:"mr-1.5 h-3.5 w-3.5"}),"Delete"]}),s.kind==="webhook"&&(0,e.jsxs)(E,{variant:"outline",size:"sm",onClick:i(()=>n(s.id),"onClick"),children:[(0,e.jsx)(It,{className:"mr-1.5 h-3.5 w-3.5"}),"Rotate secret"]}),(0,e.jsxs)(E,{variant:"outline",size:"sm",onClick:i(()=>a(s.id,ms(s,m,gs())),"onClick"),children:[(0,e.jsx)(Dt,{className:"mr-1.5 h-3.5 w-3.5"}),"Save trigger"]})]})]})}i(xs,"RoutineTriggerCard");var ys=[{value:"coalesce_if_active",title:"Coalesce if active",description:"Keep one follow-up run queued while an active run is still working."},{value:"always_enqueue",title:"Always enqueue",description:"Queue every trigger occurrence, even if several runs stack up."},{value:"skip_if_active",title:"Skip if active",description:"Drop overlapping trigger occurrences while the routine is already active."}],vs=[{value:"skip_missed",title:"Skip missed",description:"Ignore schedule windows that were missed while paused."},{value:"enqueue_missed_with_cap",title:"Enqueue missed with cap",description:"Catch up missed schedule windows after recovery; sub-hourly schedules are combined into one catch-up run, slower schedules replay each missed window up to a cap."}],fs=[{value:"always",title:"Run on every scheduled tick",description:"Fire on the schedule no matter what — the default behavior."},{value:"require_external_activity",title:"Skip when there's been no activity since the last run",description:"On a scheduled tick, only run if something happened since the last run that finished. Lets a watcher-style routine stay asleep while the system is settled instead of burning tokens."}],bs=[{value:"company",title:"Company-wide",description:"Any activity across the company counts as a reason to run."},{value:"project",title:"This project",description:"Only activity in the routine's project counts as a reason to run."}],js=["schedule","webhook"],ws=["app_webhook","bearer","hmac_sha256","github_hmac","none"],Ns={bearer:"Send Authorization: Bearer <secret> with each request.",hmac_sha256:"Send X-Paperclip-Timestamp and X-Paperclip-Signature: sha256=<hex>, signing timestamp + a dot + the exact JSON body.",github_hmac:"Accept GitHub-style X-Hub-Signature-256 header (HMAC over raw body, no timestamp).",app_webhook:"Accept a bearer token or an HMAC-SHA256 signature over the exact request body in X-Hub-Signature or X-Hub-Signature-256.",fireflies_hmac:"Signed webhook (legacy).",none:"No authentication — the webhook URL itself acts as a shared secret."},ks=new Set(["app_webhook","bearer","github_hmac","fireflies_hmac","none"]);function Ss({defaultDescriptionAnnotationsOpen:s=!1}={}){const{routine:a,editDraft:n,setEditDraft:c,assigneeOptions:r,projectOptions:m,recentAssigneeIds:l,recentProjectIds:k,agentById:I,projectById:M,currentAssignee:C,currentProject:x,mentionOptions:S,assigneeSelectorRef:D,projectSelectorRef:q,descriptionEditorRef:A,routineRuns:g,activity:b,saveRoutine:j,saveConflict:se,isSectionDirty:f,navigateToSection:P}=Q(),[w,_]=(0,u.useState)(s),o=a.triggers.length,z=(0,u.useMemo)(()=>{const d=a.triggers.filter(y=>y.kind==="schedule"&&y.nextRunAt).map(y=>new Date(y.nextRunAt)).sort((y,G)=>y.getTime()-G.getTime())[0];return d?d.toLocaleString():null},[a.triggers]),W=n.env?Object.keys(n.env).length:0,R=(g??[])[0]??null,B=(b??[]).slice(0,5);return(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsx)("div",{className:"overflow-x-auto overscroll-x-contain",children:(0,e.jsxs)("div",{className:"inline-flex min-w-full flex-wrap items-center gap-2 text-sm text-muted-foreground sm:min-w-max sm:flex-nowrap",children:[(0,e.jsx)("span",{children:"For"}),(0,e.jsx)(Oe,{ref:D,value:n.assigneeAgentId,options:r,recentOptionIds:l,placeholder:"Responsible",noneLabel:"No responsible",searchPlaceholder:"Search responsible...",emptyMessage:"No responsible found.",onChange:i(d=>c(y=>({...y,assigneeAgentId:d})),"onChange"),onConfirm:i(()=>{n.projectId?A.current?.focus():q.current?.focus()},"onConfirm"),renderTriggerValue:i(d=>d?C?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(_e,{agent:C,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,e.jsx)("span",{className:"truncate",children:d.label})]}):(0,e.jsx)("span",{className:"truncate",children:d.label}):(0,e.jsx)("span",{className:"text-muted-foreground",children:"Responsible"}),"renderTriggerValue"),renderOption:i(d=>{if(!d.id)return(0,e.jsx)("span",{className:"truncate",children:d.label});const y=I.get(d.id);return(0,e.jsxs)(e.Fragment,{children:[y?(0,e.jsx)(_e,{agent:y,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,(0,e.jsx)("span",{className:"truncate",children:d.label})]})},"renderOption")}),(0,e.jsx)("span",{children:"in"}),(0,e.jsx)(Oe,{ref:q,value:n.projectId,options:m,recentOptionIds:k,placeholder:"Project",noneLabel:"No project",searchPlaceholder:"Search projects...",emptyMessage:"No projects found.",onChange:i(d=>c(y=>({...y,projectId:d})),"onChange"),onConfirm:i(()=>A.current?.focus(),"onConfirm"),renderTriggerValue:i(d=>d&&x?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:x.color??"var(--project-none)"}}),(0,e.jsx)("span",{className:"truncate",children:d.label})]}):(0,e.jsx)("span",{className:"text-muted-foreground",children:"Project"}),"renderTriggerValue"),renderOption:i(d=>{if(!d.id)return(0,e.jsx)("span",{className:"truncate",children:d.label});const y=M.get(d.id);return(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:y?.color??"var(--project-none)"}}),(0,e.jsx)("span",{className:"truncate",children:d.label})]})},"renderOption")})]})}),a.assigneeAgentId?null:(0,e.jsx)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 p-4 text-sm text-amber-900 dark:text-amber-200",children:"Default agent required. This routine can stay as a draft and still run manually, but automation stays paused until you assign a default agent."}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("div",{className:"flex items-center justify-end",children:a.descriptionDocument?(0,e.jsx)(ns,{issueId:a.id,docKey:"description",target:{kind:"routine",routineId:a.id,documentKey:"description"},panelOpen:w,onToggle:i(()=>_(d=>!d),"onToggle")}):null}),a.descriptionDocument?(0,e.jsx)(Ht,{issueId:a.id,doc:a.descriptionDocument,target:{kind:"routine",routineId:a.id,documentKey:"description"},bodyMarkdown:n.description,draftDirty:f("overview")||j.isPending,draftConflicted:se,historicalPreview:!1,locationHash:typeof window>"u"?"":window.location.hash,panelOpen:w,onPanelOpenChange:_,children:(0,e.jsx)(De,{ref:A,value:n.description,onChange:i(d=>c(y=>({...y,description:d})),"onChange"),placeholder:"Add instructions...",bordered:!1,contentClassName:"min-h-(--sz-120px) text-sm leading-7",mentions:S,onSubmit:i(()=>{!j.isPending&&n.title.trim()&&j.mutate()},"onSubmit")})}):(0,e.jsx)(De,{ref:A,value:n.description,onChange:i(d=>c(y=>({...y,description:d})),"onChange"),placeholder:"Add instructions...",bordered:!1,contentClassName:"min-h-(--sz-120px) text-sm leading-7",mentions:S,onSubmit:i(()=>{!j.isPending&&n.title.trim()&&j.mutate()},"onSubmit")})]}),(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)(ls,{}),(0,e.jsx)(Ue,{title:n.title,description:n.description,value:n.variables,onChange:i(d=>c(y=>({...y,variables:d})),"onChange")})]}),(0,e.jsxs)("div",{className:"grid gap-3 sm:grid-cols-3",children:[(0,e.jsx)(ce,{icon:ye,label:"Triggers",value:o===0?"None":`${o} active`,hint:z?`Next fire ${z}`:"No schedule",to:i(()=>P("triggers"),"to"),ariaLabel:`${o} triggers. Open triggers.`}),(0,e.jsx)(ce,{icon:Mt,label:"Secrets",value:W===0?"None":`${W} bound`,hint:"Manage bound secrets",to:i(()=>P("secrets"),"to"),ariaLabel:`${W} secrets bound. Open secrets.`}),(0,e.jsx)(ce,{icon:At,label:"Last run",value:R?R.status.replaceAll("_"," "):"No runs",hint:R?Ee(R.triggeredAt):"Trigger a run",to:i(()=>P("runs"),"to"),ariaLabel:R?`Last run ${R.status}. Open runs.`:"No runs. Open runs."})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Recent activity"}),B.length===0?(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"No activity yet."}):(0,e.jsxs)("div",{className:"divide-y divide-border/60",children:[B.map(d=>(0,e.jsxs)("div",{className:"flex items-center gap-2 py-1.5 text-xs",children:[(0,e.jsx)(xe,{variant:"outline",className:"shrink-0 font-mono",children:d.action}),(0,e.jsx)("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:d.details&&Object.keys(d.details).length>0?Object.keys(d.details).slice(0,3).join(" · "):""}),(0,e.jsx)("span",{className:"shrink-0 text-muted-foreground/60",children:Ee(d.createdAt)})]},d.id)),(0,e.jsxs)("button",{type:"button",onClick:i(()=>P("activity"),"onClick"),className:"flex items-center gap-1 pt-2 text-xs text-muted-foreground hover:text-foreground",children:["View all activity ",(0,e.jsx)(ve,{className:"h-3 w-3"})]})]})]})]})}i(Ss,"OverviewSection");function ce({icon:s,label:a,value:n,hint:c,to:r,ariaLabel:m}){return(0,e.jsx)("button",{type:"button",onClick:r,"aria-label":m,className:"text-left",children:(0,e.jsx)(Wt,{className:"gap-2 p-4 transition-colors hover:border-border hover:bg-accent/30",children:(0,e.jsxs)(Ut,{className:"space-y-1 p-0",children:[(0,e.jsxs)("div",{className:"flex items-center gap-1.5 text-xs uppercase tracking-wide text-muted-foreground",children:[(0,e.jsx)(s,{className:"h-3.5 w-3.5"}),a,(0,e.jsx)(ve,{className:"ml-auto h-3.5 w-3.5 text-muted-foreground/60"})]}),(0,e.jsx)("p",{className:"text-lg font-semibold",children:n}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:c})]})})})}i(ce,"SummaryCard");function Is(){const{routine:s,newTrigger:a,setNewTrigger:n,createTrigger:c,updateTrigger:r,deleteTrigger:m,rotateTrigger:l,secretMessage:k,copySecretValue:I,setSecretMessage:M}=Q(),[C,x]=(0,u.useState)(!1),[S,D]=(0,u.useState)(!0),q=(0,u.useMemo)(()=>a.kind==="schedule"?Zt(a.cronExpression):null,[a.cronExpression,a.kind]),A=c.isPending||(q?!q.valid||!S:!1);return(0,u.useEffect)(()=>{a.kind!=="schedule"&&D(!0)},[a.kind]),(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsx)("p",{className:"text-sm font-medium text-muted-foreground",children:s.triggers.length===0?"No triggers yet":`${s.triggers.length} trigger${s.triggers.length===1?"":"s"}`}),(0,e.jsx)(E,{size:"sm",variant:C?"secondary":"default",onClick:i(()=>x(g=>!g),"onClick"),"aria-expanded":C,children:C?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(Nt,{className:"mr-1.5 h-3.5 w-3.5"}),"Cancel"]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(_t,{className:"mr-1.5 h-3.5 w-3.5"}),"New trigger"]})})]}),C?(0,e.jsxs)("div",{className:"space-y-3 rounded-lg border border-border p-4",children:[(0,e.jsx)("p",{className:"text-sm font-medium",children:"Add trigger"}),(0,e.jsxs)("div",{className:"grid gap-3 md:grid-cols-2",children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Kind"}),(0,e.jsxs)(he,{value:a.kind,onValueChange:i(g=>n(b=>({...b,kind:g})),"onValueChange"),children:[(0,e.jsx)(pe,{children:(0,e.jsx)(de,{})}),(0,e.jsx)(me,{children:js.map(g=>(0,e.jsx)(ue,{value:g,children:g},g))})]})]}),a.kind==="schedule"&&(0,e.jsxs)("div",{className:"space-y-1.5 md:col-span-2",children:[(0,e.jsx)(O,{className:"text-xs",children:"Schedule"}),(0,e.jsx)(We,{value:a.cronExpression,onChange:i(g=>n(b=>({...b,cronExpression:g})),"onChange"),onValidityChange:D})]}),a.kind==="webhook"&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Signing mode"}),(0,e.jsxs)(he,{value:a.signingMode,onValueChange:i(g=>n(b=>({...b,signingMode:g})),"onValueChange"),children:[(0,e.jsx)(pe,{children:(0,e.jsx)(de,{})}),(0,e.jsx)(me,{children:ws.map(g=>(0,e.jsx)(ue,{value:g,children:g},g))})]}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:Ns[a.signingMode]})]}),!ks.has(a.signingMode)&&(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Replay window (seconds)"}),(0,e.jsx)(V,{value:a.replayWindowSec,onChange:i(g=>n(b=>({...b,replayWindowSec:g.target.value})),"onChange")})]})]})]}),(0,e.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[(0,e.jsx)(E,{size:"sm",variant:"ghost",onClick:i(()=>x(!1),"onClick"),children:"Cancel"}),(0,e.jsx)(E,{size:"sm",onClick:i(()=>c.mutate(void 0,{onSuccess:i(()=>{n($e()),x(!1)},"onSuccess")}),"onClick"),disabled:A,children:c.isPending?"Adding...":"Add trigger"})]})]}):null,k?(0,e.jsxs)("div",{className:"space-y-3 rounded-lg border border-border bg-muted/20 p-4 text-sm",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"font-medium",children:k.title}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"Save this now. Paperclip will not show the secret value again."})]}),(0,e.jsx)("div",{className:"space-y-3",children:k.entries.map((g,b)=>(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(V,{"aria-label":"New webhook URL",value:g.webhookUrl,readOnly:!0,className:"flex-1"}),(0,e.jsx)(E,{variant:"outline",size:"sm",onClick:i(()=>I("Webhook URL",g.webhookUrl),"onClick"),children:"URL"})]}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(V,{"aria-label":"New webhook secret",value:g.webhookSecret,readOnly:!0,className:"flex-1"}),(0,e.jsx)(E,{variant:"outline",size:"sm",onClick:i(()=>I("Webhook secret",g.webhookSecret),"onClick"),children:"Secret"})]})]},`${g.webhookUrl}-${b}`))}),(0,e.jsx)(E,{variant:"outline",size:"sm",onClick:i(()=>M(null),"onClick"),children:"Done"})]}):null,s.triggers.length===0?(0,e.jsx)(te,{icon:ye,message:"No triggers yet.",action:"Add a trigger",onAction:i(()=>x(!0),"onAction")}):(0,e.jsx)("div",{className:"space-y-3",children:s.triggers.map(g=>(0,e.jsx)(xs,{trigger:g,onSave:i((b,j)=>r.mutate({id:b,patch:j}),"onSave"),onRotate:i(b=>l.mutate(b),"onRotate"),onDelete:i(b=>m.mutate(b),"onDelete")},g.id))})]})}i(Is,"TriggersSection");function Cs(){const{editDraft:s,setEditDraft:a,navigateToSection:n}=Q(),c=s.variables.length>0;return(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"flex items-center gap-3 rounded-md border border-border bg-muted/20 px-4 py-3 text-xs",children:[(0,e.jsxs)("span",{className:"flex-1 text-muted-foreground",children:["Variables are auto-detected from ",(0,e.jsx)("code",{className:"font-mono",children:"{{placeholders}}"})," in the title & instructions. The variable name is read-only — rename by editing the placeholder."]}),(0,e.jsxs)(E,{variant:"secondary",size:"sm",onClick:i(()=>n("overview"),"onClick"),children:[(0,e.jsx)(Qt,{className:"mr-1.5 h-3.5 w-3.5"}),"Edit instructions"]})]}),c?(0,e.jsx)(Ue,{title:s.title,description:s.description,value:s.variables,onChange:i(r=>a(m=>({...m,variables:r})),"onChange")}):(0,e.jsx)(te,{icon:is,message:"No variables yet. Add a {{placeholder}} in the title or instructions to create one.",action:"Edit instructions",onAction:i(()=>n("overview"),"onAction")})]})}i(Cs,"VariablesSection");function As(){const{editDraft:s,setEditDraft:a,availableSecrets:n,createSecret:c}=Q(),r=(0,u.useMemo)(()=>[...n].filter(m=>m.status==="active").sort((m,l)=>{const k=(l.referenceCount??0)-(m.referenceCount??0);return k!==0?k:new Date(l.updatedAt).getTime()-new Date(m.updatedAt).getTime()}).slice(0,8),[n]);return(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"rounded-md border border-border bg-muted/20 px-4 py-3 text-xs text-muted-foreground",children:["Routine secrets apply to every task this routine creates. They override matching keys in project and agent env. ",(0,e.jsx)("span",{className:"font-mono",children:"PAPERCLIP_*"})," names are reserved."]}),(0,e.jsx)(ds,{value:s.env??{},secrets:n,recentlyUsedSecrets:r,onCreateSecret:i(async(m,l)=>c.mutateAsync({name:m,value:l}),"onCreateSecret"),onChange:i(m=>a(l=>({...l,env:m??null})),"onChange")})]})}i(As,"SecretsSection");function Ps(){const{editDraft:s,setEditDraft:a,routine:n}=Q(),c=n.triggers.some(m=>m.kind==="schedule"),r=s.activityGatePolicy==="require_external_activity";return(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Concurrency"}),(0,e.jsx)(X,{ariaLabel:"Concurrency policy",value:s.concurrencyPolicy,onValueChange:i(m=>a(l=>({...l,concurrencyPolicy:m})),"onValueChange"),options:ys})]}),(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Catch-up"}),(0,e.jsx)(X,{ariaLabel:"Catch-up policy",value:s.catchUpPolicy,onValueChange:i(m=>a(l=>({...l,catchUpPolicy:m})),"onValueChange"),options:vs})]}),(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Advanced run policy"}),(0,e.jsx)(X,{ariaLabel:"Advanced run policy",value:s.activityGatePolicy,onValueChange:i(m=>a(l=>({...l,activityGatePolicy:m})),"onValueChange"),options:fs,disabled:!c}),c?r?(0,e.jsxs)("div",{className:"space-y-2 rounded-lg border border-border p-3",children:[(0,e.jsx)(O,{className:"text-xs font-medium",children:"Activity scope"}),(0,e.jsx)(X,{ariaLabel:"Activity gate scope",value:s.activityGateScope,onValueChange:i(m=>a(l=>({...l,activityGateScope:m})),"onValueChange"),options:bs})]}):null:(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"Add a schedule trigger to gate runs on activity. Webhook, manual, and API fires always run."})]}),(0,e.jsx)(Ts,{triggers:n.triggers,concurrencyPolicy:s.concurrencyPolicy})]})}i(Ps,"DeliverySection");var Rs={queued:"text-emerald-600 dark:text-emerald-400",coalesced:"text-amber-600 dark:text-amber-400",skipped:"text-muted-foreground"};function Ts({triggers:s,concurrencyPolicy:a}){const n=(0,u.useMemo)(()=>{const c=s.filter(r=>r.kind==="schedule"&&r.enabled&&r.cronExpression).map(r=>({trigger:r,fires:zt(r.cronExpression,5,{timeZone:r.timezone??"UTC"})})).filter(r=>r.fires.length>0).sort((r,m)=>r.fires[0].getTime()-m.fires[0].getTime())[0];return c?{timeZone:c.trigger.timezone??"UTC",entries:Jt(c.fires,a)}:null},[s,a]);return(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Next 5 fires"}),n?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"space-y-1.5 rounded-lg border border-border p-3 font-mono text-xs",children:n.entries.map((c,r)=>(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("span",{className:"text-muted-foreground/40",children:"·"}),(0,e.jsx)("span",{className:"tabular-nums",children:Es(c.at,n.timeZone)}),(0,e.jsx)(ve,{className:"h-3 w-3 shrink-0 text-muted-foreground/50"}),(0,e.jsx)("span",{className:ut("font-medium",Rs[c.disposition]),children:c.label}),c.note?(0,e.jsxs)("span",{className:"truncate text-muted-foreground/60",children:["(",c.note,")"]}):null]},r))}),(0,e.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground/60",children:["Preview assumes the previous run is still in flight when the next fires. Times shown in"," ",n.timeZone,"."]})]}):(0,e.jsx)("p",{className:"rounded-lg border border-dashed border-border p-3 text-xs text-muted-foreground",children:"No enabled schedule trigger to preview. Add a schedule in Triggers to see how this policy treats upcoming fires."})]})}i(Ts,"NextFiresPreview");function Es(s,a){try{return new Intl.DateTimeFormat(void 0,{timeZone:a,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(s).replace(",","")}catch{return s.toISOString()}}i(Es,"formatFireTime");var ge="paperclip.routineLastSection";function Os(s){return s.filter(a=>!a.archivedAt).map(a=>({id:a.id,label:a.name,searchText:a.description??""}))}i(Os,"buildRoutineProjectOptions");var Ds={overview:"Overview",triggers:"Triggers",variables:"Variables",secrets:"Secrets",delivery:"Delivery",runs:"Runs",activity:"Activity",history:"History"};function ee(s){return s!=null&&ss.includes(s)}i(ee,"isRoutineSection");function _s(s){try{const a=localStorage.getItem(ge);if(!a)return null;const n=JSON.parse(a)[s];return ee(n)?n:null}catch{return null}}i(_s,"readLastSection");function le(s,a){try{const n=localStorage.getItem(ge),c=n?JSON.parse(n):{};c[s]=a,localStorage.setItem(ge,JSON.stringify(c))}catch{}}i(le,"writeLastSection");var Fe={triggers:"triggers",runs:"runs",activity:"activity",secrets:"secrets",history:"history"};function Ke(s){s&&(s.style.height="auto",s.style.height=`${s.scrollHeight}px`)}i(Ke,"autoResizeTextarea");function Ms(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}i(Ms,"getLocalTimezone");function qs(s){return{...s,description:s.description.trim()||null,projectId:s.projectId||null,assigneeAgentId:s.assigneeAgentId||null,env:s.env&&Object.keys(s.env).length>0?s.env:null}}i(qs,"buildRoutineMutationPayload");function di(){const{routineId:s,section:a}=gt(),{selectedCompanyId:n}=mt(),{setBreadcrumbs:c}=Et(),r=dt(),m=ht(),{pushToast:l}=as(),k=(0,u.useRef)(null),I=(0,u.useRef)(null),M=(0,u.useRef)(null),C=(0,u.useRef)(null),x=(0,u.useRef)(null),[S,D]=(0,u.useState)(null),[q,A]=(0,u.useState)(!1),[g,b]=(0,u.useState)(!1),[j,se]=(0,u.useState)($e),[f,P]=(0,u.useState)({title:"",description:"",projectId:"",assigneeAgentId:"",priority:"medium",concurrencyPolicy:"coalesce_if_active",catchUpPolicy:"skip_missed",activityGatePolicy:"always",activityGateScope:"company",variables:[],env:null}),w=ee(a)?a:"overview",_=(0,u.useCallback)((t,h)=>{s&&(le(s,t),m(`/routines/${s}/${t}`,{replace:h?.replace??!0}))},[m,s]),{data:o,isLoading:z,error:W}=L({queryKey:p.routines.detail(s),queryFn:i(()=>T.get(s),"queryFn"),enabled:!!s}),R=o?.activeIssue?.id,{data:B}=L({queryKey:p.issues.liveRuns(R),queryFn:i(()=>Ft.liveRunsForIssue(R),"queryFn"),enabled:!!R,refetchInterval:3e3}),d=(B??[]).length>0,{data:y}=L({queryKey:p.routines.runs(s),queryFn:i(()=>T.listRuns(s),"queryFn"),enabled:!!s,refetchInterval:d?3e3:!1}),G=(0,u.useMemo)(()=>({triggerIds:o?.triggers.map(t=>t.id)??[],runIds:y?.map(t=>t.id)??[]}),[o?.triggers,y]),{data:Ve}=L({queryKey:[...p.routines.activity(n,s),G.triggerIds.join(","),G.runIds.join(",")],queryFn:i(()=>T.activity(n,s,G),"queryFn"),enabled:!!n&&!!s&&!!o}),{data:F}=L({queryKey:p.agents.list(n),queryFn:i(()=>Rt.list(n),"queryFn"),enabled:!!n}),{data:K}=L({queryKey:p.projects.list(n,{includeArchived:!0}),queryFn:i(()=>Tt.list(n,{includeArchived:!0}),"queryFn"),enabled:!!n}),{data:fe}=L({queryKey:p.access.companyUserDirectory(n),queryFn:i(()=>Lt.listUserDirectory(n),"queryFn"),enabled:!!n}),{data:Ge=[]}=L({queryKey:n?p.secrets.list(n):["secrets","none"],queryFn:i(()=>Me.list(n),"queryFn"),enabled:!!n}),Qe=U({mutationFn:i(t=>{if(!n)throw new Error("Select a company to create secrets");return Me.create(n,t)},"mutationFn"),onSuccess:i(()=>{n&&r.invalidateQueries({queryKey:p.secrets.list(n)})},"onSuccess")}),v=(0,u.useMemo)(()=>o?{title:o.title,description:o.description??"",projectId:o.projectId??"",assigneeAgentId:o.assigneeAgentId??"",priority:o.priority,concurrencyPolicy:o.concurrencyPolicy,catchUpPolicy:o.catchUpPolicy,activityGatePolicy:o.activityGatePolicy,activityGateScope:o.activityGateScope,variables:o.variables,env:o.env??null}:null,[o]),H=(0,u.useMemo)(()=>{if(!v)return[];const t=[];return f.title!==v.title&&t.push({key:"title",label:"the title"}),f.description!==v.description&&t.push({key:"description",label:"the description"}),f.projectId!==v.projectId&&t.push({key:"projectId",label:"the project"}),f.assigneeAgentId!==v.assigneeAgentId&&t.push({key:"assigneeAgentId",label:"the default agent"}),f.priority!==v.priority&&t.push({key:"priority",label:"the priority"}),f.concurrencyPolicy!==v.concurrencyPolicy&&t.push({key:"concurrencyPolicy",label:"the concurrency policy"}),f.catchUpPolicy!==v.catchUpPolicy&&t.push({key:"catchUpPolicy",label:"the catch-up policy"}),f.activityGatePolicy!==v.activityGatePolicy&&t.push({key:"activityGatePolicy",label:"the advanced run policy"}),f.activityGateScope!==v.activityGateScope&&t.push({key:"activityGateScope",label:"the activity gate scope"}),JSON.stringify(f.variables)!==JSON.stringify(v.variables)&&t.push({key:"variables",label:"the variables"}),JSON.stringify(f.env??null)!==JSON.stringify(v.env??null)&&t.push({key:"env",label:"the secrets"}),t},[f,v]),ie=H.length>0,J=(0,u.useCallback)(t=>{const h=qe[t];return h?H.filter(N=>h.includes(N.key)):[]},[H]),ne=(0,u.useCallback)(t=>J(t).length>0,[J]),be=(0,u.useCallback)(t=>{if(!v)return;const h=qe[t];h&&P(N=>{const Re={...N};for(const Te of h)Re[Te]=v[Te];return Re})},[v]);(0,u.useEffect)(()=>{o&&(c([{label:"Routines",href:"/routines"},{label:o.title}]),v&&(k.current!==o.id||!ie)&&(P(v),k.current=o.id))},[o,v,ie,c]),(0,u.useEffect)(()=>{Ke(I.current)},[f.title,o?.id]),(0,u.useEffect)(()=>{s&&ee(a)&&le(s,a)},[s,a]);const ze=(0,u.useCallback)(async(t,h)=>{try{await qt(h),l({title:`${t} copied`,tone:"success"})}catch(N){l({title:`Failed to copy ${t.toLowerCase()}`,body:N instanceof Error?N.message:"Clipboard access was denied.",tone:"error"})}},[l]),Y=U({mutationFn:i(()=>{const t=qs(f),h=o?.latestRevisionId??null;return T.update(s,{...t,...h?{baseRevisionId:h}:{}})},"mutationFn"),onSuccess:i(async()=>{A(!1),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)}),r.invalidateQueries({queryKey:p.routines.revisions(s)})])},"onSuccess"),onError:i(t=>{if(t instanceof pt&&t.status===409){A(!0),l({title:"Routine changed",body:"Someone else updated this routine. Reload to see the latest revision.",tone:"warn"});return}l({title:"Failed to save routine",body:t instanceof Error?t.message:"Paperclip could not save the routine.",tone:"error"})},"onError")}),Z=U({mutationFn:i(t=>T.run(s,{...t?.variables&&Object.keys(t.variables).length>0?{variables:t.variables}:{},...t?.assigneeAgentId!==void 0?{assigneeAgentId:t.assigneeAgentId}:{},...t?.projectId!==void 0?{projectId:t.projectId}:{},...t?.executionWorkspaceId!==void 0?{executionWorkspaceId:t.executionWorkspaceId}:{},...t?.executionWorkspacePreference!==void 0?{executionWorkspacePreference:t.executionWorkspacePreference}:{},...t?.executionWorkspaceSettings!==void 0?{executionWorkspaceSettings:t.executionWorkspaceSettings}:{}}),"mutationFn"),onSuccess:i(async()=>{l({title:"Routine run started",tone:"success"}),b(!1),_("runs"),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.runs(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Routine run failed",body:t instanceof Error?t.message:"Paperclip could not start the routine run.",tone:"error"})},"onError")}),je=U({mutationFn:i(t=>T.update(s,{status:t}),"mutationFn"),onSuccess:i(async(t,h)=>{l({title:"Routine saved",body:h==="paused"?"Automation paused.":"Automation enabled.",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to update routine",body:t instanceof Error?t.message:"Paperclip could not update the routine.",tone:"error"})},"onError")}),Be=U({mutationFn:i(async()=>{const t=(o?.triggers??[]).filter(N=>N.kind===j.kind).length,h=t>0?`${j.kind}-${t+1}`:j.kind;return T.createTrigger(s,{kind:j.kind,label:h,...j.kind==="schedule"?{cronExpression:j.cronExpression.trim(),timezone:Ms()}:{},...j.kind==="webhook"?{signingMode:j.signingMode,replayWindowSec:Number(j.replayWindowSec||"300")}:{}})},"mutationFn"),onSuccess:i(async t=>{t.secretMaterial?D({title:"Webhook trigger created",entries:[{webhookUrl:t.secretMaterial.webhookUrl,webhookSecret:t.secretMaterial.webhookSecret}]}):l({title:"Trigger added",body:"The routine schedule was saved.",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to add trigger",body:t instanceof Error?t.message:"Paperclip could not create the trigger.",tone:"error"})},"onError")}),He=U({mutationFn:i(({id:t,patch:h})=>T.updateTrigger(t,h),"mutationFn"),onSuccess:i(async()=>{l({title:"Trigger saved",body:"The routine cadence update was saved.",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to update trigger",body:t instanceof Error?t.message:"Paperclip could not update the trigger.",tone:"error"})},"onError")}),Je=U({mutationFn:i(t=>T.deleteTrigger(t),"mutationFn"),onSuccess:i(async()=>{l({title:"Trigger deleted",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to delete trigger",body:t instanceof Error?t.message:"Paperclip could not delete the trigger.",tone:"error"})},"onError")}),Ye=U({mutationFn:i(t=>T.rotateTriggerSecret(t),"mutationFn"),onSuccess:i(async t=>{D({title:"Webhook secret rotated",entries:[{webhookUrl:t.secretMaterial.webhookUrl,webhookSecret:t.secretMaterial.webhookSecret}]}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to rotate webhook secret",body:t instanceof Error?t.message:"Paperclip could not rotate the webhook secret.",tone:"error"})},"onError")}),we=(0,u.useMemo)(()=>new Map((F??[]).map(t=>[t.id,t])),[F]),Ne=(0,u.useMemo)(()=>new Map((K??[]).map(t=>[t.id,t])),[K]),ae=(0,u.useMemo)(()=>jt(),[o?.id]),Ze=(0,u.useMemo)(()=>wt(),[o?.id]),Xe=(0,u.useMemo)(()=>xt((F??[]).filter(t=>t.status!=="terminated"),ae).map(t=>({id:t.id,label:t.name,searchText:`${t.name} ${t.role} ${t.title??""}`})),[F,ae]),et=(0,u.useMemo)(()=>Os(K??[]),[K]),tt=(0,u.useMemo)(()=>Kt({agents:F,projects:(K??[]).filter(t=>!t.archivedAt),members:fe?.users}),[F,fe?.users,K]),st=(0,u.useCallback)(t=>{P(h=>{const N=typeof t=="function"?t(h):t;return N.assigneeAgentId&&N.assigneeAgentId!==h.assigneeAgentId&&bt(N.assigneeAgentId),N.projectId&&N.projectId!==h.projectId&&yt(N.projectId),N})},[]),it=f.assigneeAgentId?we.get(f.assigneeAgentId)??null:null,nt=f.projectId?Ne.get(f.projectId)??null:null,ke=(0,u.useCallback)(()=>{A(!1),v&&P(v),r.invalidateQueries({queryKey:p.routines.detail(s)})},[r,v,s]),at=(0,u.useCallback)(t=>{t.secretMaterials.length>0&&(_("triggers"),D({title:t.secretMaterials.length===1?"Webhook trigger restored":`${t.secretMaterials.length} webhook triggers restored`,entries:t.secretMaterials.map(h=>({webhookUrl:h.webhookUrl,webhookSecret:h.webhookSecret}))}))},[_]),rt=(0,u.useCallback)(t=>{A(!1),r.setQueryData(p.routines.detail(s),h=>h&&{...h,...t.routine,latestRevisionId:t.revision.id,latestRevisionNumber:t.revision.revisionNumber}),P({title:t.routine.title,description:t.routine.description??"",projectId:t.routine.projectId??"",assigneeAgentId:t.routine.assigneeAgentId??"",priority:t.routine.priority,concurrencyPolicy:t.routine.concurrencyPolicy,catchUpPolicy:t.routine.catchUpPolicy,activityGatePolicy:t.routine.activityGatePolicy,activityGateScope:t.routine.activityGateScope,variables:t.routine.variables,env:t.routine.env??null}),k.current=t.routine.id},[r,s]);if(!n)return(0,e.jsx)(te,{icon:vt,message:"Select a company to view routines."});const re=new URLSearchParams(window.location.search).get("tab");if(s&&re&&Fe[re])return(0,e.jsx)(oe,{to:`/routines/${s}/${Fe[re]}`,replace:!0});if(s&&!a){const t=_s(s)??"overview";return(0,e.jsx)(oe,{to:`/routines/${s}/${t}`,replace:!0})}if(s&&a&&!ee(a))return(0,e.jsx)(oe,{to:`/routines/${s}/overview`,replace:!0});if(z)return(0,e.jsx)($t,{variant:"issues-list"});if(W||!o||!v)return(0,e.jsx)(te,{icon:Ot,message:W instanceof Error?W.message:"We couldn't load this routine."});const $=o.status==="active",Se=je.isPending||o.status==="archived",Ie=o.status==="archived"?"Archived":o.assigneeAgentId?$?"Active":"Paused":"Draft",Ce=o.status==="archived"?"text-muted-foreground":$?"text-emerald-400":"text-muted-foreground",Ae={routine:o,routineId:s,companyId:o.companyId,editDraft:f,setEditDraft:st,routineDefaults:v,dirtyFields:H,isEditDirty:ie,sectionDirtyFields:J,isSectionDirty:ne,discardSection:be,saveRoutine:Y,saveConflict:q,reloadLatest:ke,automationEnabled:$,automationLabel:Ie,automationLabelClassName:Ce,automationToggleDisabled:Se,onToggleAutomation:i(()=>{if(!$&&!o.assigneeAgentId){l({title:"Default agent required",body:"Set a default agent before enabling routine automation.",tone:"warn"});return}je.mutate($?"paused":"active")},"onToggleAutomation"),onOpenRunDialog:i(()=>b(!0),"onOpenRunDialog"),runRoutinePending:Z.isPending,newTrigger:j,setNewTrigger:se,createTrigger:Be,updateTrigger:He,deleteTrigger:Je,rotateTrigger:Ye,secretMessage:S,setSecretMessage:D,copySecretValue:ze,availableSecrets:Ge,createSecret:Qe,agents:F??[],projects:K??[],agentById:we,projectById:Ne,assigneeOptions:Xe,projectOptions:et,recentAssigneeIds:ae,recentProjectIds:Ze,mentionOptions:tt,currentAssignee:it,currentProject:nt,routineRuns:y,activity:Ve,hasLiveRun:d,activeIssueId:R,titleInputRef:I,descriptionEditorRef:M,assigneeSelectorRef:C,projectSelectorRef:x,onHistoryRestoreSecretMaterials:at,onHistoryRestored:rt,navigateToSection:_},Pe=Gt.includes(w);return(0,e.jsxs)(Bt.Provider,{value:Ae,children:[(0,e.jsx)("a",{href:"#routine-section",className:"sr-only focus:not-sr-only focus:absolute focus:left-2 focus:top-2 focus:z-20 focus:rounded focus:bg-background focus:px-3 focus:py-1.5 focus:text-sm",children:"Skip to section"}),(0,e.jsxs)("div",{className:"-m-4 flex h-full min-h-0 flex-col overflow-hidden md:-m-6",children:[(0,e.jsxs)("header",{className:"flex h-14 shrink-0 items-center gap-3 border-b border-border bg-background px-6",children:[(0,e.jsxs)("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[(0,e.jsx)("textarea",{ref:I,"data-autosize-title":!0,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",rows:1,value:f.title,onChange:i(t=>{P(h=>({...h,title:t.target.value})),Ke(t.target)},"onChange"),onKeyDown:i(t=>{t.key==="Enter"&&!t.metaKey&&!t.ctrlKey&&!t.nativeEvent.isComposing&&(t.preventDefault(),w==="overview"?M.current?.focus():_("overview"))},"onKeyDown")}),o.managedByPlugin?(0,e.jsxs)(xe,{variant:"outline",className:"hidden shrink-0 gap-1.5 text-xs text-muted-foreground sm:inline-flex",children:[(0,e.jsx)(kt,{className:"h-3 w-3"}),o.managedByPlugin.pluginDisplayName,(0,e.jsx)("span",{className:"font-mono text-(length:--text-nano)",children:o.managedByPlugin.resourceKey})]}):null]}),(0,e.jsxs)("div",{className:"ml-auto flex shrink-0 items-center gap-3",children:[(0,e.jsx)(ts,{onClick:i(()=>b(!0),"onClick"),disabled:Z.isPending}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(Pt,{size:"default",checked:$,onCheckedChange:Ae.onToggleAutomation,disabled:Se,"aria-label":$?"Pause automatic triggers":"Enable automatic triggers"}),(0,e.jsx)("span",{className:`text-sm font-medium ${Ce}`,children:Ie})]})]})]}),(0,e.jsx)(es,{activeSection:w,onNavigate:_,isSectionDirty:ne}),(0,e.jsxs)("div",{className:"flex min-h-0 flex-1",children:[(0,e.jsx)(us,{activeSection:w,hrefFor:i(t=>`/routines/${s}/${t}`,"hrefFor"),isSectionDirty:ne,hasLiveRun:d,onNavigate:i(t=>le(s,t),"onNavigate")}),(0,e.jsx)("main",{id:"routine-section",role:"main",className:"min-h-0 min-w-0 flex-1 overflow-y-auto px-4 pb-6 pt-10 md:px-8",children:(0,e.jsxs)("section",{"aria-labelledby":"routine-section-title",className:Pe?"mx-auto w-full max-w-3xl":"w-full",children:[(0,e.jsx)("h2",{id:"routine-section-title",className:"mb-4 text-lg font-semibold",children:Ds[w]}),w==="overview"&&(0,e.jsx)(Ss,{}),w==="triggers"&&(0,e.jsx)(Is,{}),w==="variables"&&(0,e.jsx)(Cs,{}),w==="secrets"&&(0,e.jsx)(As,{}),w==="delivery"&&(0,e.jsx)(Ps,{}),w==="runs"&&(0,e.jsx)(rs,{}),w==="activity"&&(0,e.jsx)(os,{}),w==="history"&&(0,e.jsx)(Vt,{}),Pe?(0,e.jsx)(Yt,{dirtyFields:J(w),isSaving:Y.isPending,saveConflict:q,onSave:i(()=>{!Y.isPending&&f.title.trim()&&Y.mutate()},"onSave"),onDiscard:i(()=>be(w),"onDiscard"),onReload:ke}):null]})})]})]}),(0,e.jsx)(ft,{open:g,onOpenChange:b,companyId:o.companyId,routineName:o.title,agents:F??[],projects:K??[],defaultProjectId:o.projectId,defaultAssigneeAgentId:o.assigneeAgentId,variables:o.variables??[],isPending:Z.isPending,onSubmit:i(t=>Z.mutate(t),"onSubmit")})]})}i(di,"RoutineDetail");export{di as RoutineDetail};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var ks=Object.defineProperty;var t=(n,c)=>ks(n,"name",{value:c,configurable:!0});import{i as as}from"./rolldown-runtime-ZpX3ckPj.js";import{Fr as Ps,Lr as As,Pr as Ms,S as Ds,U as Ts,Y as m,nr as A,tr as _}from"./createLucideIcon-r3v6fbGz.js";import{B as ze,U as qs,b as Ks,ct as Us,o as Es}from"./router-DyZkoSkG.js";import{Ct as Os,O as Ls,bt as Qs,cr as ls,gr as Bs,lr as ee,or as Ge,r as Vs,sr as We,t as $s,v as he,vt as Ye,wt as zs,xt as Gs,yt as Ws}from"./RoutineRunVariablesDialog-IRX4TLng.js";import{l as J,t as Ys}from"./MarkdownEditor-Pip4OXiJ.js";import{t as He}from"./AgentAvatar-PT82VwmU.js";import{a as Hs,r as Js}from"./checkbox-CmMbs2PZ.js";import{n as Je,t as Xs}from"./tabs-DWRZjksg.js";import{a as Xe,c as Ze,r as es,t as Zs}from"./agents-BlSzFh-1.js";import{g as et}from"./StatusIcon-BuUYMqqU.js";import{r as st,t as je}from"./EmptyState-DPcc0zYh.js";import{t as tt}from"./check-DDiXDm2i.js";import{t as nt}from"./chevron-down-F9aZv-V7.js";import{t as cs}from"./chevron-right-B9JUOr38.js";import{c as ye,i as X,n as ve,s as be,t as we}from"./select-mS22eY6T.js";import{k as Z,t as F}from"./button-CAPbz11u.js";import{t as rt}from"./heartbeats-CK_aXmx5.js";import{i as it,o as ot}from"./company-members-BcZm1g8Q.js";import{r as at,t as lt}from"./card-dmVcp3AX.js";import{t as ct}from"./PageSkeleton-DHjTwRT3.js";import{$ as dt,$t as ut,J as mt,Q as pt,X as ft,Y as gt,Z as xt,at as ht,et as jt,fn as yt,ht as M,in as vt,it as bt,mt as wt,nt as Nt,pt as It,rn as Rt,rt as Ct,tt as St}from"./index-zttiya6r.js";var l=as(As(),1),s=as(Ps(),1),_t=["coalesce_if_active","always_enqueue","skip_if_active"],Ft=["skip_missed","enqueue_missed_with_cap"],kt={coalesce_if_active:"If a run is already active, keep just one follow-up run queued.",always_enqueue:"Queue every trigger occurrence, even if the routine is already running.",skip_if_active:"Drop new trigger occurrences while a run is still active."},Pt={skip_missed:"Ignore windows that were missed while the scheduler or routine was paused.",enqueue_missed_with_cap:"Catch up missed schedule windows after recovery; sub-hourly schedules are combined into one catch-up run, slower schedules replay each missed window up to a cap."};function ss(n){n&&(n.style.height="auto",n.style.height=`${n.scrollHeight}px`)}t(ss,"autoResizeTextarea");var At="__built_in_routines",ts={sortField:"title",sortDir:"asc",groupBy:"folder",collapsedGroups:[]};function ns(n){try{const c=localStorage.getItem(n);if(c)return{...ts,...JSON.parse(c)}}catch{}return{...ts}}t(ns,"getRoutineViewState");function Mt(n,c){localStorage.setItem(n,JSON.stringify(c))}t(Mt,"saveRoutineViewState");function q(n){if(!n)return Number.NEGATIVE_INFINITY;const c=new Date(n).getTime();return Number.isFinite(c)?c:Number.NEGATIVE_INFINITY}t(q,"timestampValue");function rs(n,c){return(n??"").localeCompare(c??"",void 0,{sensitivity:"base"})}t(rs,"compareNullableText");function Dt(n){return{...n,description:n.description.trim()||null,projectId:n.projectId||null,folderId:n.folderId||null,assigneeAgentId:n.assigneeAgentId||null}}t(Dt,"buildRoutineMutationPayload");function Tt(n,c,d,b,g){if(c==="none")return[{key:"__all",label:null,items:n}];if(c==="folder"){const i=he(n,o=>o.folderId??"__unfiled");return Object.keys(i).sort((o,j)=>{if(o==="__unfiled"||j==="__unfiled")return o===j?0:o==="__unfiled"?1:-1;const w=g.get(o),I=g.get(j),O=(Number.isFinite(w?.position)?w.position:Number.POSITIVE_INFINITY)-(Number.isFinite(I?.position)?I.position:Number.POSITIVE_INFINITY);return O!==0?O:(w?.name??"Unknown folder").localeCompare(I?.name??"Unknown folder",void 0,{sensitivity:"base"})||o.localeCompare(j)}).map(o=>({key:o,label:o==="__unfiled"?"Unfiled":g.get(o)?.name??"Unknown folder",items:i[o]}))}if(c==="project"){const i=he(n,o=>o.projectId??"__no_project");return Object.keys(i).sort((o,j)=>{const w=o==="__no_project"?"No project":d.get(o)?.name??"Unknown project",I=j==="__no_project"?"No project":d.get(j)?.name??"Unknown project";return w.localeCompare(I)}).map(o=>({key:o,label:o==="__no_project"?"No project":d.get(o)?.name??"Unknown project",items:i[o]}))}const x=he(n,i=>i.assigneeAgentId??"__unassigned");return Object.keys(x).sort((i,o)=>{const j=i==="__unassigned"?"Unassigned":b.get(i)?.name??"Unknown agent",w=o==="__unassigned"?"Unassigned":b.get(o)?.name??"Unknown agent";return j.localeCompare(w)}).map(i=>({key:i,label:i==="__unassigned"?"Unassigned":b.get(i)?.name??"Unknown agent",items:x[i]}))}t(Tt,"buildRoutineGroups");function is(n){return n.originKind==="built_in_agent_bundle"}t(is,"isBuiltInRoutine");function qt(n,c,d,b,g){const x=n.filter(is),i=Tt(n.filter(o=>!is(o)),c,d,b,g).filter(o=>o.items.length>0).map(o=>x.length>0&&c==="none"&&o.key==="__all"?{...o,label:"Custom routines"}:o);return x.length===0?i:[...i,{key:At,label:"Built-in routines",items:x}]}t(qt,"buildRoutineSections");function Kt(n,c,d){const b=d==="asc"?1:-1;return[...n].sort((g,x)=>{let i=0;return c==="title"?i=rs(g.title,x.title):c==="created"?i=q(g.createdAt)-q(x.createdAt):c==="lastRun"?i=q(g.lastRun?.triggeredAt??g.lastTriggeredAt)-q(x.lastRun?.triggeredAt??x.lastTriggeredAt):i=q(g.updatedAt)-q(x.updatedAt),i!==0?i*b:rs(g.title,x.title)})}t(Kt,"sortRoutines");function os(n){return n==="runs"?"/routines?tab=runs":"/routines"}t(os,"buildRoutinesTabHref");function Ut({label:n,count:c,isOpen:d}){return(0,s.jsxs)("div",{className:`flex items-center gap-2 rounded-lg border border-border px-3 py-2${d?" mb-1":""}`,children:[(0,s.jsxs)(ls,{className:"flex items-center gap-1.5",children:[(0,s.jsx)(cs,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform [[data-state=open]>&]:rotate-90"}),(0,s.jsx)("span",{className:"text-sm font-semibold uppercase tracking-wide",children:n})]}),(0,s.jsx)("span",{className:"text-xs text-muted-foreground",children:c})]})}t(Ut,"RoutineSectionHeader");function cn(){const{selectedCompanyId:n}=Ts(),{setBreadcrumbs:c}=st(),d=Ms(),b=Es(),[g,x]=Us(),{pushToast:i}=yt(),o=(0,l.useRef)(null),j=(0,l.useRef)(null),w=(0,l.useRef)(null),I=(0,l.useRef)(null),[O,K]=(0,l.useState)(!1),[se,L]=(0,l.useState)(null),[Q,te]=(0,l.useState)(null),[ds,Ne]=(0,l.useState)(!1),[ne,re]=(0,l.useState)(!1),[B,V]=(0,l.useState)([]),[Ie,Re]=(0,l.useState)([]),[us,Ce]=(0,l.useState)(null),[ms,Se]=(0,l.useState)(null),[k,ie]=(0,l.useState)(null),[$,z]=(0,l.useState)(!1),[_e,oe]=(0,l.useState)(!1),P=g.get("tab")==="runs"?"runs":"routines",[p,R]=(0,l.useState)({title:"",description:"",projectId:"",folderId:null,assigneeAgentId:"",priority:"medium",concurrencyPolicy:"coalesce_if_active",catchUpPolicy:"skip_missed",variables:[]}),G=n?`paperclip:routines-view:${n}`:"paperclip:routines-view",[u,Fe]=(0,l.useState)(()=>ns(G)),f=bt(g.get("folder"));(0,l.useEffect)(()=>{c([{label:"Routines"}])},[c]),(0,l.useEffect)(()=>{Fe(ns(G))},[G]);const{data:ke,isLoading:ps,error:ae}=A({queryKey:m.routines.list(n),queryFn:t(()=>J.list(n),"queryFn"),enabled:!!n}),{data:h,isLoading:Pe}=A({queryKey:m.folders.list(n,"routine"),queryFn:t(()=>M.list(n,"routine"),"queryFn"),enabled:!!n&&P==="routines"}),{data:C}=A({queryKey:m.agents.list(n),queryFn:t(()=>Zs.list(n),"queryFn"),enabled:!!n}),{data:S}=A({queryKey:m.projects.list(n,{includeArchived:!0}),queryFn:t(()=>et.list(n,{includeArchived:!0}),"queryFn"),enabled:!!n}),{data:Ae}=A({queryKey:m.access.companyUserDirectory(n),queryFn:t(()=>ot.listUserDirectory(n),"queryFn"),enabled:!!n}),{data:le,isLoading:fs,error:gs}=A({queryKey:[...m.issues.list(n),"routine-executions"],queryFn:t(()=>ze.list(n,{originKind:"routine_execution"}),"queryFn"),enabled:!!n&&P==="runs"}),Me=m.liveRuns(n),ce=vt({companyId:n,resourceKey:"live-runs",queryKey:Me,enabled:!!n&&P==="runs",refetchInterval:!1,leaderOnly:!0}),{data:de,dataUpdatedAt:xs}=A({queryKey:Me,queryFn:t(()=>rt.liveRunsForCompany(n),"queryFn"),enabled:ce.enabled,refetchInterval:ce.refetchInterval});Rt(ce,de,xs),(0,l.useEffect)(()=>{ss(j.current)},[p.title,$]);const hs=(0,l.useMemo)(()=>it({agents:C,projects:(S??[]).filter(e=>!e.archivedAt),members:Ae?.users}),[C,Ae?.users,S]),N=_({mutationFn:t(()=>J.create(n,Dt(p)),"mutationFn"),onSuccess:t(async e=>{R({title:"",description:"",projectId:"",folderId:null,assigneeAgentId:"",priority:"medium",concurrencyPolicy:"coalesce_if_active",catchUpPolicy:"skip_missed",variables:[]}),z(!1),oe(!1),await d.invalidateQueries({queryKey:m.routines.list(n)}),i({title:"Routine created",body:e.assigneeAgentId?"Add the first trigger to turn it into a live workflow.":"Draft saved. Add a default agent before enabling automation.",tone:"success"}),b(`/routines/${e.id}?tab=triggers`)},"onSuccess")}),De=_({mutationFn:t(e=>M.create(n,{kind:"routine",...e}),"mutationFn"),onSuccess:t(async e=>{if(K(!1),L(null),await d.invalidateQueries({queryKey:m.folders.list(n,"routine")}),Ie.length>0){const r=Ie;Re([]);try{await Promise.all(r.map(a=>M.moveItem(n,{kind:"routine",itemId:a,folderId:e.id}))),await Promise.all([d.invalidateQueries({queryKey:m.routines.list(n)}),d.invalidateQueries({queryKey:m.folders.list(n,"routine")})])}catch(a){i({title:"Folder created, move failed",body:a instanceof Error?a.message:"Paperclip could not move the selected routines.",tone:"error"});return}}else Y(e.id);i({title:"Folder created",body:e.name,tone:"success"})},"onSuccess"),onError:t(e=>{i({title:"Failed to save folder",body:e instanceof Error?e.message:"Paperclip could not save the folder.",tone:"error"})},"onError")}),ue=_({mutationFn:t(({folderId:e,payload:r})=>M.update(n,e,r),"mutationFn"),onSuccess:t(async()=>{K(!1),L(null),await d.invalidateQueries({queryKey:m.folders.list(n,"routine")})},"onSuccess"),onError:t(e=>{i({title:"Folder save failed",body:e instanceof Error?e.message:"Paperclip could not update the folder.",tone:"error"})},"onError")}),Te=_({mutationFn:t(e=>M.delete(n,e),"mutationFn"),onSuccess:t(async(e,r)=>{f===r&&Y("all"),te(null),await Promise.all([d.invalidateQueries({queryKey:m.routines.list(n)}),d.invalidateQueries({queryKey:m.folders.list(n,"routine")})]),i({title:"Folder deleted",body:"Items moved to Unfiled.",tone:"success"})},"onSuccess"),onError:t(e=>{i({title:"Folder delete failed",body:e instanceof Error?e.message:"Paperclip could not delete the folder.",tone:"error"})},"onError")}),qe=_({mutationFn:t(({itemId:e,folderId:r})=>M.moveItem(n,{kind:"routine",itemId:e,folderId:r}),"mutationFn"),onSuccess:t(async()=>{await Promise.all([d.invalidateQueries({queryKey:m.routines.list(n)}),d.invalidateQueries({queryKey:m.folders.list(n,"routine")})])},"onSuccess"),onError:t(e=>{i({title:"Move failed",body:e instanceof Error?e.message:"Paperclip could not move the routine.",tone:"error"})},"onError")}),js=_({mutationFn:t(({id:e,data:r})=>ze.update(e,r),"mutationFn"),onSuccess:t(async()=>{await d.invalidateQueries({queryKey:[...m.issues.list(n),"routine-executions"]})},"onSuccess")}),Ke=_({mutationFn:t(({id:e,status:r})=>J.update(e,{status:r}),"mutationFn"),onMutate:t(({id:e})=>{Se(e)},"onMutate"),onSuccess:t(async(e,r)=>{await Promise.all([d.invalidateQueries({queryKey:m.routines.list(n)}),d.invalidateQueries({queryKey:m.routines.detail(r.id)})])},"onSuccess"),onSettled:t(()=>{Se(null)},"onSettled"),onError:t(e=>{i({title:"Failed to update routine",body:e instanceof Error?e.message:"Paperclip could not update the routine.",tone:"error"})},"onError")}),Ue=_({mutationFn:t(({id:e,data:r})=>J.run(e,{...r?.variables&&Object.keys(r.variables).length>0?{variables:r.variables}:{},...r?.assigneeAgentId!==void 0?{assigneeAgentId:r.assigneeAgentId}:{},...r?.projectId!==void 0?{projectId:r.projectId}:{},...r?.executionWorkspaceId!==void 0?{executionWorkspaceId:r.executionWorkspaceId}:{},...r?.executionWorkspacePreference!==void 0?{executionWorkspacePreference:r.executionWorkspacePreference}:{},...r?.executionWorkspaceSettings!==void 0?{executionWorkspaceSettings:r.executionWorkspaceSettings}:{}}),"mutationFn"),onMutate:t(({id:e})=>{Ce(e)},"onMutate"),onSuccess:t(async(e,{id:r})=>{ie(null),await Promise.all([d.invalidateQueries({queryKey:m.routines.list(n)}),d.invalidateQueries({queryKey:m.routines.detail(r)})])},"onSuccess"),onSettled:t(()=>{Ce(null)},"onSettled"),onError:t(e=>{i({title:"Routine run failed",body:e instanceof Error?e.message:"Paperclip could not start the routine run.",tone:"error"})},"onError")}),me=(0,l.useMemo)(()=>Gs(),[$]),ys=(0,l.useMemo)(()=>Ws(),[$]),vs=(0,l.useMemo)(()=>Os((C??[]).filter(e=>e.status!=="terminated"),me).map(e=>({id:e.id,label:e.name,searchText:`${e.name} ${e.role} ${e.title??""}`})),[C,me]),bs=(0,l.useMemo)(()=>(S??[]).filter(e=>!e.archivedAt).map(e=>({id:e.id,label:e.name,searchText:e.description??""})),[S]),U=(0,l.useMemo)(()=>new Map((C??[]).map(e=>[e.id,e])),[C]),E=(0,l.useMemo)(()=>new Map((S??[]).map(e=>[e.id,e])),[S]),Ee=(0,l.useMemo)(()=>new Map((h?.folders??[]).map(e=>[e.id,e])),[h]),ws=(0,l.useMemo)(()=>Ls(de,le),[de,le]),y=(0,l.useMemo)(()=>(ke??[]).filter(e=>e.status!=="archived"),[ke]),Oe=(0,l.useMemo)(()=>u.groupBy!=="folder"||f==="all"?y:f==="unfiled"?y.filter(e=>!e.folderId):y.filter(e=>e.folderId===f),[f,u.groupBy,y]),pe=(0,l.useMemo)(()=>{if(!h)return h;const e=new Map;let r=0;for(const a of y)a.folderId?e.set(a.folderId,(e.get(a.folderId)??0)+1):r+=1;return{...h,allCount:y.length,unfiledCount:r,folders:h.folders.map(a=>({...a,itemCount:e.get(a.id)??0}))}},[h,y]),D=(0,l.useMemo)(()=>Kt(Oe,u.sortField,u.sortDir),[Oe,u.sortDir,u.sortField]),Ns=(0,l.useMemo)(()=>qt(D,u.groupBy,E,U,Ee),[U,Ee,E,u.groupBy,D]),Is=(0,l.useMemo)(()=>qs("Recent Runs",os("runs"),"issues"),[]),Le=p.assigneeAgentId?U.get(p.assigneeAgentId)??null:null,Qe=p.projectId?E.get(p.projectId)??null:null,Be=ht(h?.folders??[],f),W=(h?.folders.length??0)>0,fe=P==="routines"&&u.groupBy==="folder"&&W;function ge(e){Fe(r=>{const a={...r,...e};return Mt(G,a),a})}t(ge,"updateRoutineView");function Ve(e){const r=e==="runs"?"runs":"routines";(0,l.startTransition)(()=>{b(os(r))})}t(Ve,"handleTabChange");function Y(e){x(r=>{const a=new URLSearchParams(r),v=Ct(e);return v?a.set("folder",v):a.delete("folder"),a})}t(Y,"setFolderSelection");function T(e=[]){Re(e),L(null),K(!0)}t(T,"openCreateFolder");function $e(){R(e=>({...e,folderId:f==="all"||f==="unfiled"?null:f})),z(!0)}t($e,"openCreateRoutine");async function Rs(e){const r=B;if(r.length!==0)try{await Promise.all(r.map(a=>M.moveItem(n,{kind:"routine",itemId:a,folderId:e}))),V([]),re(!1),await Promise.all([d.invalidateQueries({queryKey:m.routines.list(n)}),d.invalidateQueries({queryKey:m.folders.list(n,"routine")})]),i({title:"Routines moved",body:`${r.length} routine${r.length===1?"":"s"} filed.`,tone:"success"})}catch(a){i({title:"Failed to move routines",body:a instanceof Error?a.message:"Paperclip could not move the selected routines.",tone:"error"})}}t(Rs,"moveSelectedRoutines");function Cs(e){ie(e)}t(Cs,"handleRunNow");function Ss(e,r){if(!r&&!e.assigneeAgentId){i({title:"Default agent required",body:"Set a default agent before enabling routine automation.",tone:"warn"});return}Ke.mutate({id:e.id,status:wt(e.status,!r)})}t(Ss,"handleToggleEnabled");function _s(e){Ke.mutate({id:e.id,status:e.status==="archived"?"active":"archived"})}return t(_s,"handleToggleArchived"),n?ps?(0,s.jsx)(ct,{variant:"issues-list"}):(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[(0,s.jsxs)("div",{className:"space-y-1",children:[(0,s.jsx)("h1",{className:"text-2xl font-semibold tracking-tight",children:"Routines"}),(0,s.jsx)("p",{className:"text-sm text-muted-foreground",children:"Recurring work definitions that materialize into auditable execution tasks."})]}),(0,s.jsxs)(F,{onClick:$e,children:[(0,s.jsx)(Z,{className:"mr-2 h-4 w-4"}),"Create routine"]})]}),(0,s.jsxs)(Xs,{value:P,onValueChange:Ve,children:[(0,s.jsx)(ut,{align:"start",value:P,onValueChange:Ve,items:[{value:"routines",label:"Routines"},{value:"runs",label:"Recent Runs"}]}),(0,s.jsxs)(Je,{value:"routines",className:"space-y-4",children:[(0,s.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,s.jsxs)("p",{className:"text-sm text-muted-foreground",children:[y.length," routine",y.length===1?"":"s"]}),(0,s.jsxs)("div",{className:"flex items-center gap-1",children:[(0,s.jsxs)(es,{children:[(0,s.jsx)(Ze,{asChild:!0,children:(0,s.jsxs)(F,{variant:"ghost",size:"sm",className:"text-xs",title:"Sort",children:[(0,s.jsx)(Bs,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1"}),(0,s.jsx)("span",{className:"hidden sm:inline",children:"Sort"})]})}),(0,s.jsx)(Xe,{align:"end",className:"w-44 p-0",children:(0,s.jsx)("div",{className:"p-2 space-y-0.5",children:[["updated","Updated"],["created","Created"],["lastRun","Last run"],["title","Title"]].map(([e,r])=>(0,s.jsxs)("button",{className:`flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm ${u.sortField===e?"bg-accent/50 text-foreground":"text-muted-foreground hover:bg-accent/50"}`,onClick:t(()=>{ge(u.sortField===e?{sortDir:u.sortDir==="asc"?"desc":"asc"}:{sortField:e,sortDir:e==="title"?"asc":"desc"})},"onClick"),children:[(0,s.jsx)("span",{children:r}),u.sortField===e?(0,s.jsx)("span",{className:"text-xs text-muted-foreground",children:u.sortDir==="asc"?"Asc":"Desc"}):null]},e))})})]}),(0,s.jsxs)(es,{children:[(0,s.jsx)(Ze,{asChild:!0,children:(0,s.jsxs)(F,{variant:"ghost",size:"sm",className:"text-xs",title:"Group",children:[(0,s.jsx)(Ks,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1"}),(0,s.jsx)("span",{className:"hidden sm:inline",children:"Group"})]})}),(0,s.jsx)(Xe,{align:"end",className:"w-44 p-0",children:(0,s.jsx)("div",{className:"p-2 space-y-0.5",children:[["folder","Folder"],["project","Project"],["assignee","Agent"],["none","None"]].map(([e,r])=>(0,s.jsxs)("button",{className:`flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm ${u.groupBy===e?"bg-accent/50 text-foreground":"text-muted-foreground hover:bg-accent/50"}`,onClick:t(()=>ge({groupBy:e,collapsedGroups:[]}),"onClick"),children:[(0,s.jsx)("span",{children:r}),u.groupBy===e?(0,s.jsx)(tt,{className:"h-3.5 w-3.5"}):null]},e))})})]}),u.groupBy==="folder"&&!W?(0,s.jsxs)(F,{variant:"outline",size:"sm",onClick:t(()=>T(),"onClick"),children:[(0,s.jsx)(Z,{className:"mr-2 h-3.5 w-3.5"}),"New folder"]}):null,fe?(0,s.jsx)(F,{variant:"ghost",size:"sm",className:"text-xs",onClick:t(()=>re(e=>!e),"onClick"),children:ne?"Done":"Select"}):null]})]}),u.groupBy==="folder"?(0,s.jsx)("div",{className:"md:hidden",children:(0,s.jsx)(xt,{result:pe,selection:f,allLabel:"All routines",onClick:t(()=>Ne(!0),"onClick")})}):null]}),(0,s.jsx)(Je,{value:"runs",children:(0,s.jsx)(Vs,{issues:le??[],isLoading:fs,error:gs,agents:C,projects:S,liveIssueIds:ws,viewStateKey:"paperclip:routine-recent-runs-view",issueLinkState:Is,onUpdateIssue:t((e,r)=>js.mutate({id:e,data:r}),"onUpdateIssue")})})]}),(0,s.jsx)(Js,{open:$,onOpenChange:t(e=>{N.isPending||z(e)},"onOpenChange"),children:(0,s.jsxs)(Hs,{showCloseButton:!1,className:"flex max-h-(--sz-calc-18) max-w-3xl flex-col gap-0 overflow-hidden p-0",children:[(0,s.jsxs)("div",{className:"shrink-0 flex flex-wrap items-center justify-between gap-3 border-b border-border/60 px-5 py-3",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"New routine"}),(0,s.jsx)("p",{className:"text-sm text-muted-foreground",children:"Define the recurring work first. Default project and agent are optional for draft routines."})]}),(0,s.jsx)(F,{variant:"ghost",size:"sm",onClick:t(()=>{z(!1),oe(!1)},"onClick"),disabled:N.isPending,children:"Cancel"})]}),(0,s.jsxs)("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[(0,s.jsx)("div",{className:"px-5 pt-5 pb-3",children:(0,s.jsx)("textarea",{ref:j,className:"w-full resize-none overflow-hidden bg-transparent text-xl font-semibold outline-none placeholder:text-muted-foreground/50",placeholder:"Routine title",rows:1,value:p.title,onChange:t(e=>{R(r=>({...r,title:e.target.value})),ss(e.target)},"onChange"),onKeyDown:t(e=>{if(e.key==="Enter"&&!e.metaKey&&!e.ctrlKey&&!e.nativeEvent.isComposing){e.preventDefault(),o.current?.focus();return}e.key==="Tab"&&!e.shiftKey&&(e.preventDefault(),p.assigneeAgentId?p.projectId?o.current?.focus():I.current?.focus():w.current?.focus())},"onKeyDown"),autoFocus:!0})}),(0,s.jsx)("div",{className:"px-5 pb-3",children:(0,s.jsx)("div",{className:"overflow-x-auto overscroll-x-contain",children:(0,s.jsxs)("div",{className:"inline-flex min-w-full flex-wrap items-center gap-2 text-sm text-muted-foreground sm:min-w-max sm:flex-nowrap",children:[(0,s.jsx)("span",{children:"For"}),(0,s.jsx)(Ye,{ref:w,value:p.assigneeAgentId,options:vs,recentOptionIds:me,placeholder:"Responsible",noneLabel:"No responsible",searchPlaceholder:"Search responsible...",emptyMessage:"No responsible found.",onChange:t(e=>{e&&zs(e),R(r=>({...r,assigneeAgentId:e}))},"onChange"),onConfirm:t(()=>{p.projectId?o.current?.focus():I.current?.focus()},"onConfirm"),renderTriggerValue:t(e=>e?Le?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(He,{agent:Le,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,s.jsx)("span",{className:"truncate",children:e.label})]}):(0,s.jsx)("span",{className:"truncate",children:e.label}):(0,s.jsx)("span",{className:"text-muted-foreground",children:"Responsible"}),"renderTriggerValue"),renderOption:t(e=>{if(!e.id)return(0,s.jsx)("span",{className:"truncate",children:e.label});const r=U.get(e.id);return(0,s.jsxs)(s.Fragment,{children:[r?(0,s.jsx)(He,{agent:r,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,(0,s.jsx)("span",{className:"truncate",children:e.label})]})},"renderOption")}),(0,s.jsx)("span",{children:"in"}),(0,s.jsx)(Ye,{ref:I,value:p.projectId,options:bs,recentOptionIds:ys,placeholder:"Project",noneLabel:"No project",searchPlaceholder:"Search projects...",emptyMessage:"No projects found.",onChange:t(e=>{e&&Qs(e),R(r=>({...r,projectId:e}))},"onChange"),onConfirm:t(()=>o.current?.focus(),"onConfirm"),renderTriggerValue:t(e=>e&&Qe?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:Qe.color??"var(--project-none)"}}),(0,s.jsx)("span",{className:"truncate",children:e.label})]}):(0,s.jsx)("span",{className:"text-muted-foreground",children:"Project"}),"renderTriggerValue"),renderOption:t(e=>{if(!e.id)return(0,s.jsx)("span",{className:"truncate",children:e.label});const r=E.get(e.id);return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:r?.color??"var(--project-none)"}}),(0,s.jsx)("span",{className:"truncate",children:e.label})]})},"renderOption")}),(0,s.jsx)("span",{children:"filed in"}),(0,s.jsxs)(we,{value:p.folderId??"__unfiled",onValueChange:t(e=>R(r=>({...r,folderId:e==="__unfiled"?null:e})),"onValueChange"),children:[(0,s.jsx)(be,{className:"h-8 w-auto min-w-32 border-0 bg-muted/50 px-2 shadow-none",children:(0,s.jsx)(ye,{})}),(0,s.jsxs)(ve,{children:[(0,s.jsx)(X,{value:"__unfiled",children:"Unfiled"}),(h?.folders??[]).map(e=>(0,s.jsx)(X,{value:e.id,children:e.name},e.id))]})]})]})})}),(0,s.jsx)("div",{className:"border-t border-border/60 px-5 py-4",children:(0,s.jsx)(Ys,{ref:o,value:p.description,onChange:t(e=>R(r=>({...r,description:e})),"onChange"),placeholder:"Add instructions...",bordered:!1,contentClassName:"min-h-(--sz-160px) text-sm text-muted-foreground",mentions:hs,onSubmit:t(()=>{!N.isPending&&p.title.trim()&&p.projectId&&p.assigneeAgentId&&N.mutate()},"onSubmit")})}),(0,s.jsx)("div",{className:"border-t border-border/60 px-5 py-3",children:(0,s.jsxs)(Ge,{open:_e,onOpenChange:oe,children:[(0,s.jsxs)(ls,{className:"flex w-full items-center justify-between text-left",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"text-sm font-medium",children:"Advanced delivery settings"}),(0,s.jsx)("p",{className:"text-sm text-muted-foreground",children:"Keep policy controls secondary to the work definition."})]}),_e?(0,s.jsx)(nt,{className:"h-4 w-4 text-muted-foreground"}):(0,s.jsx)(cs,{className:"h-4 w-4 text-muted-foreground"})]}),(0,s.jsx)(We,{className:"pt-3",children:(0,s.jsxs)("div",{className:"grid gap-4 md:grid-cols-2",children:[(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Concurrency"}),(0,s.jsxs)(we,{value:p.concurrencyPolicy,onValueChange:t(e=>R(r=>({...r,concurrencyPolicy:e})),"onValueChange"),children:[(0,s.jsx)(be,{children:(0,s.jsx)(ye,{})}),(0,s.jsx)(ve,{children:_t.map(e=>(0,s.jsx)(X,{value:e,children:e.replaceAll("_"," ")},e))})]}),(0,s.jsx)("p",{className:"text-xs text-muted-foreground",children:kt[p.concurrencyPolicy]})]}),(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Catch-up"}),(0,s.jsxs)(we,{value:p.catchUpPolicy,onValueChange:t(e=>R(r=>({...r,catchUpPolicy:e})),"onValueChange"),children:[(0,s.jsx)(be,{children:(0,s.jsx)(ye,{})}),(0,s.jsx)(ve,{children:Ft.map(e=>(0,s.jsx)(X,{value:e,children:e.replaceAll("_"," ")},e))})]}),(0,s.jsx)("p",{className:"text-xs text-muted-foreground",children:Pt[p.catchUpPolicy]})]})]})})]})})]}),(0,s.jsxs)("div",{className:"shrink-0 flex flex-col gap-3 border-t border-border/60 px-5 py-4 sm:flex-row sm:items-center sm:justify-between",children:[(0,s.jsx)("div",{className:"text-sm text-muted-foreground",children:"After creation, Paperclip takes you straight to trigger setup. Draft routines stay paused until you add a default agent."}),(0,s.jsxs)("div",{className:"flex flex-col gap-2 sm:items-end",children:[(0,s.jsxs)(F,{onClick:t(()=>N.mutate(),"onClick"),disabled:N.isPending||!p.title.trim(),children:[(0,s.jsx)(Z,{className:"mr-2 h-4 w-4"}),N.isPending?"Creating...":"Create routine"]}),N.isError?(0,s.jsx)("p",{className:"text-sm text-destructive",children:N.error instanceof Error?N.error.message:"Failed to create routine"}):null]})]})]})}),ae?(0,s.jsx)(lt,{children:(0,s.jsx)(at,{className:"pt-6 text-sm text-destructive",children:ae instanceof Error?ae.message:"Failed to load routines"})}):null,P==="routines"?(0,s.jsxs)("div",{className:Ds(fe&&"flex gap-4"),children:[fe?(0,s.jsx)(dt,{result:pe,selection:f,allLabel:"All routines",itemLabelPlural:"routines",loading:Pe,onSelect:Y,onCreate:t(()=>T(),"onCreate"),onRename:t((e,r)=>ue.mutate({folderId:e.id,payload:{name:r}}),"onRename"),onEdit:t(e=>{L(e),K(!0)},"onEdit"),onDelete:te}):null,(0,s.jsxs)("div",{className:"min-w-0 flex-1",children:[u.groupBy==="folder"&&W?(0,s.jsx)("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:f==="all"?(0,s.jsx)(Et,{label:"All routines",count:D.length}):(0,s.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,s.jsx)(jt,{color:Be?.color}),(0,s.jsx)("span",{className:"truncate font-medium",children:f==="unfiled"?"Unfiled":Be?.name??"Folder"}),(0,s.jsxs)("span",{className:"text-muted-foreground",children:[D.length," routine",D.length===1?"":"s"]})]})}):null,u.groupBy==="folder"&&!W&&!Pe&&y.length>0?(0,s.jsx)(mt,{storageKey:`paperclip:routines-folder-nudge:${n??"none"}`,itemLabelPlural:"routines",onCreateFolder:t(()=>T(),"onCreateFolder")}):null,ne?(0,s.jsx)(gt,{selectedCount:B.length,folders:h?.folders??[],onMove:t(e=>{Rs(e)},"onMove"),onCreateAndMove:t(()=>T(B),"onCreateAndMove"),onClear:t(()=>V([]),"onClear"),onDone:t(()=>{re(!1),V([])},"onDone")}):null,y.length===0?(0,s.jsx)("div",{className:"py-12",children:(0,s.jsx)(je,{icon:ee,message:"No active routines. Use Create routine to define the first recurring workflow."})}):D.length===0?(0,s.jsxs)("div",{className:"py-12",children:[(0,s.jsx)(je,{icon:ee,message:f==="all"?"No routines match this view.":"This folder is empty."}),f!=="all"?(0,s.jsx)("div",{className:"mt-3 flex justify-center",children:(0,s.jsxs)(F,{size:"sm",onClick:$e,children:[(0,s.jsx)(Z,{className:"mr-2 h-3.5 w-3.5"}),"New routine in this folder"]})}):null]}):(0,s.jsx)("div",{className:"flex flex-col gap-3",children:Ns.map(e=>{const r=!u.collapsedGroups.includes(e.key);return(0,s.jsxs)(Ge,{open:r,onOpenChange:t(a=>{ge({collapsedGroups:a?u.collapsedGroups.filter(v=>v!==e.key):[...u.collapsedGroups,e.key]})},"onOpenChange"),children:[e.label?(0,s.jsx)(Ut,{label:e.label,count:e.items.length,isOpen:r}):null,(0,s.jsx)(We,{children:e.items.map(a=>(0,s.jsx)(It,{routine:a,projectById:E,agentById:U,runningRoutineId:us,statusMutationRoutineId:ms,href:`/routines/${a.id}`,runNowButton:!0,divider:!1,onRunNow:Cs,onToggleEnabled:Ss,onToggleArchived:_s,selectMode:ne,selected:B.includes(a.id),onSelectChange:t((v,xe)=>{V(H=>xe?Array.from(new Set([...H,v.id])):H.filter(Fs=>Fs!==v.id))},"onSelectChange"),extraMenuItems:(0,s.jsx)(Nt,{folders:h?.folders??[],currentFolderId:a.folderId??null,onMove:t(v=>{const xe=a.folderId??null;qe.mutate({itemId:a.id,folderId:v}),i({title:"Routine moved",body:v?`Moved "${a.title}" to ${h?.folders.find(H=>H.id===v)?.name??"folder"}.`:`Moved "${a.title}" to Unfiled.`,tone:"success",action:{label:"Undo",onClick:t(()=>qe.mutate({itemId:a.id,folderId:xe}),"onClick")}})},"onMove"),onCreateAndMove:t(()=>T([a.id]),"onCreateAndMove")})},a.id))})]},e.key)})})]})]}):null,(0,s.jsx)(pt,{open:O,kind:"routine",folder:se,pending:De.isPending||ue.isPending,onOpenChange:K,onSubmit:t(e=>{se?ue.mutate({folderId:se.id,payload:e}):De.mutate(e)},"onSubmit")}),(0,s.jsx)(ft,{open:Q!==null,folder:Q,itemLabelPlural:"routines",pending:Te.isPending,onOpenChange:t(e=>{e||te(null)},"onOpenChange"),onConfirm:t(()=>{Q&&Te.mutate(Q.id)},"onConfirm")}),(0,s.jsx)(St,{open:ds,onOpenChange:Ne,result:pe,selection:f,allLabel:"All routines",itemLabelPlural:"Routines",onSelect:Y,onCreate:t(()=>T(),"onCreate")}),(0,s.jsx)($s,{open:k!==null,onOpenChange:t(e=>{e||ie(null)},"onOpenChange"),companyId:n,routineName:k?.title??null,agents:C??[],projects:S??[],defaultProjectId:k?.projectId??null,defaultAssigneeAgentId:k?.assigneeAgentId??null,variables:k?.variables??[],isPending:Ue.isPending,onSubmit:t(e=>{k&&Ue.mutate({id:k.id,data:e})},"onSubmit")})]}):(0,s.jsx)(je,{icon:ee,message:"Select a company to view routines."})}t(cn,"Routines");function Et({label:n,count:c}){return(0,s.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,s.jsx)(ee,{className:"h-3.5 w-3.5 text-muted-foreground"}),(0,s.jsx)("span",{className:"truncate font-medium",children:n}),(0,s.jsxs)("span",{className:"text-muted-foreground",children:[c," routine",c===1?"":"s"]})]})}t(Et,"FolderIconHeader");export{cn as Routines};
|
|
1
|
+
var ks=Object.defineProperty;var t=(n,c)=>ks(n,"name",{value:c,configurable:!0});import{i as as}from"./rolldown-runtime-ZpX3ckPj.js";import{Fr as Ps,Lr as As,Pr as Ms,S as Ds,U as Ts,Y as m,nr as A,tr as _}from"./createLucideIcon-r3v6fbGz.js";import{B as ze,U as qs,b as Ks,ct as Us,o as Es}from"./router-DyZkoSkG.js";import{Ct as Os,O as Ls,bt as Qs,cr as ls,gr as Bs,lr as ee,or as Ge,r as Vs,sr as We,t as $s,v as he,vt as Ye,wt as zs,xt as Gs,yt as Ws}from"./RoutineRunVariablesDialog-IRX4TLng.js";import{l as J,t as Ys}from"./MarkdownEditor-Pip4OXiJ.js";import{t as He}from"./AgentAvatar-PT82VwmU.js";import{a as Hs,r as Js}from"./checkbox-CmMbs2PZ.js";import{n as Je,t as Xs}from"./tabs-DWRZjksg.js";import{a as Xe,c as Ze,r as es,t as Zs}from"./agents-BlSzFh-1.js";import{g as et}from"./StatusIcon-BuUYMqqU.js";import{r as st,t as je}from"./EmptyState-DPcc0zYh.js";import{t as tt}from"./check-DDiXDm2i.js";import{t as nt}from"./chevron-down-F9aZv-V7.js";import{t as cs}from"./chevron-right-B9JUOr38.js";import{c as ye,i as X,n as ve,s as be,t as we}from"./select-mS22eY6T.js";import{k as Z,t as F}from"./button-CAPbz11u.js";import{t as rt}from"./heartbeats-CK_aXmx5.js";import{i as it,o as ot}from"./company-members-BcZm1g8Q.js";import{r as at,t as lt}from"./card-dmVcp3AX.js";import{t as ct}from"./PageSkeleton-DHjTwRT3.js";import{$ as dt,$t as ut,J as mt,Q as pt,X as ft,Y as gt,Z as xt,at as ht,et as jt,fn as yt,ht as M,in as vt,it as bt,mt as wt,nt as Nt,pt as It,rn as Rt,rt as Ct,tt as St}from"./index-BF7JM92C.js";var l=as(As(),1),s=as(Ps(),1),_t=["coalesce_if_active","always_enqueue","skip_if_active"],Ft=["skip_missed","enqueue_missed_with_cap"],kt={coalesce_if_active:"If a run is already active, keep just one follow-up run queued.",always_enqueue:"Queue every trigger occurrence, even if the routine is already running.",skip_if_active:"Drop new trigger occurrences while a run is still active."},Pt={skip_missed:"Ignore windows that were missed while the scheduler or routine was paused.",enqueue_missed_with_cap:"Catch up missed schedule windows after recovery; sub-hourly schedules are combined into one catch-up run, slower schedules replay each missed window up to a cap."};function ss(n){n&&(n.style.height="auto",n.style.height=`${n.scrollHeight}px`)}t(ss,"autoResizeTextarea");var At="__built_in_routines",ts={sortField:"title",sortDir:"asc",groupBy:"folder",collapsedGroups:[]};function ns(n){try{const c=localStorage.getItem(n);if(c)return{...ts,...JSON.parse(c)}}catch{}return{...ts}}t(ns,"getRoutineViewState");function Mt(n,c){localStorage.setItem(n,JSON.stringify(c))}t(Mt,"saveRoutineViewState");function q(n){if(!n)return Number.NEGATIVE_INFINITY;const c=new Date(n).getTime();return Number.isFinite(c)?c:Number.NEGATIVE_INFINITY}t(q,"timestampValue");function rs(n,c){return(n??"").localeCompare(c??"",void 0,{sensitivity:"base"})}t(rs,"compareNullableText");function Dt(n){return{...n,description:n.description.trim()||null,projectId:n.projectId||null,folderId:n.folderId||null,assigneeAgentId:n.assigneeAgentId||null}}t(Dt,"buildRoutineMutationPayload");function Tt(n,c,d,b,g){if(c==="none")return[{key:"__all",label:null,items:n}];if(c==="folder"){const i=he(n,o=>o.folderId??"__unfiled");return Object.keys(i).sort((o,j)=>{if(o==="__unfiled"||j==="__unfiled")return o===j?0:o==="__unfiled"?1:-1;const w=g.get(o),I=g.get(j),O=(Number.isFinite(w?.position)?w.position:Number.POSITIVE_INFINITY)-(Number.isFinite(I?.position)?I.position:Number.POSITIVE_INFINITY);return O!==0?O:(w?.name??"Unknown folder").localeCompare(I?.name??"Unknown folder",void 0,{sensitivity:"base"})||o.localeCompare(j)}).map(o=>({key:o,label:o==="__unfiled"?"Unfiled":g.get(o)?.name??"Unknown folder",items:i[o]}))}if(c==="project"){const i=he(n,o=>o.projectId??"__no_project");return Object.keys(i).sort((o,j)=>{const w=o==="__no_project"?"No project":d.get(o)?.name??"Unknown project",I=j==="__no_project"?"No project":d.get(j)?.name??"Unknown project";return w.localeCompare(I)}).map(o=>({key:o,label:o==="__no_project"?"No project":d.get(o)?.name??"Unknown project",items:i[o]}))}const x=he(n,i=>i.assigneeAgentId??"__unassigned");return Object.keys(x).sort((i,o)=>{const j=i==="__unassigned"?"Unassigned":b.get(i)?.name??"Unknown agent",w=o==="__unassigned"?"Unassigned":b.get(o)?.name??"Unknown agent";return j.localeCompare(w)}).map(i=>({key:i,label:i==="__unassigned"?"Unassigned":b.get(i)?.name??"Unknown agent",items:x[i]}))}t(Tt,"buildRoutineGroups");function is(n){return n.originKind==="built_in_agent_bundle"}t(is,"isBuiltInRoutine");function qt(n,c,d,b,g){const x=n.filter(is),i=Tt(n.filter(o=>!is(o)),c,d,b,g).filter(o=>o.items.length>0).map(o=>x.length>0&&c==="none"&&o.key==="__all"?{...o,label:"Custom routines"}:o);return x.length===0?i:[...i,{key:At,label:"Built-in routines",items:x}]}t(qt,"buildRoutineSections");function Kt(n,c,d){const b=d==="asc"?1:-1;return[...n].sort((g,x)=>{let i=0;return c==="title"?i=rs(g.title,x.title):c==="created"?i=q(g.createdAt)-q(x.createdAt):c==="lastRun"?i=q(g.lastRun?.triggeredAt??g.lastTriggeredAt)-q(x.lastRun?.triggeredAt??x.lastTriggeredAt):i=q(g.updatedAt)-q(x.updatedAt),i!==0?i*b:rs(g.title,x.title)})}t(Kt,"sortRoutines");function os(n){return n==="runs"?"/routines?tab=runs":"/routines"}t(os,"buildRoutinesTabHref");function Ut({label:n,count:c,isOpen:d}){return(0,s.jsxs)("div",{className:`flex items-center gap-2 rounded-lg border border-border px-3 py-2${d?" mb-1":""}`,children:[(0,s.jsxs)(ls,{className:"flex items-center gap-1.5",children:[(0,s.jsx)(cs,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform [[data-state=open]>&]:rotate-90"}),(0,s.jsx)("span",{className:"text-sm font-semibold uppercase tracking-wide",children:n})]}),(0,s.jsx)("span",{className:"text-xs text-muted-foreground",children:c})]})}t(Ut,"RoutineSectionHeader");function cn(){const{selectedCompanyId:n}=Ts(),{setBreadcrumbs:c}=st(),d=Ms(),b=Es(),[g,x]=Us(),{pushToast:i}=yt(),o=(0,l.useRef)(null),j=(0,l.useRef)(null),w=(0,l.useRef)(null),I=(0,l.useRef)(null),[O,K]=(0,l.useState)(!1),[se,L]=(0,l.useState)(null),[Q,te]=(0,l.useState)(null),[ds,Ne]=(0,l.useState)(!1),[ne,re]=(0,l.useState)(!1),[B,V]=(0,l.useState)([]),[Ie,Re]=(0,l.useState)([]),[us,Ce]=(0,l.useState)(null),[ms,Se]=(0,l.useState)(null),[k,ie]=(0,l.useState)(null),[$,z]=(0,l.useState)(!1),[_e,oe]=(0,l.useState)(!1),P=g.get("tab")==="runs"?"runs":"routines",[p,R]=(0,l.useState)({title:"",description:"",projectId:"",folderId:null,assigneeAgentId:"",priority:"medium",concurrencyPolicy:"coalesce_if_active",catchUpPolicy:"skip_missed",variables:[]}),G=n?`paperclip:routines-view:${n}`:"paperclip:routines-view",[u,Fe]=(0,l.useState)(()=>ns(G)),f=bt(g.get("folder"));(0,l.useEffect)(()=>{c([{label:"Routines"}])},[c]),(0,l.useEffect)(()=>{Fe(ns(G))},[G]);const{data:ke,isLoading:ps,error:ae}=A({queryKey:m.routines.list(n),queryFn:t(()=>J.list(n),"queryFn"),enabled:!!n}),{data:h,isLoading:Pe}=A({queryKey:m.folders.list(n,"routine"),queryFn:t(()=>M.list(n,"routine"),"queryFn"),enabled:!!n&&P==="routines"}),{data:C}=A({queryKey:m.agents.list(n),queryFn:t(()=>Zs.list(n),"queryFn"),enabled:!!n}),{data:S}=A({queryKey:m.projects.list(n,{includeArchived:!0}),queryFn:t(()=>et.list(n,{includeArchived:!0}),"queryFn"),enabled:!!n}),{data:Ae}=A({queryKey:m.access.companyUserDirectory(n),queryFn:t(()=>ot.listUserDirectory(n),"queryFn"),enabled:!!n}),{data:le,isLoading:fs,error:gs}=A({queryKey:[...m.issues.list(n),"routine-executions"],queryFn:t(()=>ze.list(n,{originKind:"routine_execution"}),"queryFn"),enabled:!!n&&P==="runs"}),Me=m.liveRuns(n),ce=vt({companyId:n,resourceKey:"live-runs",queryKey:Me,enabled:!!n&&P==="runs",refetchInterval:!1,leaderOnly:!0}),{data:de,dataUpdatedAt:xs}=A({queryKey:Me,queryFn:t(()=>rt.liveRunsForCompany(n),"queryFn"),enabled:ce.enabled,refetchInterval:ce.refetchInterval});Rt(ce,de,xs),(0,l.useEffect)(()=>{ss(j.current)},[p.title,$]);const hs=(0,l.useMemo)(()=>it({agents:C,projects:(S??[]).filter(e=>!e.archivedAt),members:Ae?.users}),[C,Ae?.users,S]),N=_({mutationFn:t(()=>J.create(n,Dt(p)),"mutationFn"),onSuccess:t(async e=>{R({title:"",description:"",projectId:"",folderId:null,assigneeAgentId:"",priority:"medium",concurrencyPolicy:"coalesce_if_active",catchUpPolicy:"skip_missed",variables:[]}),z(!1),oe(!1),await d.invalidateQueries({queryKey:m.routines.list(n)}),i({title:"Routine created",body:e.assigneeAgentId?"Add the first trigger to turn it into a live workflow.":"Draft saved. Add a default agent before enabling automation.",tone:"success"}),b(`/routines/${e.id}?tab=triggers`)},"onSuccess")}),De=_({mutationFn:t(e=>M.create(n,{kind:"routine",...e}),"mutationFn"),onSuccess:t(async e=>{if(K(!1),L(null),await d.invalidateQueries({queryKey:m.folders.list(n,"routine")}),Ie.length>0){const r=Ie;Re([]);try{await Promise.all(r.map(a=>M.moveItem(n,{kind:"routine",itemId:a,folderId:e.id}))),await Promise.all([d.invalidateQueries({queryKey:m.routines.list(n)}),d.invalidateQueries({queryKey:m.folders.list(n,"routine")})])}catch(a){i({title:"Folder created, move failed",body:a instanceof Error?a.message:"Paperclip could not move the selected routines.",tone:"error"});return}}else Y(e.id);i({title:"Folder created",body:e.name,tone:"success"})},"onSuccess"),onError:t(e=>{i({title:"Failed to save folder",body:e instanceof Error?e.message:"Paperclip could not save the folder.",tone:"error"})},"onError")}),ue=_({mutationFn:t(({folderId:e,payload:r})=>M.update(n,e,r),"mutationFn"),onSuccess:t(async()=>{K(!1),L(null),await d.invalidateQueries({queryKey:m.folders.list(n,"routine")})},"onSuccess"),onError:t(e=>{i({title:"Folder save failed",body:e instanceof Error?e.message:"Paperclip could not update the folder.",tone:"error"})},"onError")}),Te=_({mutationFn:t(e=>M.delete(n,e),"mutationFn"),onSuccess:t(async(e,r)=>{f===r&&Y("all"),te(null),await Promise.all([d.invalidateQueries({queryKey:m.routines.list(n)}),d.invalidateQueries({queryKey:m.folders.list(n,"routine")})]),i({title:"Folder deleted",body:"Items moved to Unfiled.",tone:"success"})},"onSuccess"),onError:t(e=>{i({title:"Folder delete failed",body:e instanceof Error?e.message:"Paperclip could not delete the folder.",tone:"error"})},"onError")}),qe=_({mutationFn:t(({itemId:e,folderId:r})=>M.moveItem(n,{kind:"routine",itemId:e,folderId:r}),"mutationFn"),onSuccess:t(async()=>{await Promise.all([d.invalidateQueries({queryKey:m.routines.list(n)}),d.invalidateQueries({queryKey:m.folders.list(n,"routine")})])},"onSuccess"),onError:t(e=>{i({title:"Move failed",body:e instanceof Error?e.message:"Paperclip could not move the routine.",tone:"error"})},"onError")}),js=_({mutationFn:t(({id:e,data:r})=>ze.update(e,r),"mutationFn"),onSuccess:t(async()=>{await d.invalidateQueries({queryKey:[...m.issues.list(n),"routine-executions"]})},"onSuccess")}),Ke=_({mutationFn:t(({id:e,status:r})=>J.update(e,{status:r}),"mutationFn"),onMutate:t(({id:e})=>{Se(e)},"onMutate"),onSuccess:t(async(e,r)=>{await Promise.all([d.invalidateQueries({queryKey:m.routines.list(n)}),d.invalidateQueries({queryKey:m.routines.detail(r.id)})])},"onSuccess"),onSettled:t(()=>{Se(null)},"onSettled"),onError:t(e=>{i({title:"Failed to update routine",body:e instanceof Error?e.message:"Paperclip could not update the routine.",tone:"error"})},"onError")}),Ue=_({mutationFn:t(({id:e,data:r})=>J.run(e,{...r?.variables&&Object.keys(r.variables).length>0?{variables:r.variables}:{},...r?.assigneeAgentId!==void 0?{assigneeAgentId:r.assigneeAgentId}:{},...r?.projectId!==void 0?{projectId:r.projectId}:{},...r?.executionWorkspaceId!==void 0?{executionWorkspaceId:r.executionWorkspaceId}:{},...r?.executionWorkspacePreference!==void 0?{executionWorkspacePreference:r.executionWorkspacePreference}:{},...r?.executionWorkspaceSettings!==void 0?{executionWorkspaceSettings:r.executionWorkspaceSettings}:{}}),"mutationFn"),onMutate:t(({id:e})=>{Ce(e)},"onMutate"),onSuccess:t(async(e,{id:r})=>{ie(null),await Promise.all([d.invalidateQueries({queryKey:m.routines.list(n)}),d.invalidateQueries({queryKey:m.routines.detail(r)})])},"onSuccess"),onSettled:t(()=>{Ce(null)},"onSettled"),onError:t(e=>{i({title:"Routine run failed",body:e instanceof Error?e.message:"Paperclip could not start the routine run.",tone:"error"})},"onError")}),me=(0,l.useMemo)(()=>Gs(),[$]),ys=(0,l.useMemo)(()=>Ws(),[$]),vs=(0,l.useMemo)(()=>Os((C??[]).filter(e=>e.status!=="terminated"),me).map(e=>({id:e.id,label:e.name,searchText:`${e.name} ${e.role} ${e.title??""}`})),[C,me]),bs=(0,l.useMemo)(()=>(S??[]).filter(e=>!e.archivedAt).map(e=>({id:e.id,label:e.name,searchText:e.description??""})),[S]),U=(0,l.useMemo)(()=>new Map((C??[]).map(e=>[e.id,e])),[C]),E=(0,l.useMemo)(()=>new Map((S??[]).map(e=>[e.id,e])),[S]),Ee=(0,l.useMemo)(()=>new Map((h?.folders??[]).map(e=>[e.id,e])),[h]),ws=(0,l.useMemo)(()=>Ls(de,le),[de,le]),y=(0,l.useMemo)(()=>(ke??[]).filter(e=>e.status!=="archived"),[ke]),Oe=(0,l.useMemo)(()=>u.groupBy!=="folder"||f==="all"?y:f==="unfiled"?y.filter(e=>!e.folderId):y.filter(e=>e.folderId===f),[f,u.groupBy,y]),pe=(0,l.useMemo)(()=>{if(!h)return h;const e=new Map;let r=0;for(const a of y)a.folderId?e.set(a.folderId,(e.get(a.folderId)??0)+1):r+=1;return{...h,allCount:y.length,unfiledCount:r,folders:h.folders.map(a=>({...a,itemCount:e.get(a.id)??0}))}},[h,y]),D=(0,l.useMemo)(()=>Kt(Oe,u.sortField,u.sortDir),[Oe,u.sortDir,u.sortField]),Ns=(0,l.useMemo)(()=>qt(D,u.groupBy,E,U,Ee),[U,Ee,E,u.groupBy,D]),Is=(0,l.useMemo)(()=>qs("Recent Runs",os("runs"),"issues"),[]),Le=p.assigneeAgentId?U.get(p.assigneeAgentId)??null:null,Qe=p.projectId?E.get(p.projectId)??null:null,Be=ht(h?.folders??[],f),W=(h?.folders.length??0)>0,fe=P==="routines"&&u.groupBy==="folder"&&W;function ge(e){Fe(r=>{const a={...r,...e};return Mt(G,a),a})}t(ge,"updateRoutineView");function Ve(e){const r=e==="runs"?"runs":"routines";(0,l.startTransition)(()=>{b(os(r))})}t(Ve,"handleTabChange");function Y(e){x(r=>{const a=new URLSearchParams(r),v=Ct(e);return v?a.set("folder",v):a.delete("folder"),a})}t(Y,"setFolderSelection");function T(e=[]){Re(e),L(null),K(!0)}t(T,"openCreateFolder");function $e(){R(e=>({...e,folderId:f==="all"||f==="unfiled"?null:f})),z(!0)}t($e,"openCreateRoutine");async function Rs(e){const r=B;if(r.length!==0)try{await Promise.all(r.map(a=>M.moveItem(n,{kind:"routine",itemId:a,folderId:e}))),V([]),re(!1),await Promise.all([d.invalidateQueries({queryKey:m.routines.list(n)}),d.invalidateQueries({queryKey:m.folders.list(n,"routine")})]),i({title:"Routines moved",body:`${r.length} routine${r.length===1?"":"s"} filed.`,tone:"success"})}catch(a){i({title:"Failed to move routines",body:a instanceof Error?a.message:"Paperclip could not move the selected routines.",tone:"error"})}}t(Rs,"moveSelectedRoutines");function Cs(e){ie(e)}t(Cs,"handleRunNow");function Ss(e,r){if(!r&&!e.assigneeAgentId){i({title:"Default agent required",body:"Set a default agent before enabling routine automation.",tone:"warn"});return}Ke.mutate({id:e.id,status:wt(e.status,!r)})}t(Ss,"handleToggleEnabled");function _s(e){Ke.mutate({id:e.id,status:e.status==="archived"?"active":"archived"})}return t(_s,"handleToggleArchived"),n?ps?(0,s.jsx)(ct,{variant:"issues-list"}):(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[(0,s.jsxs)("div",{className:"space-y-1",children:[(0,s.jsx)("h1",{className:"text-2xl font-semibold tracking-tight",children:"Routines"}),(0,s.jsx)("p",{className:"text-sm text-muted-foreground",children:"Recurring work definitions that materialize into auditable execution tasks."})]}),(0,s.jsxs)(F,{onClick:$e,children:[(0,s.jsx)(Z,{className:"mr-2 h-4 w-4"}),"Create routine"]})]}),(0,s.jsxs)(Xs,{value:P,onValueChange:Ve,children:[(0,s.jsx)(ut,{align:"start",value:P,onValueChange:Ve,items:[{value:"routines",label:"Routines"},{value:"runs",label:"Recent Runs"}]}),(0,s.jsxs)(Je,{value:"routines",className:"space-y-4",children:[(0,s.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,s.jsxs)("p",{className:"text-sm text-muted-foreground",children:[y.length," routine",y.length===1?"":"s"]}),(0,s.jsxs)("div",{className:"flex items-center gap-1",children:[(0,s.jsxs)(es,{children:[(0,s.jsx)(Ze,{asChild:!0,children:(0,s.jsxs)(F,{variant:"ghost",size:"sm",className:"text-xs",title:"Sort",children:[(0,s.jsx)(Bs,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1"}),(0,s.jsx)("span",{className:"hidden sm:inline",children:"Sort"})]})}),(0,s.jsx)(Xe,{align:"end",className:"w-44 p-0",children:(0,s.jsx)("div",{className:"p-2 space-y-0.5",children:[["updated","Updated"],["created","Created"],["lastRun","Last run"],["title","Title"]].map(([e,r])=>(0,s.jsxs)("button",{className:`flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm ${u.sortField===e?"bg-accent/50 text-foreground":"text-muted-foreground hover:bg-accent/50"}`,onClick:t(()=>{ge(u.sortField===e?{sortDir:u.sortDir==="asc"?"desc":"asc"}:{sortField:e,sortDir:e==="title"?"asc":"desc"})},"onClick"),children:[(0,s.jsx)("span",{children:r}),u.sortField===e?(0,s.jsx)("span",{className:"text-xs text-muted-foreground",children:u.sortDir==="asc"?"Asc":"Desc"}):null]},e))})})]}),(0,s.jsxs)(es,{children:[(0,s.jsx)(Ze,{asChild:!0,children:(0,s.jsxs)(F,{variant:"ghost",size:"sm",className:"text-xs",title:"Group",children:[(0,s.jsx)(Ks,{className:"h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1"}),(0,s.jsx)("span",{className:"hidden sm:inline",children:"Group"})]})}),(0,s.jsx)(Xe,{align:"end",className:"w-44 p-0",children:(0,s.jsx)("div",{className:"p-2 space-y-0.5",children:[["folder","Folder"],["project","Project"],["assignee","Agent"],["none","None"]].map(([e,r])=>(0,s.jsxs)("button",{className:`flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm ${u.groupBy===e?"bg-accent/50 text-foreground":"text-muted-foreground hover:bg-accent/50"}`,onClick:t(()=>ge({groupBy:e,collapsedGroups:[]}),"onClick"),children:[(0,s.jsx)("span",{children:r}),u.groupBy===e?(0,s.jsx)(tt,{className:"h-3.5 w-3.5"}):null]},e))})})]}),u.groupBy==="folder"&&!W?(0,s.jsxs)(F,{variant:"outline",size:"sm",onClick:t(()=>T(),"onClick"),children:[(0,s.jsx)(Z,{className:"mr-2 h-3.5 w-3.5"}),"New folder"]}):null,fe?(0,s.jsx)(F,{variant:"ghost",size:"sm",className:"text-xs",onClick:t(()=>re(e=>!e),"onClick"),children:ne?"Done":"Select"}):null]})]}),u.groupBy==="folder"?(0,s.jsx)("div",{className:"md:hidden",children:(0,s.jsx)(xt,{result:pe,selection:f,allLabel:"All routines",onClick:t(()=>Ne(!0),"onClick")})}):null]}),(0,s.jsx)(Je,{value:"runs",children:(0,s.jsx)(Vs,{issues:le??[],isLoading:fs,error:gs,agents:C,projects:S,liveIssueIds:ws,viewStateKey:"paperclip:routine-recent-runs-view",issueLinkState:Is,onUpdateIssue:t((e,r)=>js.mutate({id:e,data:r}),"onUpdateIssue")})})]}),(0,s.jsx)(Js,{open:$,onOpenChange:t(e=>{N.isPending||z(e)},"onOpenChange"),children:(0,s.jsxs)(Hs,{showCloseButton:!1,className:"flex max-h-(--sz-calc-18) max-w-3xl flex-col gap-0 overflow-hidden p-0",children:[(0,s.jsxs)("div",{className:"shrink-0 flex flex-wrap items-center justify-between gap-3 border-b border-border/60 px-5 py-3",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"New routine"}),(0,s.jsx)("p",{className:"text-sm text-muted-foreground",children:"Define the recurring work first. Default project and agent are optional for draft routines."})]}),(0,s.jsx)(F,{variant:"ghost",size:"sm",onClick:t(()=>{z(!1),oe(!1)},"onClick"),disabled:N.isPending,children:"Cancel"})]}),(0,s.jsxs)("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[(0,s.jsx)("div",{className:"px-5 pt-5 pb-3",children:(0,s.jsx)("textarea",{ref:j,className:"w-full resize-none overflow-hidden bg-transparent text-xl font-semibold outline-none placeholder:text-muted-foreground/50",placeholder:"Routine title",rows:1,value:p.title,onChange:t(e=>{R(r=>({...r,title:e.target.value})),ss(e.target)},"onChange"),onKeyDown:t(e=>{if(e.key==="Enter"&&!e.metaKey&&!e.ctrlKey&&!e.nativeEvent.isComposing){e.preventDefault(),o.current?.focus();return}e.key==="Tab"&&!e.shiftKey&&(e.preventDefault(),p.assigneeAgentId?p.projectId?o.current?.focus():I.current?.focus():w.current?.focus())},"onKeyDown"),autoFocus:!0})}),(0,s.jsx)("div",{className:"px-5 pb-3",children:(0,s.jsx)("div",{className:"overflow-x-auto overscroll-x-contain",children:(0,s.jsxs)("div",{className:"inline-flex min-w-full flex-wrap items-center gap-2 text-sm text-muted-foreground sm:min-w-max sm:flex-nowrap",children:[(0,s.jsx)("span",{children:"For"}),(0,s.jsx)(Ye,{ref:w,value:p.assigneeAgentId,options:vs,recentOptionIds:me,placeholder:"Responsible",noneLabel:"No responsible",searchPlaceholder:"Search responsible...",emptyMessage:"No responsible found.",onChange:t(e=>{e&&zs(e),R(r=>({...r,assigneeAgentId:e}))},"onChange"),onConfirm:t(()=>{p.projectId?o.current?.focus():I.current?.focus()},"onConfirm"),renderTriggerValue:t(e=>e?Le?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(He,{agent:Le,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,s.jsx)("span",{className:"truncate",children:e.label})]}):(0,s.jsx)("span",{className:"truncate",children:e.label}):(0,s.jsx)("span",{className:"text-muted-foreground",children:"Responsible"}),"renderTriggerValue"),renderOption:t(e=>{if(!e.id)return(0,s.jsx)("span",{className:"truncate",children:e.label});const r=U.get(e.id);return(0,s.jsxs)(s.Fragment,{children:[r?(0,s.jsx)(He,{agent:r,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,(0,s.jsx)("span",{className:"truncate",children:e.label})]})},"renderOption")}),(0,s.jsx)("span",{children:"in"}),(0,s.jsx)(Ye,{ref:I,value:p.projectId,options:bs,recentOptionIds:ys,placeholder:"Project",noneLabel:"No project",searchPlaceholder:"Search projects...",emptyMessage:"No projects found.",onChange:t(e=>{e&&Qs(e),R(r=>({...r,projectId:e}))},"onChange"),onConfirm:t(()=>o.current?.focus(),"onConfirm"),renderTriggerValue:t(e=>e&&Qe?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:Qe.color??"var(--project-none)"}}),(0,s.jsx)("span",{className:"truncate",children:e.label})]}):(0,s.jsx)("span",{className:"text-muted-foreground",children:"Project"}),"renderTriggerValue"),renderOption:t(e=>{if(!e.id)return(0,s.jsx)("span",{className:"truncate",children:e.label});const r=E.get(e.id);return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:r?.color??"var(--project-none)"}}),(0,s.jsx)("span",{className:"truncate",children:e.label})]})},"renderOption")}),(0,s.jsx)("span",{children:"filed in"}),(0,s.jsxs)(we,{value:p.folderId??"__unfiled",onValueChange:t(e=>R(r=>({...r,folderId:e==="__unfiled"?null:e})),"onValueChange"),children:[(0,s.jsx)(be,{className:"h-8 w-auto min-w-32 border-0 bg-muted/50 px-2 shadow-none",children:(0,s.jsx)(ye,{})}),(0,s.jsxs)(ve,{children:[(0,s.jsx)(X,{value:"__unfiled",children:"Unfiled"}),(h?.folders??[]).map(e=>(0,s.jsx)(X,{value:e.id,children:e.name},e.id))]})]})]})})}),(0,s.jsx)("div",{className:"border-t border-border/60 px-5 py-4",children:(0,s.jsx)(Ys,{ref:o,value:p.description,onChange:t(e=>R(r=>({...r,description:e})),"onChange"),placeholder:"Add instructions...",bordered:!1,contentClassName:"min-h-(--sz-160px) text-sm text-muted-foreground",mentions:hs,onSubmit:t(()=>{!N.isPending&&p.title.trim()&&p.projectId&&p.assigneeAgentId&&N.mutate()},"onSubmit")})}),(0,s.jsx)("div",{className:"border-t border-border/60 px-5 py-3",children:(0,s.jsxs)(Ge,{open:_e,onOpenChange:oe,children:[(0,s.jsxs)(ls,{className:"flex w-full items-center justify-between text-left",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"text-sm font-medium",children:"Advanced delivery settings"}),(0,s.jsx)("p",{className:"text-sm text-muted-foreground",children:"Keep policy controls secondary to the work definition."})]}),_e?(0,s.jsx)(nt,{className:"h-4 w-4 text-muted-foreground"}):(0,s.jsx)(cs,{className:"h-4 w-4 text-muted-foreground"})]}),(0,s.jsx)(We,{className:"pt-3",children:(0,s.jsxs)("div",{className:"grid gap-4 md:grid-cols-2",children:[(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Concurrency"}),(0,s.jsxs)(we,{value:p.concurrencyPolicy,onValueChange:t(e=>R(r=>({...r,concurrencyPolicy:e})),"onValueChange"),children:[(0,s.jsx)(be,{children:(0,s.jsx)(ye,{})}),(0,s.jsx)(ve,{children:_t.map(e=>(0,s.jsx)(X,{value:e,children:e.replaceAll("_"," ")},e))})]}),(0,s.jsx)("p",{className:"text-xs text-muted-foreground",children:kt[p.concurrencyPolicy]})]}),(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Catch-up"}),(0,s.jsxs)(we,{value:p.catchUpPolicy,onValueChange:t(e=>R(r=>({...r,catchUpPolicy:e})),"onValueChange"),children:[(0,s.jsx)(be,{children:(0,s.jsx)(ye,{})}),(0,s.jsx)(ve,{children:Ft.map(e=>(0,s.jsx)(X,{value:e,children:e.replaceAll("_"," ")},e))})]}),(0,s.jsx)("p",{className:"text-xs text-muted-foreground",children:Pt[p.catchUpPolicy]})]})]})})]})})]}),(0,s.jsxs)("div",{className:"shrink-0 flex flex-col gap-3 border-t border-border/60 px-5 py-4 sm:flex-row sm:items-center sm:justify-between",children:[(0,s.jsx)("div",{className:"text-sm text-muted-foreground",children:"After creation, Paperclip takes you straight to trigger setup. Draft routines stay paused until you add a default agent."}),(0,s.jsxs)("div",{className:"flex flex-col gap-2 sm:items-end",children:[(0,s.jsxs)(F,{onClick:t(()=>N.mutate(),"onClick"),disabled:N.isPending||!p.title.trim(),children:[(0,s.jsx)(Z,{className:"mr-2 h-4 w-4"}),N.isPending?"Creating...":"Create routine"]}),N.isError?(0,s.jsx)("p",{className:"text-sm text-destructive",children:N.error instanceof Error?N.error.message:"Failed to create routine"}):null]})]})]})}),ae?(0,s.jsx)(lt,{children:(0,s.jsx)(at,{className:"pt-6 text-sm text-destructive",children:ae instanceof Error?ae.message:"Failed to load routines"})}):null,P==="routines"?(0,s.jsxs)("div",{className:Ds(fe&&"flex gap-4"),children:[fe?(0,s.jsx)(dt,{result:pe,selection:f,allLabel:"All routines",itemLabelPlural:"routines",loading:Pe,onSelect:Y,onCreate:t(()=>T(),"onCreate"),onRename:t((e,r)=>ue.mutate({folderId:e.id,payload:{name:r}}),"onRename"),onEdit:t(e=>{L(e),K(!0)},"onEdit"),onDelete:te}):null,(0,s.jsxs)("div",{className:"min-w-0 flex-1",children:[u.groupBy==="folder"&&W?(0,s.jsx)("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:f==="all"?(0,s.jsx)(Et,{label:"All routines",count:D.length}):(0,s.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,s.jsx)(jt,{color:Be?.color}),(0,s.jsx)("span",{className:"truncate font-medium",children:f==="unfiled"?"Unfiled":Be?.name??"Folder"}),(0,s.jsxs)("span",{className:"text-muted-foreground",children:[D.length," routine",D.length===1?"":"s"]})]})}):null,u.groupBy==="folder"&&!W&&!Pe&&y.length>0?(0,s.jsx)(mt,{storageKey:`paperclip:routines-folder-nudge:${n??"none"}`,itemLabelPlural:"routines",onCreateFolder:t(()=>T(),"onCreateFolder")}):null,ne?(0,s.jsx)(gt,{selectedCount:B.length,folders:h?.folders??[],onMove:t(e=>{Rs(e)},"onMove"),onCreateAndMove:t(()=>T(B),"onCreateAndMove"),onClear:t(()=>V([]),"onClear"),onDone:t(()=>{re(!1),V([])},"onDone")}):null,y.length===0?(0,s.jsx)("div",{className:"py-12",children:(0,s.jsx)(je,{icon:ee,message:"No active routines. Use Create routine to define the first recurring workflow."})}):D.length===0?(0,s.jsxs)("div",{className:"py-12",children:[(0,s.jsx)(je,{icon:ee,message:f==="all"?"No routines match this view.":"This folder is empty."}),f!=="all"?(0,s.jsx)("div",{className:"mt-3 flex justify-center",children:(0,s.jsxs)(F,{size:"sm",onClick:$e,children:[(0,s.jsx)(Z,{className:"mr-2 h-3.5 w-3.5"}),"New routine in this folder"]})}):null]}):(0,s.jsx)("div",{className:"flex flex-col gap-3",children:Ns.map(e=>{const r=!u.collapsedGroups.includes(e.key);return(0,s.jsxs)(Ge,{open:r,onOpenChange:t(a=>{ge({collapsedGroups:a?u.collapsedGroups.filter(v=>v!==e.key):[...u.collapsedGroups,e.key]})},"onOpenChange"),children:[e.label?(0,s.jsx)(Ut,{label:e.label,count:e.items.length,isOpen:r}):null,(0,s.jsx)(We,{children:e.items.map(a=>(0,s.jsx)(It,{routine:a,projectById:E,agentById:U,runningRoutineId:us,statusMutationRoutineId:ms,href:`/routines/${a.id}`,runNowButton:!0,divider:!1,onRunNow:Cs,onToggleEnabled:Ss,onToggleArchived:_s,selectMode:ne,selected:B.includes(a.id),onSelectChange:t((v,xe)=>{V(H=>xe?Array.from(new Set([...H,v.id])):H.filter(Fs=>Fs!==v.id))},"onSelectChange"),extraMenuItems:(0,s.jsx)(Nt,{folders:h?.folders??[],currentFolderId:a.folderId??null,onMove:t(v=>{const xe=a.folderId??null;qe.mutate({itemId:a.id,folderId:v}),i({title:"Routine moved",body:v?`Moved "${a.title}" to ${h?.folders.find(H=>H.id===v)?.name??"folder"}.`:`Moved "${a.title}" to Unfiled.`,tone:"success",action:{label:"Undo",onClick:t(()=>qe.mutate({itemId:a.id,folderId:xe}),"onClick")}})},"onMove"),onCreateAndMove:t(()=>T([a.id]),"onCreateAndMove")})},a.id))})]},e.key)})})]})]}):null,(0,s.jsx)(pt,{open:O,kind:"routine",folder:se,pending:De.isPending||ue.isPending,onOpenChange:K,onSubmit:t(e=>{se?ue.mutate({folderId:se.id,payload:e}):De.mutate(e)},"onSubmit")}),(0,s.jsx)(ft,{open:Q!==null,folder:Q,itemLabelPlural:"routines",pending:Te.isPending,onOpenChange:t(e=>{e||te(null)},"onOpenChange"),onConfirm:t(()=>{Q&&Te.mutate(Q.id)},"onConfirm")}),(0,s.jsx)(St,{open:ds,onOpenChange:Ne,result:pe,selection:f,allLabel:"All routines",itemLabelPlural:"Routines",onSelect:Y,onCreate:t(()=>T(),"onCreate")}),(0,s.jsx)($s,{open:k!==null,onOpenChange:t(e=>{e||ie(null)},"onOpenChange"),companyId:n,routineName:k?.title??null,agents:C??[],projects:S??[],defaultProjectId:k?.projectId??null,defaultAssigneeAgentId:k?.assigneeAgentId??null,variables:k?.variables??[],isPending:Ue.isPending,onSubmit:t(e=>{k&&Ue.mutate({id:k.id,data:e})},"onSubmit")})]}):(0,s.jsx)(je,{icon:ee,message:"Select a company to view routines."})}t(cn,"Routines");function Et({label:n,count:c}){return(0,s.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,s.jsx)(ee,{className:"h-3.5 w-3.5 text-muted-foreground"}),(0,s.jsx)("span",{className:"truncate font-medium",children:n}),(0,s.jsxs)("span",{className:"text-muted-foreground",children:[c," routine",c===1?"":"s"]})]})}t(Et,"FolderIconHeader");export{cn as Routines};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var n=(e,o)=>c(e,"name",{value:o,configurable:!0});import{zt as p}from"./index-
|
|
1
|
+
var c=Object.defineProperty;var n=(e,o)=>c(e,"name",{value:o,configurable:!0});import{zt as p}from"./index-BF7JM92C.js";import{PAPERCLIP_CHARACTER as a}from"./character-CguPM7IG.js";import{o as l,r as f}from"./model-DL5biheO.js";function b(e,o=!1){const r=p[o?"muted-dream":e.paletteId],i={...a.character,id:"paperclip-cap-v1",name:"Agent",color:r.a,color2:r.b,followCursor:!0,followRotation:!0},s=f({version:1,name:"Paperclip",characters:[i],expressions:a.expressions,animations:a.animations},i);for(const t of s.animations)t.id==="happy"&&(t.loop=!1);return s}n(b,"characterDefinition");function d(e){return e==="success"?"happy":e==="rest"?"idle":e}n(d,"animationId");function C(e,o){if(o==="rest"){const r=e.expressions.find(i=>i.id==="idle")??e.expressions[0];return{pose:{...r.beats[0].pose},blink:0,bob:0,breathe:0,expressionId:r.id,beatIndex:0,stepIndex:0,faceLayers:void 0}}return l(e,d(o),.6)}n(C,"characterStill");export{d as animationId,b as characterDefinition,C as characterStill};
|