@tickernelz/paperclip-pro-server 2026.926.4 → 2026.926.6
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/build-info.json +1 -1
- package/dist/routes/agents.d.ts.map +1 -1
- package/dist/routes/agents.js +5 -4
- package/dist/routes/agents.js.map +1 -1
- package/dist/routes/experimental-api-metadata.js +3 -3
- package/dist/routes/experimental-api-metadata.js.map +1 -1
- package/dist/routes/issues.d.ts.map +1 -1
- package/dist/routes/issues.js +8 -0
- package/dist/routes/issues.js.map +1 -1
- package/dist/routes/openapi.d.ts.map +1 -1
- package/dist/routes/openapi.js +3 -0
- package/dist/routes/openapi.js.map +1 -1
- package/dist/routes/pipelines.d.ts.map +1 -1
- package/dist/routes/pipelines.js +7 -0
- package/dist/routes/pipelines.js.map +1 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +6 -1
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/smoke-lab.js +4 -4
- package/dist/routes/smoke-lab.js.map +1 -1
- package/dist/services/environment-execution-target.d.ts +1 -0
- package/dist/services/environment-execution-target.d.ts.map +1 -1
- package/dist/services/environment-execution-target.js +9 -1
- package/dist/services/environment-execution-target.js.map +1 -1
- package/dist/services/heartbeat.d.ts.map +1 -1
- package/dist/services/heartbeat.js +7 -4
- package/dist/services/heartbeat.js.map +1 -1
- package/dist/services/instance-settings.d.ts +1 -0
- package/dist/services/instance-settings.d.ts.map +1 -1
- package/dist/services/instance-settings.js +8 -1
- package/dist/services/instance-settings.js.map +1 -1
- package/dist/services/pipelines.d.ts.map +1 -1
- package/dist/services/pipelines.js +48 -0
- package/dist/services/pipelines.js.map +1 -1
- package/dist/services/smoke-lab.d.ts.map +1 -1
- package/dist/services/smoke-lab.js +12 -1
- package/dist/services/smoke-lab.js.map +1 -1
- package/package.json +20 -20
- package/ui-dist/assets/{Agents.production-DYgcR2ZQ.js → Agents.production-DVAeGpcj.js} +2 -2
- package/ui-dist/assets/{CompanyActivity.production-MiS7fCCl.js → CompanyActivity.production-CfhZMRXj.js} +1 -1
- package/ui-dist/assets/{CompanyExport-C-7PQaz8.js → CompanyExport-gwDWvzqx.js} +1 -1
- package/ui-dist/assets/{CompanySkills.production-D3xms9bg.js → CompanySkills.production-BT_6NNEX.js} +1 -1
- package/ui-dist/assets/{Costs.production-DdIIwVUT.js → Costs.production-rBVKz6XI.js} +1 -1
- package/ui-dist/assets/{OrgChart.production-hVW6TgEL.js → OrgChart.production-BUvWpHy6.js} +1 -1
- package/ui-dist/assets/{RoutineDetail.production-MBJ3aeg2.js → RoutineDetail.production-DOdpoBuO.js} +1 -1
- package/ui-dist/assets/{Routines.production-LQRGr5dX.js → Routines.production-DaUtfMFw.js} +1 -1
- package/ui-dist/assets/{definition-INtTKxdn.js → definition-6XjQ-LsW.js} +1 -1
- package/ui-dist/assets/{index-DbWxivZc.js → index-Cf2CHzHP.js} +97 -97
- package/ui-dist/index.html +1 -1
- package/ui-dist/sw.js +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var ot=Object.defineProperty;var o=(i,h)=>ot(i,"name",{value:h,configurable:!0});import{i as Re}from"./rolldown-runtime-ZpX3ckPj.js";import{Fr as dt,L as J,Lr as lt,M,Pr as ct,S as Ie,T as m,U as ut,Y as v,nr as S,tr as qe,x as mt}from"./createLucideIcon-CZEG6UJ7.js";import{i as O,n as B,r as pt,t as te}from"./tabs-D8G3-AL7.js";import{r as gt,t as xt}from"./EmptyState-DeVTy8IU.js";import{t as ht}from"./chevron-down-CpKmud_n.js";import{t as bt}from"./chevron-right-IZydUoW5.js";import{t as vt}from"./button-LkWt40cm.js";import{t as yt}from"./AgentIdentity-CV55DQtR.js";import{i as R,o as $,r as F,s as L,t as q}from"./card-DbvoJZ3K.js";import{t as se}from"./PageSkeleton-DRRnaWWU.js";import{$t as De,C as jt,D as N,E as Ae,Fn as ne,Gt as ft,Hn as re,In as ie,S as Fe,T as Ee,Wn as Nt,_t as ae,b as Ct,gt as wt,v as Tt,w as kt,x as Ke,xn as oe,y as St}from"./index-DbWxivZc.js";var l=Re(lt(),1),e=Re(dt(),1),Bt="__none__";function Mt(){const i=new Date,h=i.getDay(),y=h===0?-6:1-h,u=new Date(i.getFullYear(),i.getMonth(),i.getDate()+y,0,0,0,0),j=new Date(u.getFullYear(),u.getMonth(),u.getDate()+6,23,59,59,999);return{from:u.toISOString(),to:j.toISOString()}}o(Mt,"currentWeekRange");function Pt({provider:i,rows:h}){const y=h.reduce((j,b)=>j+b.inputTokens+b.cachedInputTokens+b.outputTokens,0),u=h.reduce((j,b)=>j+b.costCents,0);return(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:J(i)}),(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(y)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(u)})]})}o(Pt,"ProviderTabLabel");function It({biller:i,rows:h}){const y=h.reduce((j,b)=>j+b.inputTokens+b.cachedInputTokens+b.outputTokens,0),u=h.reduce((j,b)=>j+b.costCents,0);return(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:J(i)}),(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(y)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(u)})]})}o(It,"BillerTabLabel");function C({label:i,value:h,subtitle:y,icon:u}){return(0,e.jsx)(q,{className:"block p-4",children:(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground",children:i}),(0,e.jsx)("div",{className:"mt-2 text-2xl font-semibold tabular-nums",children:h}),(0,e.jsx)("div",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:y})]}),(0,e.jsx)("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-border",children:(0,e.jsx)(u,{className:"h-4 w-4 text-muted-foreground"})})]})})}o(C,"MetricTile");function _e({debitCents:i,creditCents:h,netCents:y,estimatedDebitCents:u,eventCount:j}){return(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"Finance ledger"}),(0,e.jsx)(R,{children:"Account-level charges that do not map to a single inference request."})]}),(0,e.jsxs)(F,{className:"grid gap-3 px-5 pb-5 pt-2 sm:grid-cols-2 xl:grid-cols-4",children:[(0,e.jsx)(C,{label:"Debits",value:m(i),subtitle:`${j} total event${j===1?"":"s"} in range`,icon:re}),(0,e.jsx)(C,{label:"Credits",value:m(h),subtitle:"Refunds, offsets, and credit returns",icon:Nt}),(0,e.jsx)(C,{label:"Net",value:m(y),subtitle:"Debit minus credit for the selected period",icon:oe}),(0,e.jsx)(C,{label:"Estimated",value:m(u),subtitle:"Estimated debits that are not yet invoice-authoritative",icon:ie})]})]})}o(_e,"FinanceSummaryCard");function Ot(){const{selectedCompanyId:i}=ut(),{setBreadcrumbs:h}=gt(),y=ct(),[u,j]=(0,l.useState)("overview"),[b,de]=(0,l.useState)("all"),[W,le]=(0,l.useState)("all"),{preset:E,setPreset:$e,customFrom:Le,setCustomFrom:We,customTo:ze,setCustomTo:Oe,from:g,to:x,customReady:D}=Ct();(0,l.useEffect)(()=>{h([{label:"Costs"}])},[h]);const[Qe,Ye]=(0,l.useState)(()=>new Date().toDateString()),X=(0,l.useRef)(null);(0,l.useEffect)(()=>{const t=o(()=>{const s=new Date,n=new Date(s.getFullYear(),s.getMonth(),s.getDate()+1).getTime()-s.getTime();X.current=setTimeout(()=>{Ye(new Date().toDateString()),t()},n)},"schedule");return t(),()=>{X.current!=null&&clearTimeout(X.current)}},[]);const P=(0,l.useMemo)(()=>Mt(),[Qe]),d=i??Bt,{data:A,isLoading:Ue,error:ce}=S({queryKey:v.budgets.overview(d),queryFn:o(()=>ae.overview(d),"queryFn"),enabled:!!i&&D,refetchInterval:3e4,staleTime:5e3}),ue=o(()=>{i&&(y.invalidateQueries({queryKey:v.budgets.overview(i)}),y.invalidateQueries({queryKey:v.dashboard(i)}),y.invalidateQueries({queryKey:v.agents.list(i)}),y.invalidateQueries({queryKey:v.projects.all(i)}))},"invalidateBudgetViews"),me=qe({mutationFn:o(t=>ae.upsertPolicy(d,{scopeType:t.scopeType,scopeId:t.scopeId,amount:t.amount,windowKind:t.windowKind}),"mutationFn"),onSuccess:ue}),K=qe({mutationFn:o(t=>ae.resolveIncident(d,t.incidentId,t),"mutationFn"),onSuccess:ue}),{data:a,isLoading:Ve,error:He}=S({queryKey:v.costs(d,g||void 0,x||void 0),queryFn:o(async()=>{const[t,s,n,r]=await Promise.all([N.summary(d,g||void 0,x||void 0),N.byAgent(d,g||void 0,x||void 0),N.byProject(d,g||void 0,x||void 0),N.byAgentModel(d,g||void 0,x||void 0)]);return{summary:t,byAgent:s,byProject:n,byAgentModel:r}},"queryFn"),enabled:!!i&&D}),{data:p,isLoading:pe,error:Z}=S({queryKey:[v.financeSummary(d,g||void 0,x||void 0),v.financeByBiller(d,g||void 0,x||void 0),v.financeByKind(d,g||void 0,x||void 0),v.financeEvents(d,g||void 0,x||void 0,18)],queryFn:o(async()=>{const[t,s,n,r]=await Promise.all([N.financeSummary(d,g||void 0,x||void 0),N.financeByBiller(d,g||void 0,x||void 0),N.financeByKind(d,g||void 0,x||void 0),N.financeEvents(d,g||void 0,x||void 0,18)]);return{summary:t,byBiller:s,byKind:n,events:r}},"queryFn"),enabled:!!i&&D}),[Ge,ge]=(0,l.useState)(new Set);(0,l.useEffect)(()=>{ge(new Set)},[d,g,x]);function Je(t){ge(s=>{const n=new Set(s);return n.has(t)?n.delete(t):n.add(t),n})}o(Je,"toggleAgent");const Xe=(0,l.useMemo)(()=>{const t=new Map;for(const s of a?.byAgentModel??[]){const n=t.get(s.agentId)??[];n.push(s),t.set(s.agentId,n)}for(const[s,n]of t)t.set(s,n.slice().sort((r,c)=>c.costCents-r.costCents));return t},[a?.byAgentModel]),{data:Q}=S({queryKey:v.usageByProvider(d,g||void 0,x||void 0),queryFn:o(()=>N.byProvider(d,g||void 0,x||void 0),"queryFn"),enabled:!!i&&D&&(u==="providers"||u==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:xe}=S({queryKey:v.usageByBiller(d,g||void 0,x||void 0),queryFn:o(()=>N.byBiller(d,g||void 0,x||void 0),"queryFn"),enabled:!!i&&D&&u==="billers",refetchInterval:3e4,staleTime:1e4}),{data:he}=S({queryKey:v.usageByProvider(d,P.from,P.to),queryFn:o(()=>N.byProvider(d,P.from,P.to),"queryFn"),enabled:!!i&&(u==="providers"||u==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:be}=S({queryKey:v.usageByBiller(d,P.from,P.to),queryFn:o(()=>N.byBiller(d,P.from,P.to),"queryFn"),enabled:!!i&&u==="billers",refetchInterval:3e4,staleTime:1e4}),{data:ve}=S({queryKey:v.usageWindowSpend(d),queryFn:o(()=>N.windowSpend(d),"queryFn"),enabled:!!i&&u==="providers",refetchInterval:3e4,staleTime:1e4}),{data:_,isLoading:ye}=S({queryKey:v.usageQuotaWindows(d),queryFn:o(()=>N.quotaWindows(d),"queryFn"),enabled:!!i&&u==="providers",refetchInterval:3e5,staleTime:6e4}),w=(0,l.useMemo)(()=>{const t=new Map;for(const s of Q??[]){const n=t.get(s.provider)??[];n.push(s),t.set(s.provider,n)}return t},[Q]),k=(0,l.useMemo)(()=>{const t=new Map;for(const s of xe??[]){const n=t.get(s.biller)??[];n.push(s),t.set(s.biller,n)}return t},[xe]),je=(0,l.useMemo)(()=>{const t=new Map;for(const s of he??[])t.set(s.provider,(t.get(s.provider)??0)+s.costCents);return t},[he]),fe=(0,l.useMemo)(()=>{const t=new Map;for(const s of be??[])t.set(s.biller,(t.get(s.biller)??0)+s.costCents);return t},[be]),Ne=(0,l.useMemo)(()=>{const t=new Map;for(const s of ve??[]){const n=t.get(s.provider)??[];n.push(s),t.set(s.provider,n)}return t},[ve]),Ce=(0,l.useMemo)(()=>{const t=new Map;for(const s of _??[])s.ok&&s.windows.length>0&&t.set(s.provider,s.windows);return t},[_]),we=(0,l.useMemo)(()=>{const t=new Map;for(const s of _??[])!s.ok&&s.error&&t.set(s.provider,s.error);return t},[_]),Te=(0,l.useMemo)(()=>{const t=new Map;for(const s of _??[])typeof s.source=="string"&&s.source.length>0&&t.set(s.provider,s.source);return t},[_]),ke=(0,l.useMemo)(()=>{const t=new Map;if(E!=="mtd")return t;const s=a?.summary.budgetCents??0;if(s<=0)return t;const n=a?.summary.spendCents??0,r=new Date,c=r.getDate(),T=new Date(r.getFullYear(),r.getMonth()+1,0).getDate();for(const[f,nt]of w){const ee=nt.reduce((rt,it)=>rt+it.costCents,0),Pe=s*(n>0?ee/n:0);if(Pe<=0){t.set(f,!1);continue}const at=ee/Math.max(c,1);t.set(f,ee+at*(T-c)>Pe)}return t},[E,a,w]),Y=(0,l.useMemo)(()=>Array.from(w.keys()),[w]),U=(0,l.useMemo)(()=>Array.from(k.keys()),[k]),V=b==="all"||Y.includes(b)?b:"all";(0,l.useEffect)(()=>{V!==b&&de("all")},[V,b]);const H=W==="all"||U.includes(W)?W:"all";(0,l.useEffect)(()=>{H!==W&&le("all")},[H,W]);const Ze=(0,l.useMemo)(()=>{const t=Array.from(w.keys()),s=t.reduce((r,c)=>r+(w.get(c)?.reduce((T,f)=>T+f.inputTokens+f.cachedInputTokens+f.outputTokens,0)??0),0),n=t.reduce((r,c)=>r+(w.get(c)?.reduce((T,f)=>T+f.costCents,0)??0),0);return[{value:"all",label:(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:"All providers"}),t.length>0?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(s)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(n)})]}):null]})},...t.map(r=>({value:r,label:(0,e.jsx)(Pt,{provider:r,rows:w.get(r)??[]})}))]},[w]),et=(0,l.useMemo)(()=>{const t=Array.from(k.keys()),s=t.reduce((r,c)=>r+(k.get(c)?.reduce((T,f)=>T+f.inputTokens+f.cachedInputTokens+f.outputTokens,0)??0),0),n=t.reduce((r,c)=>r+(k.get(c)?.reduce((T,f)=>T+f.costCents,0)??0),0);return[{value:"all",label:(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:"All billers"}),t.length>0?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(s)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(n)})]}):null]})},...t.map(r=>({value:r,label:(0,e.jsx)(It,{biller:r,rows:k.get(r)??[]})}))]},[k]),Se=(a?.byAgent??[]).reduce((t,s)=>t+s.inputTokens+s.cachedInputTokens+s.outputTokens,0),Be=p?.events??[],z=A?.policies??[],I=A?.activeIncidents??[],tt=(0,l.useMemo)(()=>({company:z.filter(t=>t.scopeType==="company"),agent:z.filter(t=>t.scopeType==="agent"),project:z.filter(t=>t.scopeType==="project")}),[z]);if(!i)return(0,e.jsx)(xt,{icon:ne,message:"Select a company to view costs."});const G=E==="custom"&&!D,st=(Ve||pe)&&D,Me=He??Z;return(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsxs)("div",{className:"space-y-5",children:[(0,e.jsxs)("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h1",{className:"text-3xl font-semibold tracking-tight",children:"Costs"}),(0,e.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted-foreground",children:"Inference spend, platform fees, credits, and live quota windows."})]}),(0,e.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:Tt.map(t=>(0,e.jsx)(vt,{variant:E===t?"secondary":"ghost",size:"sm",onClick:o(()=>$e(t),"onClick"),"aria-pressed":E===t,children:St[t]},t))})]}),E==="custom"?(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2 border border-border p-3",children:[(0,e.jsx)("input",{type:"date",value:Le,onChange:o(t=>We(t.target.value),"onChange"),className:"h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"}),(0,e.jsx)("span",{className:"text-sm text-muted-foreground",children:"to"}),(0,e.jsx)("input",{type:"date",value:ze,onChange:o(t=>Oe(t.target.value),"onChange"),className:"h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"})]}):null,(0,e.jsxs)("div",{className:"grid gap-3 lg:grid-cols-4",children:[(0,e.jsx)(C,{label:"Inference spend",value:m(a?.summary.spendCents??0),subtitle:`${M(Se)} tokens across request-scoped events`,icon:ne}),(0,e.jsx)(C,{label:"Budget",value:I.length>0?String(I.length):a?.summary.budgetCents&&a.summary.budgetCents>0?`${a.summary.utilizationPercent}%`:"Open",subtitle:I.length>0?`${A?.pausedAgentCount??0} agents paused · ${A?.pausedProjectCount??0} projects paused`:a?.summary.budgetCents&&a.summary.budgetCents>0?`${m(a.summary.spendCents)} of ${m(a.summary.budgetCents)}`:"No monthly cap configured",icon:ie}),(0,e.jsx)(C,{label:"Finance net",value:m(p?.summary.netCents??0),subtitle:`${m(p?.summary.debitCents??0)} debits · ${m(p?.summary.creditCents??0)} credits`,icon:oe}),(0,e.jsx)(C,{label:"Finance events",value:String(p?.summary.eventCount??0),subtitle:`${m(p?.summary.estimatedDebitCents??0)} estimated in range`,icon:re})]})]}),(0,e.jsxs)(te,{value:u,onValueChange:o(t=>j(t),"onValueChange"),children:[(0,e.jsxs)(pt,{variant:"line",className:"justify-start",children:[(0,e.jsx)(O,{value:"overview",children:"Overview"}),(0,e.jsx)(O,{value:"budgets",children:"Budgets"}),(0,e.jsx)(O,{value:"providers",children:"Providers"}),(0,e.jsx)(O,{value:"billers",children:"Billers"}),(0,e.jsx)(O,{value:"finance",children:"Finance"})]}),(0,e.jsx)(B,{value:"overview",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):st?(0,e.jsx)(se,{variant:"costs"}):Me?(0,e.jsx)("p",{className:"text-sm text-destructive",children:Me.message}):(0,e.jsxs)(e.Fragment,{children:[I.length>0?(0,e.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:I.slice(0,2).map(t=>(0,e.jsx)(Ee,{incident:t,isMutating:K.isPending,onKeepPaused:o(()=>K.mutate({incidentId:t.id,action:"keep_paused"}),"onKeepPaused"),onRaiseAndResume:o(s=>K.mutate({incidentId:t.id,action:"raise_budget_and_resume",amount:s}),"onRaiseAndResume")},t.id))}):null,(0,e.jsxs)("div",{className:"grid gap-4 xl:grid-cols-(--gtc-31)",children:[(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"Inference ledger"}),(0,e.jsx)(R,{children:"Request-scoped inference spend for the selected period."})]}),(0,e.jsxs)(F,{className:"space-y-4 px-5 pb-5 pt-2",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("div",{className:"text-3xl font-semibold tabular-nums",children:m(a?.summary.spendCents??0)}),(0,e.jsx)("div",{className:"mt-1 text-sm text-muted-foreground",children:a?.summary.budgetCents&&a.summary.budgetCents>0?`Budget ${m(a.summary.budgetCents)}`:"Unlimited budget"})]}),(0,e.jsxs)("div",{className:"border border-border px-4 py-3 text-right",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground",children:"usage"}),(0,e.jsx)("div",{className:"mt-1 text-lg font-medium tabular-nums",children:M(Se)})]})]}),a?.summary.budgetCents&&a.summary.budgetCents>0?(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("div",{className:"h-2 overflow-hidden bg-muted",children:(0,e.jsx)("div",{className:Ie("h-full transition-(--tp-width-background-color) duration-150",a.summary.utilizationPercent>90?"bg-(--status-task-blocked)":a.summary.utilizationPercent>70?"bg-(--status-task-todo)":"bg-(--status-task-done)"),style:{width:`${Math.min(100,a.summary.utilizationPercent)}%`}})}),(0,e.jsxs)("div",{className:"text-xs text-muted-foreground",children:[a.summary.utilizationPercent,"% of monthly budget consumed in this range."]})]}):null]})]}),(0,e.jsx)(_e,{debitCents:p?.summary.debitCents??0,creditCents:p?.summary.creditCents??0,netCents:p?.summary.netCents??0,estimatedDebitCents:p?.summary.estimatedDebitCents??0,eventCount:p?.summary.eventCount??0})]}),(0,e.jsxs)("div",{className:"grid gap-4 xl:grid-cols-(--gtc-32)",children:[(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"By agent"}),(0,e.jsx)(R,{children:"What each agent consumed in the selected period."})]}),(0,e.jsx)(F,{className:"space-y-2 px-5 pb-5 pt-2",children:(a?.byAgent.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No cost events yet."}):a?.byAgent.map(t=>{const s=Xe.get(t.agentId)??[],n=Ge.has(t.agentId),r=s.length>0;return(0,e.jsxs)("div",{className:"border border-border px-4 py-3",children:[(0,e.jsxs)("div",{className:Ie("flex items-start justify-between gap-3",r?"cursor-pointer select-none":""),onClick:o(()=>r&&Je(t.agentId),"onClick"),children:[(0,e.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[r?n?(0,e.jsx)(ht,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):(0,e.jsx)(bt,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):(0,e.jsx)("span",{className:"h-3 w-3 shrink-0"}),(0,e.jsx)(yt,{agent:{id:t.agentId,name:t.agentName??t.agentId,appearance:t.agentAppearance},size:"sm"}),t.agentStatus==="terminated"?(0,e.jsx)(ft,{status:"terminated"}):null]}),(0,e.jsxs)("div",{className:"text-right text-sm tabular-nums",children:[(0,e.jsx)("div",{className:"font-medium",children:m(t.costCents)}),(0,e.jsxs)("div",{className:"text-xs text-muted-foreground",children:["in ",M(t.inputTokens+t.cachedInputTokens)," · out ",M(t.outputTokens)]}),t.apiRunCount>0||t.subscriptionRunCount>0?(0,e.jsxs)("div",{className:"text-xs text-muted-foreground",children:[t.apiRunCount>0?`${t.apiRunCount} api`:"0 api"," · ",t.subscriptionRunCount>0?`${t.subscriptionRunCount} subscription`:"0 subscription"]}):null]})]}),n&&s.length>0?(0,e.jsx)("div",{className:"mt-3 space-y-2 border-l border-border pl-4",children:s.map(c=>{const T=t.costCents>0?Math.round(c.costCents/t.costCents*100):0;return(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3 text-xs",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsxs)("div",{className:"truncate font-medium text-foreground",children:[J(c.provider),(0,e.jsx)("span",{className:"mx-1 text-border",children:"/"}),(0,e.jsx)("span",{className:"font-mono",children:c.model})]}),(0,e.jsxs)("div",{className:"truncate text-muted-foreground",children:[J(c.biller)," · ",mt(c.billingType)]})]}),(0,e.jsxs)("div",{className:"text-right tabular-nums",children:[(0,e.jsxs)("div",{className:"font-medium",children:[m(c.costCents),(0,e.jsxs)("span",{className:"ml-1 font-normal text-muted-foreground",children:["(",T,"%)"]})]}),(0,e.jsxs)("div",{className:"text-muted-foreground",children:[M(c.inputTokens+c.cachedInputTokens+c.outputTokens)," tok"]})]})]},`${c.provider}:${c.model}:${c.billingType}`)})}):null]},t.agentId)})})]}),(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"By project"}),(0,e.jsx)(R,{children:"Run costs attributed through project-linked tasks."})]}),(0,e.jsx)(F,{className:"space-y-2 px-5 pb-5 pt-2",children:(a?.byProject.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No project-attributed run costs yet."}):a?.byProject.map((t,s)=>(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3 border border-border px-3 py-2 text-sm",children:[(0,e.jsx)("span",{className:"truncate",children:t.projectName??t.projectId??"Unattributed"}),(0,e.jsx)("span",{className:"font-medium tabular-nums",children:m(t.costCents)})]},t.projectId??`unattributed-${s}`))})]}),(0,e.jsx)(Fe,{rows:Be.slice(0,6),emptyMessage:"No finance events yet. Add account-level charges once biller invoices or credits land."})]})]})]})}),(0,e.jsx)(B,{value:"budgets",className:"mt-4 space-y-4",children:Ue?(0,e.jsx)(se,{variant:"costs"}):ce?(0,e.jsx)("p",{className:"text-sm text-destructive",children:ce.message}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(q,{className:"border-border/70 bg-(image:--gradient-extract-2)",children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-3",children:[(0,e.jsx)(L,{className:"text-base",children:"Budget control plane"}),(0,e.jsx)(R,{children:"Hard-stop spend limits for agents and projects. Provider subscription quota stays separate and appears under Providers."})]}),(0,e.jsxs)(F,{className:"grid gap-3 px-5 pb-5 pt-0 md:grid-cols-4",children:[(0,e.jsx)(C,{label:"Active incidents",value:String(I.length),subtitle:"Open soft or hard threshold crossings",icon:oe}),(0,e.jsx)(C,{label:"Pending approvals",value:String(A?.pendingApprovalCount??0),subtitle:"Budget override approvals awaiting board action",icon:re}),(0,e.jsx)(C,{label:"Paused agents",value:String(A?.pausedAgentCount??0),subtitle:"Agent heartbeats blocked by budget",icon:ie}),(0,e.jsx)(C,{label:"Paused projects",value:String(A?.pausedProjectCount??0),subtitle:"Project execution blocked by budget",icon:ne})]})]}),I.length>0?(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h2",{className:"text-lg font-semibold",children:"Active incidents"}),(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Resolve hard stops here by raising the budget or explicitly keeping the scope paused."})]}),(0,e.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:I.map(t=>(0,e.jsx)(Ee,{incident:t,isMutating:K.isPending,onKeepPaused:o(()=>K.mutate({incidentId:t.id,action:"keep_paused"}),"onKeepPaused"),onRaiseAndResume:o(s=>K.mutate({incidentId:t.id,action:"raise_budget_and_resume",amount:s}),"onRaiseAndResume")},t.id))})]}):null,(0,e.jsxs)("div",{className:"space-y-5",children:[["company","agent","project"].map(t=>{const s=tt[t];return s.length===0?null:(0,e.jsxs)("section",{className:"space-y-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsxs)("h2",{className:"text-lg font-semibold capitalize",children:[t," budgets"]}),(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:t==="company"?"Company-wide monthly policy.":t==="agent"?"Recurring monthly spend policies for individual agents.":"Lifetime spend policies for execution-bound projects."})]}),(0,e.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:s.map(n=>(0,e.jsx)(wt,{summary:n,isSaving:me.isPending,onSave:o(r=>me.mutate({scopeType:n.scopeType,scopeId:n.scopeId,amount:r,windowKind:n.windowKind}),"onSave")},n.policyId))})]},t)}),z.length===0?(0,e.jsx)(q,{children:(0,e.jsx)(F,{className:"px-5 py-8 text-sm text-muted-foreground",children:"No budget policies yet. Set agent and project budgets from their detail pages, or use the existing company monthly budget control."})}):null]})]})}),(0,e.jsx)(B,{value:"providers",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):(0,e.jsx)(e.Fragment,{children:(0,e.jsxs)(te,{value:V,onValueChange:de,children:[(0,e.jsx)(De,{items:Ze,value:V}),(0,e.jsx)(B,{value:"all",className:"mt-4",children:Y.length===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No cost events in this period."}):(0,e.jsx)("div",{className:"grid gap-4 md:grid-cols-2",children:Y.map(t=>(0,e.jsx)(Ke,{provider:t,rows:w.get(t)??[],budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,weekSpendCents:je.get(t)??0,windowRows:Ne.get(t)??[],showDeficitNotch:ke.get(t)??!1,quotaWindows:Ce.get(t)??[],quotaError:we.get(t)??null,quotaSource:Te.get(t)??null,quotaLoading:ye},t))})}),Y.map(t=>(0,e.jsx)(B,{value:t,className:"mt-4",children:(0,e.jsx)(Ke,{provider:t,rows:w.get(t)??[],budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,weekSpendCents:je.get(t)??0,windowRows:Ne.get(t)??[],showDeficitNotch:ke.get(t)??!1,quotaWindows:Ce.get(t)??[],quotaError:we.get(t)??null,quotaSource:Te.get(t)??null,quotaLoading:ye})},t))]})})}),(0,e.jsx)(B,{value:"billers",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):(0,e.jsx)(e.Fragment,{children:(0,e.jsxs)(te,{value:H,onValueChange:le,children:[(0,e.jsx)(De,{items:et,value:H}),(0,e.jsx)(B,{value:"all",className:"mt-4",children:U.length===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No billable events in this period."}):(0,e.jsx)("div",{className:"grid gap-4 md:grid-cols-2",children:U.map(t=>{const s=(k.get(t)??[])[0];if(!s)return null;const n=(Q??[]).filter(r=>r.biller===t);return(0,e.jsx)(Ae,{row:s,weekSpendCents:fe.get(t)??0,budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,providerRows:n},t)})})}),U.map(t=>{const s=(k.get(t)??[])[0];if(!s)return null;const n=(Q??[]).filter(r=>r.biller===t);return(0,e.jsx)(B,{value:t,className:"mt-4",children:(0,e.jsx)(Ae,{row:s,weekSpendCents:fe.get(t)??0,budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,providerRows:n})},t)})]})})}),(0,e.jsx)(B,{value:"finance",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):pe?(0,e.jsx)(se,{variant:"costs"}):Z?(0,e.jsx)("p",{className:"text-sm text-destructive",children:Z.message}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(_e,{debitCents:p?.summary.debitCents??0,creditCents:p?.summary.creditCents??0,netCents:p?.summary.netCents??0,estimatedDebitCents:p?.summary.estimatedDebitCents??0,eventCount:p?.summary.eventCount??0}),(0,e.jsxs)("div",{className:"grid gap-4 xl:grid-cols-(--gtc-33)",children:[(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"By biller"}),(0,e.jsx)(R,{children:"Account-level financial events grouped by who charged or credited them."})]}),(0,e.jsx)(F,{className:"grid gap-4 px-5 pb-5 pt-2 md:grid-cols-2",children:(p?.byBiller.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No finance events yet."}):p?.byBiller.map(t=>(0,e.jsx)(kt,{row:t},t.biller))})]}),(0,e.jsx)(Fe,{rows:Be})]}),(0,e.jsx)(jt,{rows:p?.byKind??[]})]})]})})]})]})}o(Ot,"Costs");export{Ot as Costs};
|
|
1
|
+
var ot=Object.defineProperty;var o=(i,h)=>ot(i,"name",{value:h,configurable:!0});import{i as Re}from"./rolldown-runtime-ZpX3ckPj.js";import{Fr as dt,L as J,Lr as lt,M,Pr as ct,S as Ie,T as m,U as ut,Y as v,nr as S,tr as qe,x as mt}from"./createLucideIcon-CZEG6UJ7.js";import{i as O,n as B,r as pt,t as te}from"./tabs-D8G3-AL7.js";import{r as gt,t as xt}from"./EmptyState-DeVTy8IU.js";import{t as ht}from"./chevron-down-CpKmud_n.js";import{t as bt}from"./chevron-right-IZydUoW5.js";import{t as vt}from"./button-LkWt40cm.js";import{t as yt}from"./AgentIdentity-CV55DQtR.js";import{i as R,o as $,r as F,s as L,t as q}from"./card-DbvoJZ3K.js";import{t as se}from"./PageSkeleton-DRRnaWWU.js";import{$t as De,C as jt,D as N,E as Ae,Fn as ne,Gt as ft,Hn as re,In as ie,S as Fe,T as Ee,Wn as Nt,_t as ae,b as Ct,gt as wt,v as Tt,w as kt,x as Ke,xn as oe,y as St}from"./index-Cf2CHzHP.js";var l=Re(lt(),1),e=Re(dt(),1),Bt="__none__";function Mt(){const i=new Date,h=i.getDay(),y=h===0?-6:1-h,u=new Date(i.getFullYear(),i.getMonth(),i.getDate()+y,0,0,0,0),j=new Date(u.getFullYear(),u.getMonth(),u.getDate()+6,23,59,59,999);return{from:u.toISOString(),to:j.toISOString()}}o(Mt,"currentWeekRange");function Pt({provider:i,rows:h}){const y=h.reduce((j,b)=>j+b.inputTokens+b.cachedInputTokens+b.outputTokens,0),u=h.reduce((j,b)=>j+b.costCents,0);return(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:J(i)}),(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(y)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(u)})]})}o(Pt,"ProviderTabLabel");function It({biller:i,rows:h}){const y=h.reduce((j,b)=>j+b.inputTokens+b.cachedInputTokens+b.outputTokens,0),u=h.reduce((j,b)=>j+b.costCents,0);return(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:J(i)}),(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(y)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(u)})]})}o(It,"BillerTabLabel");function C({label:i,value:h,subtitle:y,icon:u}){return(0,e.jsx)(q,{className:"block p-4",children:(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground",children:i}),(0,e.jsx)("div",{className:"mt-2 text-2xl font-semibold tabular-nums",children:h}),(0,e.jsx)("div",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:y})]}),(0,e.jsx)("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-border",children:(0,e.jsx)(u,{className:"h-4 w-4 text-muted-foreground"})})]})})}o(C,"MetricTile");function _e({debitCents:i,creditCents:h,netCents:y,estimatedDebitCents:u,eventCount:j}){return(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"Finance ledger"}),(0,e.jsx)(R,{children:"Account-level charges that do not map to a single inference request."})]}),(0,e.jsxs)(F,{className:"grid gap-3 px-5 pb-5 pt-2 sm:grid-cols-2 xl:grid-cols-4",children:[(0,e.jsx)(C,{label:"Debits",value:m(i),subtitle:`${j} total event${j===1?"":"s"} in range`,icon:re}),(0,e.jsx)(C,{label:"Credits",value:m(h),subtitle:"Refunds, offsets, and credit returns",icon:Nt}),(0,e.jsx)(C,{label:"Net",value:m(y),subtitle:"Debit minus credit for the selected period",icon:oe}),(0,e.jsx)(C,{label:"Estimated",value:m(u),subtitle:"Estimated debits that are not yet invoice-authoritative",icon:ie})]})]})}o(_e,"FinanceSummaryCard");function Ot(){const{selectedCompanyId:i}=ut(),{setBreadcrumbs:h}=gt(),y=ct(),[u,j]=(0,l.useState)("overview"),[b,de]=(0,l.useState)("all"),[W,le]=(0,l.useState)("all"),{preset:E,setPreset:$e,customFrom:Le,setCustomFrom:We,customTo:ze,setCustomTo:Oe,from:g,to:x,customReady:D}=Ct();(0,l.useEffect)(()=>{h([{label:"Costs"}])},[h]);const[Qe,Ye]=(0,l.useState)(()=>new Date().toDateString()),X=(0,l.useRef)(null);(0,l.useEffect)(()=>{const t=o(()=>{const s=new Date,n=new Date(s.getFullYear(),s.getMonth(),s.getDate()+1).getTime()-s.getTime();X.current=setTimeout(()=>{Ye(new Date().toDateString()),t()},n)},"schedule");return t(),()=>{X.current!=null&&clearTimeout(X.current)}},[]);const P=(0,l.useMemo)(()=>Mt(),[Qe]),d=i??Bt,{data:A,isLoading:Ue,error:ce}=S({queryKey:v.budgets.overview(d),queryFn:o(()=>ae.overview(d),"queryFn"),enabled:!!i&&D,refetchInterval:3e4,staleTime:5e3}),ue=o(()=>{i&&(y.invalidateQueries({queryKey:v.budgets.overview(i)}),y.invalidateQueries({queryKey:v.dashboard(i)}),y.invalidateQueries({queryKey:v.agents.list(i)}),y.invalidateQueries({queryKey:v.projects.all(i)}))},"invalidateBudgetViews"),me=qe({mutationFn:o(t=>ae.upsertPolicy(d,{scopeType:t.scopeType,scopeId:t.scopeId,amount:t.amount,windowKind:t.windowKind}),"mutationFn"),onSuccess:ue}),K=qe({mutationFn:o(t=>ae.resolveIncident(d,t.incidentId,t),"mutationFn"),onSuccess:ue}),{data:a,isLoading:Ve,error:He}=S({queryKey:v.costs(d,g||void 0,x||void 0),queryFn:o(async()=>{const[t,s,n,r]=await Promise.all([N.summary(d,g||void 0,x||void 0),N.byAgent(d,g||void 0,x||void 0),N.byProject(d,g||void 0,x||void 0),N.byAgentModel(d,g||void 0,x||void 0)]);return{summary:t,byAgent:s,byProject:n,byAgentModel:r}},"queryFn"),enabled:!!i&&D}),{data:p,isLoading:pe,error:Z}=S({queryKey:[v.financeSummary(d,g||void 0,x||void 0),v.financeByBiller(d,g||void 0,x||void 0),v.financeByKind(d,g||void 0,x||void 0),v.financeEvents(d,g||void 0,x||void 0,18)],queryFn:o(async()=>{const[t,s,n,r]=await Promise.all([N.financeSummary(d,g||void 0,x||void 0),N.financeByBiller(d,g||void 0,x||void 0),N.financeByKind(d,g||void 0,x||void 0),N.financeEvents(d,g||void 0,x||void 0,18)]);return{summary:t,byBiller:s,byKind:n,events:r}},"queryFn"),enabled:!!i&&D}),[Ge,ge]=(0,l.useState)(new Set);(0,l.useEffect)(()=>{ge(new Set)},[d,g,x]);function Je(t){ge(s=>{const n=new Set(s);return n.has(t)?n.delete(t):n.add(t),n})}o(Je,"toggleAgent");const Xe=(0,l.useMemo)(()=>{const t=new Map;for(const s of a?.byAgentModel??[]){const n=t.get(s.agentId)??[];n.push(s),t.set(s.agentId,n)}for(const[s,n]of t)t.set(s,n.slice().sort((r,c)=>c.costCents-r.costCents));return t},[a?.byAgentModel]),{data:Q}=S({queryKey:v.usageByProvider(d,g||void 0,x||void 0),queryFn:o(()=>N.byProvider(d,g||void 0,x||void 0),"queryFn"),enabled:!!i&&D&&(u==="providers"||u==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:xe}=S({queryKey:v.usageByBiller(d,g||void 0,x||void 0),queryFn:o(()=>N.byBiller(d,g||void 0,x||void 0),"queryFn"),enabled:!!i&&D&&u==="billers",refetchInterval:3e4,staleTime:1e4}),{data:he}=S({queryKey:v.usageByProvider(d,P.from,P.to),queryFn:o(()=>N.byProvider(d,P.from,P.to),"queryFn"),enabled:!!i&&(u==="providers"||u==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:be}=S({queryKey:v.usageByBiller(d,P.from,P.to),queryFn:o(()=>N.byBiller(d,P.from,P.to),"queryFn"),enabled:!!i&&u==="billers",refetchInterval:3e4,staleTime:1e4}),{data:ve}=S({queryKey:v.usageWindowSpend(d),queryFn:o(()=>N.windowSpend(d),"queryFn"),enabled:!!i&&u==="providers",refetchInterval:3e4,staleTime:1e4}),{data:_,isLoading:ye}=S({queryKey:v.usageQuotaWindows(d),queryFn:o(()=>N.quotaWindows(d),"queryFn"),enabled:!!i&&u==="providers",refetchInterval:3e5,staleTime:6e4}),w=(0,l.useMemo)(()=>{const t=new Map;for(const s of Q??[]){const n=t.get(s.provider)??[];n.push(s),t.set(s.provider,n)}return t},[Q]),k=(0,l.useMemo)(()=>{const t=new Map;for(const s of xe??[]){const n=t.get(s.biller)??[];n.push(s),t.set(s.biller,n)}return t},[xe]),je=(0,l.useMemo)(()=>{const t=new Map;for(const s of he??[])t.set(s.provider,(t.get(s.provider)??0)+s.costCents);return t},[he]),fe=(0,l.useMemo)(()=>{const t=new Map;for(const s of be??[])t.set(s.biller,(t.get(s.biller)??0)+s.costCents);return t},[be]),Ne=(0,l.useMemo)(()=>{const t=new Map;for(const s of ve??[]){const n=t.get(s.provider)??[];n.push(s),t.set(s.provider,n)}return t},[ve]),Ce=(0,l.useMemo)(()=>{const t=new Map;for(const s of _??[])s.ok&&s.windows.length>0&&t.set(s.provider,s.windows);return t},[_]),we=(0,l.useMemo)(()=>{const t=new Map;for(const s of _??[])!s.ok&&s.error&&t.set(s.provider,s.error);return t},[_]),Te=(0,l.useMemo)(()=>{const t=new Map;for(const s of _??[])typeof s.source=="string"&&s.source.length>0&&t.set(s.provider,s.source);return t},[_]),ke=(0,l.useMemo)(()=>{const t=new Map;if(E!=="mtd")return t;const s=a?.summary.budgetCents??0;if(s<=0)return t;const n=a?.summary.spendCents??0,r=new Date,c=r.getDate(),T=new Date(r.getFullYear(),r.getMonth()+1,0).getDate();for(const[f,nt]of w){const ee=nt.reduce((rt,it)=>rt+it.costCents,0),Pe=s*(n>0?ee/n:0);if(Pe<=0){t.set(f,!1);continue}const at=ee/Math.max(c,1);t.set(f,ee+at*(T-c)>Pe)}return t},[E,a,w]),Y=(0,l.useMemo)(()=>Array.from(w.keys()),[w]),U=(0,l.useMemo)(()=>Array.from(k.keys()),[k]),V=b==="all"||Y.includes(b)?b:"all";(0,l.useEffect)(()=>{V!==b&&de("all")},[V,b]);const H=W==="all"||U.includes(W)?W:"all";(0,l.useEffect)(()=>{H!==W&&le("all")},[H,W]);const Ze=(0,l.useMemo)(()=>{const t=Array.from(w.keys()),s=t.reduce((r,c)=>r+(w.get(c)?.reduce((T,f)=>T+f.inputTokens+f.cachedInputTokens+f.outputTokens,0)??0),0),n=t.reduce((r,c)=>r+(w.get(c)?.reduce((T,f)=>T+f.costCents,0)??0),0);return[{value:"all",label:(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:"All providers"}),t.length>0?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(s)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(n)})]}):null]})},...t.map(r=>({value:r,label:(0,e.jsx)(Pt,{provider:r,rows:w.get(r)??[]})}))]},[w]),et=(0,l.useMemo)(()=>{const t=Array.from(k.keys()),s=t.reduce((r,c)=>r+(k.get(c)?.reduce((T,f)=>T+f.inputTokens+f.cachedInputTokens+f.outputTokens,0)??0),0),n=t.reduce((r,c)=>r+(k.get(c)?.reduce((T,f)=>T+f.costCents,0)??0),0);return[{value:"all",label:(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:"All billers"}),t.length>0?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(s)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(n)})]}):null]})},...t.map(r=>({value:r,label:(0,e.jsx)(It,{biller:r,rows:k.get(r)??[]})}))]},[k]),Se=(a?.byAgent??[]).reduce((t,s)=>t+s.inputTokens+s.cachedInputTokens+s.outputTokens,0),Be=p?.events??[],z=A?.policies??[],I=A?.activeIncidents??[],tt=(0,l.useMemo)(()=>({company:z.filter(t=>t.scopeType==="company"),agent:z.filter(t=>t.scopeType==="agent"),project:z.filter(t=>t.scopeType==="project")}),[z]);if(!i)return(0,e.jsx)(xt,{icon:ne,message:"Select a company to view costs."});const G=E==="custom"&&!D,st=(Ve||pe)&&D,Me=He??Z;return(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsxs)("div",{className:"space-y-5",children:[(0,e.jsxs)("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h1",{className:"text-3xl font-semibold tracking-tight",children:"Costs"}),(0,e.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted-foreground",children:"Inference spend, platform fees, credits, and live quota windows."})]}),(0,e.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:Tt.map(t=>(0,e.jsx)(vt,{variant:E===t?"secondary":"ghost",size:"sm",onClick:o(()=>$e(t),"onClick"),"aria-pressed":E===t,children:St[t]},t))})]}),E==="custom"?(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2 border border-border p-3",children:[(0,e.jsx)("input",{type:"date",value:Le,onChange:o(t=>We(t.target.value),"onChange"),className:"h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"}),(0,e.jsx)("span",{className:"text-sm text-muted-foreground",children:"to"}),(0,e.jsx)("input",{type:"date",value:ze,onChange:o(t=>Oe(t.target.value),"onChange"),className:"h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"})]}):null,(0,e.jsxs)("div",{className:"grid gap-3 lg:grid-cols-4",children:[(0,e.jsx)(C,{label:"Inference spend",value:m(a?.summary.spendCents??0),subtitle:`${M(Se)} tokens across request-scoped events`,icon:ne}),(0,e.jsx)(C,{label:"Budget",value:I.length>0?String(I.length):a?.summary.budgetCents&&a.summary.budgetCents>0?`${a.summary.utilizationPercent}%`:"Open",subtitle:I.length>0?`${A?.pausedAgentCount??0} agents paused · ${A?.pausedProjectCount??0} projects paused`:a?.summary.budgetCents&&a.summary.budgetCents>0?`${m(a.summary.spendCents)} of ${m(a.summary.budgetCents)}`:"No monthly cap configured",icon:ie}),(0,e.jsx)(C,{label:"Finance net",value:m(p?.summary.netCents??0),subtitle:`${m(p?.summary.debitCents??0)} debits · ${m(p?.summary.creditCents??0)} credits`,icon:oe}),(0,e.jsx)(C,{label:"Finance events",value:String(p?.summary.eventCount??0),subtitle:`${m(p?.summary.estimatedDebitCents??0)} estimated in range`,icon:re})]})]}),(0,e.jsxs)(te,{value:u,onValueChange:o(t=>j(t),"onValueChange"),children:[(0,e.jsxs)(pt,{variant:"line",className:"justify-start",children:[(0,e.jsx)(O,{value:"overview",children:"Overview"}),(0,e.jsx)(O,{value:"budgets",children:"Budgets"}),(0,e.jsx)(O,{value:"providers",children:"Providers"}),(0,e.jsx)(O,{value:"billers",children:"Billers"}),(0,e.jsx)(O,{value:"finance",children:"Finance"})]}),(0,e.jsx)(B,{value:"overview",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):st?(0,e.jsx)(se,{variant:"costs"}):Me?(0,e.jsx)("p",{className:"text-sm text-destructive",children:Me.message}):(0,e.jsxs)(e.Fragment,{children:[I.length>0?(0,e.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:I.slice(0,2).map(t=>(0,e.jsx)(Ee,{incident:t,isMutating:K.isPending,onKeepPaused:o(()=>K.mutate({incidentId:t.id,action:"keep_paused"}),"onKeepPaused"),onRaiseAndResume:o(s=>K.mutate({incidentId:t.id,action:"raise_budget_and_resume",amount:s}),"onRaiseAndResume")},t.id))}):null,(0,e.jsxs)("div",{className:"grid gap-4 xl:grid-cols-(--gtc-31)",children:[(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"Inference ledger"}),(0,e.jsx)(R,{children:"Request-scoped inference spend for the selected period."})]}),(0,e.jsxs)(F,{className:"space-y-4 px-5 pb-5 pt-2",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("div",{className:"text-3xl font-semibold tabular-nums",children:m(a?.summary.spendCents??0)}),(0,e.jsx)("div",{className:"mt-1 text-sm text-muted-foreground",children:a?.summary.budgetCents&&a.summary.budgetCents>0?`Budget ${m(a.summary.budgetCents)}`:"Unlimited budget"})]}),(0,e.jsxs)("div",{className:"border border-border px-4 py-3 text-right",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground",children:"usage"}),(0,e.jsx)("div",{className:"mt-1 text-lg font-medium tabular-nums",children:M(Se)})]})]}),a?.summary.budgetCents&&a.summary.budgetCents>0?(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("div",{className:"h-2 overflow-hidden bg-muted",children:(0,e.jsx)("div",{className:Ie("h-full transition-(--tp-width-background-color) duration-150",a.summary.utilizationPercent>90?"bg-(--status-task-blocked)":a.summary.utilizationPercent>70?"bg-(--status-task-todo)":"bg-(--status-task-done)"),style:{width:`${Math.min(100,a.summary.utilizationPercent)}%`}})}),(0,e.jsxs)("div",{className:"text-xs text-muted-foreground",children:[a.summary.utilizationPercent,"% of monthly budget consumed in this range."]})]}):null]})]}),(0,e.jsx)(_e,{debitCents:p?.summary.debitCents??0,creditCents:p?.summary.creditCents??0,netCents:p?.summary.netCents??0,estimatedDebitCents:p?.summary.estimatedDebitCents??0,eventCount:p?.summary.eventCount??0})]}),(0,e.jsxs)("div",{className:"grid gap-4 xl:grid-cols-(--gtc-32)",children:[(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"By agent"}),(0,e.jsx)(R,{children:"What each agent consumed in the selected period."})]}),(0,e.jsx)(F,{className:"space-y-2 px-5 pb-5 pt-2",children:(a?.byAgent.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No cost events yet."}):a?.byAgent.map(t=>{const s=Xe.get(t.agentId)??[],n=Ge.has(t.agentId),r=s.length>0;return(0,e.jsxs)("div",{className:"border border-border px-4 py-3",children:[(0,e.jsxs)("div",{className:Ie("flex items-start justify-between gap-3",r?"cursor-pointer select-none":""),onClick:o(()=>r&&Je(t.agentId),"onClick"),children:[(0,e.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[r?n?(0,e.jsx)(ht,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):(0,e.jsx)(bt,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):(0,e.jsx)("span",{className:"h-3 w-3 shrink-0"}),(0,e.jsx)(yt,{agent:{id:t.agentId,name:t.agentName??t.agentId,appearance:t.agentAppearance},size:"sm"}),t.agentStatus==="terminated"?(0,e.jsx)(ft,{status:"terminated"}):null]}),(0,e.jsxs)("div",{className:"text-right text-sm tabular-nums",children:[(0,e.jsx)("div",{className:"font-medium",children:m(t.costCents)}),(0,e.jsxs)("div",{className:"text-xs text-muted-foreground",children:["in ",M(t.inputTokens+t.cachedInputTokens)," · out ",M(t.outputTokens)]}),t.apiRunCount>0||t.subscriptionRunCount>0?(0,e.jsxs)("div",{className:"text-xs text-muted-foreground",children:[t.apiRunCount>0?`${t.apiRunCount} api`:"0 api"," · ",t.subscriptionRunCount>0?`${t.subscriptionRunCount} subscription`:"0 subscription"]}):null]})]}),n&&s.length>0?(0,e.jsx)("div",{className:"mt-3 space-y-2 border-l border-border pl-4",children:s.map(c=>{const T=t.costCents>0?Math.round(c.costCents/t.costCents*100):0;return(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3 text-xs",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsxs)("div",{className:"truncate font-medium text-foreground",children:[J(c.provider),(0,e.jsx)("span",{className:"mx-1 text-border",children:"/"}),(0,e.jsx)("span",{className:"font-mono",children:c.model})]}),(0,e.jsxs)("div",{className:"truncate text-muted-foreground",children:[J(c.biller)," · ",mt(c.billingType)]})]}),(0,e.jsxs)("div",{className:"text-right tabular-nums",children:[(0,e.jsxs)("div",{className:"font-medium",children:[m(c.costCents),(0,e.jsxs)("span",{className:"ml-1 font-normal text-muted-foreground",children:["(",T,"%)"]})]}),(0,e.jsxs)("div",{className:"text-muted-foreground",children:[M(c.inputTokens+c.cachedInputTokens+c.outputTokens)," tok"]})]})]},`${c.provider}:${c.model}:${c.billingType}`)})}):null]},t.agentId)})})]}),(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"By project"}),(0,e.jsx)(R,{children:"Run costs attributed through project-linked tasks."})]}),(0,e.jsx)(F,{className:"space-y-2 px-5 pb-5 pt-2",children:(a?.byProject.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No project-attributed run costs yet."}):a?.byProject.map((t,s)=>(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3 border border-border px-3 py-2 text-sm",children:[(0,e.jsx)("span",{className:"truncate",children:t.projectName??t.projectId??"Unattributed"}),(0,e.jsx)("span",{className:"font-medium tabular-nums",children:m(t.costCents)})]},t.projectId??`unattributed-${s}`))})]}),(0,e.jsx)(Fe,{rows:Be.slice(0,6),emptyMessage:"No finance events yet. Add account-level charges once biller invoices or credits land."})]})]})]})}),(0,e.jsx)(B,{value:"budgets",className:"mt-4 space-y-4",children:Ue?(0,e.jsx)(se,{variant:"costs"}):ce?(0,e.jsx)("p",{className:"text-sm text-destructive",children:ce.message}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(q,{className:"border-border/70 bg-(image:--gradient-extract-2)",children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-3",children:[(0,e.jsx)(L,{className:"text-base",children:"Budget control plane"}),(0,e.jsx)(R,{children:"Hard-stop spend limits for agents and projects. Provider subscription quota stays separate and appears under Providers."})]}),(0,e.jsxs)(F,{className:"grid gap-3 px-5 pb-5 pt-0 md:grid-cols-4",children:[(0,e.jsx)(C,{label:"Active incidents",value:String(I.length),subtitle:"Open soft or hard threshold crossings",icon:oe}),(0,e.jsx)(C,{label:"Pending approvals",value:String(A?.pendingApprovalCount??0),subtitle:"Budget override approvals awaiting board action",icon:re}),(0,e.jsx)(C,{label:"Paused agents",value:String(A?.pausedAgentCount??0),subtitle:"Agent heartbeats blocked by budget",icon:ie}),(0,e.jsx)(C,{label:"Paused projects",value:String(A?.pausedProjectCount??0),subtitle:"Project execution blocked by budget",icon:ne})]})]}),I.length>0?(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h2",{className:"text-lg font-semibold",children:"Active incidents"}),(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Resolve hard stops here by raising the budget or explicitly keeping the scope paused."})]}),(0,e.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:I.map(t=>(0,e.jsx)(Ee,{incident:t,isMutating:K.isPending,onKeepPaused:o(()=>K.mutate({incidentId:t.id,action:"keep_paused"}),"onKeepPaused"),onRaiseAndResume:o(s=>K.mutate({incidentId:t.id,action:"raise_budget_and_resume",amount:s}),"onRaiseAndResume")},t.id))})]}):null,(0,e.jsxs)("div",{className:"space-y-5",children:[["company","agent","project"].map(t=>{const s=tt[t];return s.length===0?null:(0,e.jsxs)("section",{className:"space-y-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsxs)("h2",{className:"text-lg font-semibold capitalize",children:[t," budgets"]}),(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:t==="company"?"Company-wide monthly policy.":t==="agent"?"Recurring monthly spend policies for individual agents.":"Lifetime spend policies for execution-bound projects."})]}),(0,e.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:s.map(n=>(0,e.jsx)(wt,{summary:n,isSaving:me.isPending,onSave:o(r=>me.mutate({scopeType:n.scopeType,scopeId:n.scopeId,amount:r,windowKind:n.windowKind}),"onSave")},n.policyId))})]},t)}),z.length===0?(0,e.jsx)(q,{children:(0,e.jsx)(F,{className:"px-5 py-8 text-sm text-muted-foreground",children:"No budget policies yet. Set agent and project budgets from their detail pages, or use the existing company monthly budget control."})}):null]})]})}),(0,e.jsx)(B,{value:"providers",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):(0,e.jsx)(e.Fragment,{children:(0,e.jsxs)(te,{value:V,onValueChange:de,children:[(0,e.jsx)(De,{items:Ze,value:V}),(0,e.jsx)(B,{value:"all",className:"mt-4",children:Y.length===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No cost events in this period."}):(0,e.jsx)("div",{className:"grid gap-4 md:grid-cols-2",children:Y.map(t=>(0,e.jsx)(Ke,{provider:t,rows:w.get(t)??[],budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,weekSpendCents:je.get(t)??0,windowRows:Ne.get(t)??[],showDeficitNotch:ke.get(t)??!1,quotaWindows:Ce.get(t)??[],quotaError:we.get(t)??null,quotaSource:Te.get(t)??null,quotaLoading:ye},t))})}),Y.map(t=>(0,e.jsx)(B,{value:t,className:"mt-4",children:(0,e.jsx)(Ke,{provider:t,rows:w.get(t)??[],budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,weekSpendCents:je.get(t)??0,windowRows:Ne.get(t)??[],showDeficitNotch:ke.get(t)??!1,quotaWindows:Ce.get(t)??[],quotaError:we.get(t)??null,quotaSource:Te.get(t)??null,quotaLoading:ye})},t))]})})}),(0,e.jsx)(B,{value:"billers",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):(0,e.jsx)(e.Fragment,{children:(0,e.jsxs)(te,{value:H,onValueChange:le,children:[(0,e.jsx)(De,{items:et,value:H}),(0,e.jsx)(B,{value:"all",className:"mt-4",children:U.length===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No billable events in this period."}):(0,e.jsx)("div",{className:"grid gap-4 md:grid-cols-2",children:U.map(t=>{const s=(k.get(t)??[])[0];if(!s)return null;const n=(Q??[]).filter(r=>r.biller===t);return(0,e.jsx)(Ae,{row:s,weekSpendCents:fe.get(t)??0,budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,providerRows:n},t)})})}),U.map(t=>{const s=(k.get(t)??[])[0];if(!s)return null;const n=(Q??[]).filter(r=>r.biller===t);return(0,e.jsx)(B,{value:t,className:"mt-4",children:(0,e.jsx)(Ae,{row:s,weekSpendCents:fe.get(t)??0,budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,providerRows:n})},t)})]})})}),(0,e.jsx)(B,{value:"finance",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):pe?(0,e.jsx)(se,{variant:"costs"}):Z?(0,e.jsx)("p",{className:"text-sm text-destructive",children:Z.message}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(_e,{debitCents:p?.summary.debitCents??0,creditCents:p?.summary.creditCents??0,netCents:p?.summary.netCents??0,estimatedDebitCents:p?.summary.estimatedDebitCents??0,eventCount:p?.summary.eventCount??0}),(0,e.jsxs)("div",{className:"grid gap-4 xl:grid-cols-(--gtc-33)",children:[(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"By biller"}),(0,e.jsx)(R,{children:"Account-level financial events grouped by who charged or credited them."})]}),(0,e.jsx)(F,{className:"grid gap-4 px-5 pb-5 pt-2 md:grid-cols-2",children:(p?.byBiller.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No finance events yet."}):p?.byBiller.map(t=>(0,e.jsx)(kt,{row:t},t.biller))})]}),(0,e.jsx)(Fe,{rows:Be})]}),(0,e.jsx)(jt,{rows:p?.byKind??[]})]})]})})]})]})}o(Ot,"Costs");export{Ot as Costs};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var pt=Object.defineProperty;var u=(e,a)=>pt(e,"name",{value:a,configurable:!0});import{i as ot}from"./rolldown-runtime-ZpX3ckPj.js";import{En as yt,Fr as bt,Lr as vt,U as wt,Y as K,_ as Ct,nr as Q}from"./createLucideIcon-CZEG6UJ7.js";import{o as jt,t as V}from"./router-G1KztA90.js";import{t as Mt}from"./AgentAvatar-CnpBTXF0.js";import{t as J}from"./agents-ZcIBncVi.js";import{r as Nt,t as tt}from"./EmptyState-DeVTy8IU.js";import{k as kt,t as et}from"./button-LkWt40cm.js";import{n as Pt,t as Dt}from"./useHiddenSettings-vbDpbX0U.js";import{t as Yt}from"./card-DbvoJZ3K.js";import{t as Zt}from"./PageSkeleton-DRRnaWWU.js";import{Dn as rt,On as Et,Pn as Tt,Yt as _t,en as Xt,hn as zt}from"./index-DbWxivZc.js";var o=ot(vt(),1),n=ot(bt(),1),N=200,W=100,X=32,$t=80,L=60,Wt=.2,Lt=2,R=6;function Z(e){if(e.reports.length===0)return N;const a=e.reports.reduce((i,f)=>i+Z(f),0),d=(e.reports.length-1)*X;return Math.max(N,a+d)}u(Z,"subtreeWidth");function at(e,a,d){const i=Z(e),f=[];if(e.reports.length>0){const C=e.reports.reduce((k,P)=>k+Z(P),0),S=(e.reports.length-1)*X;let j=a+(i-C-S)/2;for(const k of e.reports){const P=Z(k);f.push(at(k,j,d+W+$t)),j+=P+X}}return{id:e.id,name:e.name,role:e.role,status:e.status,x:a+(i-N)/2,y:d,children:f}}u(at,"layoutTree");function St(e){if(e.length===0)return[];e.reduce((f,C)=>f+Z(C),0),(e.length-1)*X;let a=L;const d=L,i=[];for(const f of e){const C=Z(f);i.push(at(f,a,d)),a+=C+X}return i}u(St,"layoutForest");function Ht(e){const a=[];function d(i){a.push(i),i.children.forEach(d)}return u(d,"walk"),e.forEach(d),a}u(Ht,"flattenLayout");function Rt(e){const a=[];function d(i){for(const f of i.children)a.push({parent:i,child:f}),d(f)}return u(d,"walk"),e.forEach(d),a}u(Rt,"collectEdges");function A(e){return Math.min(Math.max(e,Wt),Lt)}u(A,"clampZoom");function At(e){return{x:e.clientX,y:e.clientY}}u(At,"touchPoint");function nt(e,a){const d=e.clientX-a.clientX,i=e.clientY-a.clientY;return Math.hypot(d,i)}u(nt,"touchDistance");function st(e,a,d){const i=d.getBoundingClientRect();return{x:(e.clientX+a.clientX)/2-i.left,y:(e.clientY+a.clientY)/2-i.top}}u(st,"touchCenter");var Ot={running:"var(--hex-22d3ee)",active:"var(--hex-4ade80)",paused:"var(--hex-facc15)",idle:"var(--hex-facc15)",error:"var(--hex-f87171)",terminated:"var(--hex-a3a3a3)"},Bt="var(--hex-a3a3a3)";function oe(){const{selectedCompanyId:e}=wt(),{setBreadcrumbs:a}=Nt(),d=jt(),i=!!Xt(),{hidden:f}=Dt(),C=!i&&!f.has("company.import"),S=!f.has("company.export"),{data:j,isLoading:k}=Q({queryKey:K.org(e),queryFn:u(()=>J.org(e),"queryFn"),enabled:!!e}),{data:P}=Q({queryKey:K.agents.list(e),queryFn:u(()=>J.list(e),"queryFn"),enabled:!!e}),ct=(0,o.useMemo)(()=>{const t=new Map;for(const r of P??[])t.set(r.id,r);return t},[P]);(0,o.useEffect)(()=>{a([{label:"Org Chart"}])},[a]);const z=(0,o.useMemo)(()=>St(j??[]),[j]),D=(0,o.useMemo)(()=>Ht(z),[z]),it=(0,o.useMemo)(()=>Rt(z),[z]),v=(0,o.useMemo)(()=>{if(D.length===0)return{width:800,height:600};let t=0,r=0;for(const s of D)t=Math.max(t,s.x+N),r=Math.max(r,s.y+W);return{width:t+L,height:r+L}},[D]),p=(0,o.useRef)(null),[l,M]=(0,o.useState)({x:0,y:0}),[h,E]=(0,o.useState)(1),[H,O]=(0,o.useState)(!1),T=(0,o.useRef)({x:0,y:0,panX:0,panY:0}),m=(0,o.useRef)({mode:null,startPoint:{x:0,y:0},startPan:{x:0,y:0},startZoom:1,startDistance:0,startCenter:{x:0,y:0},moved:!1}),$=(0,o.useRef)(!1),Y=(0,o.useRef)(null);(0,o.useEffect)(()=>()=>{Y.current!==null&&window.clearTimeout(Y.current)},[]);const B=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(B.current||D.length===0||!p.current)return;B.current=!0;const t=p.current,r=t.clientWidth,s=t.clientHeight,c=(r-40)/v.width,x=(s-40)/v.height,g=Math.min(c,x,1),y=v.width*g,w=v.height*g;E(g),M({x:(r-y)/2,y:(s-w)/2})},[D,v]);const lt=(0,o.useCallback)(t=>{t.button===0&&(t.target.closest("[data-org-card]")||(O(!0),T.current={x:t.clientX,y:t.clientY,panX:l.x,panY:l.y}))},[l]),ut=(0,o.useCallback)(t=>{if(!H)return;const r=t.clientX-T.current.x,s=t.clientY-T.current.y;M({x:T.current.panX+r,y:T.current.panY+s})},[H]),q=(0,o.useCallback)(()=>{O(!1)},[]),dt=(0,o.useCallback)(t=>{t.preventDefault();const r=p.current;if(!r)return;const s=r.getBoundingClientRect(),c=t.clientX-s.left,x=t.clientY-s.top,g=t.deltaY<0?1.1:.9,y=A(h*g),w=y/h;M({x:c-w*(c-l.x),y:x-w*(x-l.y)}),E(y)},[h,l]),I=(0,o.useCallback)((t,r)=>{const s=A(t),c=s/h;M({x:r.x-c*(r.x-l.x),y:r.y-c*(r.y-l.y)}),E(s)},[h,l]),ht=(0,o.useCallback)(()=>{if(!p.current)return;const t=p.current.clientWidth,r=p.current.clientHeight,s=(t-40)/v.width,c=(r-40)/v.height,x=Math.min(s,c,1),g=v.width*x,y=v.height*x;E(x),M({x:(t-g)/2,y:(r-y)/2})},[v]),mt=(0,o.useCallback)(t=>{if(t.touches.length>=2&&p.current){const[s,c]=[t.touches[0],t.touches[1]];m.current={mode:"pinch",startPoint:{x:0,y:0},startPan:l,startZoom:h,startDistance:nt(s,c),startCenter:st(s,c,p.current),moved:!1};return}const r=t.touches[0];r&&(m.current={mode:"pan",startPoint:At(r),startPan:l,startZoom:h,startDistance:0,startCenter:{x:0,y:0},moved:!1})},[l,h]),ft=(0,o.useCallback)(t=>{const r=p.current;if(!r||!m.current.mode)return;if(t.touches.length>=2){const[g,y]=[t.touches[0],t.touches[1]],w=nt(g,y),_=st(g,y,r);if(m.current.mode!=="pinch"||m.current.startDistance===0){m.current={mode:"pinch",startPoint:{x:0,y:0},startPan:l,startZoom:h,startDistance:w,startCenter:_,moved:!1};return}const b=m.current,U=A(b.startZoom*(w/b.startDistance)),G=U/b.startZoom,xt=_.x-b.startCenter.x,gt=_.y-b.startCenter.y;b.moved=b.moved||Math.abs(w-b.startDistance)>R||Math.hypot(xt,gt)>R,E(U),M({x:_.x-G*(b.startCenter.x-b.startPan.x),y:_.y-G*(b.startCenter.y-b.startPan.y)});return}const s=t.touches[0];if(!s||m.current.mode!=="pan")return;const c=s.clientX-m.current.startPoint.x,x=s.clientY-m.current.startPoint.y;m.current.moved=m.current.moved||Math.hypot(c,x)>R,M({x:m.current.startPan.x+c,y:m.current.startPan.y+x})},[l,h]),F=(0,o.useCallback)(()=>{m.current.moved&&($.current=!0,Y.current!==null&&window.clearTimeout(Y.current),Y.current=window.setTimeout(()=>{$.current=!1,Y.current=null},400)),m.current={mode:null,startPoint:{x:0,y:0},startPan:l,startZoom:h,startDistance:0,startCenter:{x:0,y:0},moved:!1}},[l,h]);return e?k?(0,n.jsx)(Zt,{variant:"org-chart"}):j&&j.length===0?(0,n.jsx)(tt,{icon:rt,message:"No organizational hierarchy defined."}):(0,n.jsxs)("div",{className:"flex h-(--sz-calc-38) min-h-(--sz-420px) flex-col md:h-full md:min-h-0",children:[(0,n.jsxs)("div",{className:"mb-2 flex shrink-0 flex-wrap items-center justify-start gap-2",children:[C&&(0,n.jsx)(V,{to:"/company/import",children:(0,n.jsxs)(et,{variant:"outline",size:"sm",children:[(0,n.jsx)(zt,{className:"mr-1.5 h-3.5 w-3.5"}),"Import company"]})}),S&&(0,n.jsx)(V,{to:"/company/export",children:(0,n.jsxs)(et,{variant:"outline",size:"sm",children:[(0,n.jsx)(Tt,{className:"mr-1.5 h-3.5 w-3.5"}),"Export company"]})})]}),(0,n.jsxs)("div",{ref:p,"data-testid":"org-chart-viewport",className:"w-full flex-1 min-h-0 overflow-hidden relative bg-muted/20 border border-border rounded-lg",style:{cursor:H?"grabbing":"grab",touchAction:"none",overscrollBehavior:"contain"},onMouseDown:lt,onMouseMove:ut,onMouseUp:q,onMouseLeave:q,onWheel:dt,onTouchStart:mt,onTouchMove:ft,onTouchEnd:F,onTouchCancel:F,children:[(0,n.jsxs)("div",{className:"absolute top-3 right-3 z-10 flex flex-col gap-1.5",children:[(0,n.jsx)("button",{className:"flex size-9 items-center justify-center rounded border border-border bg-background text-sm transition-colors hover:bg-accent sm:size-7",onClick:u(()=>{const t=p.current;t&&I(h*1.2,{x:t.clientWidth/2,y:t.clientHeight/2})},"onClick"),title:"Zoom in","aria-label":"Zoom in",children:(0,n.jsx)(kt,{className:"h-4 w-4 sm:h-3.5 sm:w-3.5"})}),(0,n.jsx)("button",{className:"flex size-9 items-center justify-center rounded border border-border bg-background text-sm transition-colors hover:bg-accent sm:size-7",onClick:u(()=>{const t=p.current;t&&I(h*.8,{x:t.clientWidth/2,y:t.clientHeight/2})},"onClick"),title:"Zoom out","aria-label":"Zoom out",children:(0,n.jsx)(Pt,{className:"h-4 w-4 sm:h-3.5 sm:w-3.5"})}),(0,n.jsx)("button",{className:"flex size-9 items-center justify-center rounded border border-border bg-background text-(length:--text-nano) transition-colors hover:bg-accent sm:size-7",onClick:ht,title:"Fit to screen","aria-label":"Fit chart to screen",children:(0,n.jsx)(Et,{className:"h-4 w-4 sm:h-3.5 sm:w-3.5"})})]}),(0,n.jsx)("svg",{className:"absolute inset-0 pointer-events-none",style:{width:"100%",height:"100%"},children:(0,n.jsx)("g",{transform:`translate(${l.x}, ${l.y}) scale(${h})`,children:it.map(({parent:t,child:r})=>{const s=t.x+N/2,c=t.y+W,x=r.x+N/2,g=r.y,y=(c+g)/2;return(0,n.jsx)("path",{d:`M ${s} ${c} L ${s} ${y} L ${x} ${y} L ${x} ${g}`,fill:"none",stroke:"var(--border)",strokeWidth:1.5},`${t.id}-${r.id}`)})})}),(0,n.jsx)("div",{"data-testid":"org-chart-card-layer",className:"absolute inset-0",style:{transform:`translate(${l.x}px, ${l.y}px) scale(${h})`,transformOrigin:"0 0"},children:D.map(t=>{const r=ct.get(t.id),s=Ot[t.status]??Bt;return(0,n.jsx)(Yt,{"data-org-card":!0,className:"block absolute py-0 hover:shadow-md hover:border-foreground/20 transition-(--tp-box-shadow-border-color) duration-150 cursor-pointer select-none",style:{left:t.x,top:t.y,width:N,minHeight:W},onClick:u(()=>d(r?Ct(r):`/agents/${t.id}`),"onClick"),onClickCapture:u(c=>{$.current&&($.current=!1,c.preventDefault(),c.stopPropagation())},"onClickCapture"),children:(0,n.jsxs)("div",{className:"flex items-center px-4 py-3 gap-3",children:[(0,n.jsxs)("div",{className:"relative shrink-0",children:[(0,n.jsx)("div",{className:"w-9 h-9 rounded-full bg-muted flex items-center justify-center",children:(0,n.jsx)(Mt,{agent:r,size:16,className:"h-4.5 w-4.5 text-foreground/70"})}),(0,n.jsx)("span",{className:"absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2 border-card",style:{backgroundColor:s}})]}),(0,n.jsxs)("div",{className:"flex flex-col items-start min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"text-sm font-semibold text-foreground leading-tight",children:t.name}),(0,n.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground leading-tight mt-0.5",children:r?.title??It(t.role)}),r&&(0,n.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground/60 font-mono leading-tight mt-1",children:_t(r.adapterType)}),r&&r.capabilities&&(0,n.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground/80 leading-tight mt-1 line-clamp-2",children:r.capabilities})]})]})},t.id)})})]})]}):(0,n.jsx)(tt,{icon:rt,message:"Select a company to view the org chart."})}u(oe,"OrgChart");var qt=yt;function It(e){return qt[e]??e}u(It,"roleLabel");export{oe as OrgChart};
|
|
1
|
+
var pt=Object.defineProperty;var u=(e,a)=>pt(e,"name",{value:a,configurable:!0});import{i as ot}from"./rolldown-runtime-ZpX3ckPj.js";import{En as yt,Fr as bt,Lr as vt,U as wt,Y as K,_ as Ct,nr as Q}from"./createLucideIcon-CZEG6UJ7.js";import{o as jt,t as V}from"./router-G1KztA90.js";import{t as Mt}from"./AgentAvatar-CnpBTXF0.js";import{t as J}from"./agents-ZcIBncVi.js";import{r as Nt,t as tt}from"./EmptyState-DeVTy8IU.js";import{k as kt,t as et}from"./button-LkWt40cm.js";import{n as Pt,t as Dt}from"./useHiddenSettings-vbDpbX0U.js";import{t as Yt}from"./card-DbvoJZ3K.js";import{t as Zt}from"./PageSkeleton-DRRnaWWU.js";import{Dn as rt,On as Et,Pn as Tt,Yt as _t,en as Xt,hn as zt}from"./index-Cf2CHzHP.js";var o=ot(vt(),1),n=ot(bt(),1),N=200,W=100,X=32,$t=80,L=60,Wt=.2,Lt=2,R=6;function Z(e){if(e.reports.length===0)return N;const a=e.reports.reduce((i,f)=>i+Z(f),0),d=(e.reports.length-1)*X;return Math.max(N,a+d)}u(Z,"subtreeWidth");function at(e,a,d){const i=Z(e),f=[];if(e.reports.length>0){const C=e.reports.reduce((k,P)=>k+Z(P),0),S=(e.reports.length-1)*X;let j=a+(i-C-S)/2;for(const k of e.reports){const P=Z(k);f.push(at(k,j,d+W+$t)),j+=P+X}}return{id:e.id,name:e.name,role:e.role,status:e.status,x:a+(i-N)/2,y:d,children:f}}u(at,"layoutTree");function St(e){if(e.length===0)return[];e.reduce((f,C)=>f+Z(C),0),(e.length-1)*X;let a=L;const d=L,i=[];for(const f of e){const C=Z(f);i.push(at(f,a,d)),a+=C+X}return i}u(St,"layoutForest");function Ht(e){const a=[];function d(i){a.push(i),i.children.forEach(d)}return u(d,"walk"),e.forEach(d),a}u(Ht,"flattenLayout");function Rt(e){const a=[];function d(i){for(const f of i.children)a.push({parent:i,child:f}),d(f)}return u(d,"walk"),e.forEach(d),a}u(Rt,"collectEdges");function A(e){return Math.min(Math.max(e,Wt),Lt)}u(A,"clampZoom");function At(e){return{x:e.clientX,y:e.clientY}}u(At,"touchPoint");function nt(e,a){const d=e.clientX-a.clientX,i=e.clientY-a.clientY;return Math.hypot(d,i)}u(nt,"touchDistance");function st(e,a,d){const i=d.getBoundingClientRect();return{x:(e.clientX+a.clientX)/2-i.left,y:(e.clientY+a.clientY)/2-i.top}}u(st,"touchCenter");var Ot={running:"var(--hex-22d3ee)",active:"var(--hex-4ade80)",paused:"var(--hex-facc15)",idle:"var(--hex-facc15)",error:"var(--hex-f87171)",terminated:"var(--hex-a3a3a3)"},Bt="var(--hex-a3a3a3)";function oe(){const{selectedCompanyId:e}=wt(),{setBreadcrumbs:a}=Nt(),d=jt(),i=!!Xt(),{hidden:f}=Dt(),C=!i&&!f.has("company.import"),S=!f.has("company.export"),{data:j,isLoading:k}=Q({queryKey:K.org(e),queryFn:u(()=>J.org(e),"queryFn"),enabled:!!e}),{data:P}=Q({queryKey:K.agents.list(e),queryFn:u(()=>J.list(e),"queryFn"),enabled:!!e}),ct=(0,o.useMemo)(()=>{const t=new Map;for(const r of P??[])t.set(r.id,r);return t},[P]);(0,o.useEffect)(()=>{a([{label:"Org Chart"}])},[a]);const z=(0,o.useMemo)(()=>St(j??[]),[j]),D=(0,o.useMemo)(()=>Ht(z),[z]),it=(0,o.useMemo)(()=>Rt(z),[z]),v=(0,o.useMemo)(()=>{if(D.length===0)return{width:800,height:600};let t=0,r=0;for(const s of D)t=Math.max(t,s.x+N),r=Math.max(r,s.y+W);return{width:t+L,height:r+L}},[D]),p=(0,o.useRef)(null),[l,M]=(0,o.useState)({x:0,y:0}),[h,E]=(0,o.useState)(1),[H,O]=(0,o.useState)(!1),T=(0,o.useRef)({x:0,y:0,panX:0,panY:0}),m=(0,o.useRef)({mode:null,startPoint:{x:0,y:0},startPan:{x:0,y:0},startZoom:1,startDistance:0,startCenter:{x:0,y:0},moved:!1}),$=(0,o.useRef)(!1),Y=(0,o.useRef)(null);(0,o.useEffect)(()=>()=>{Y.current!==null&&window.clearTimeout(Y.current)},[]);const B=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(B.current||D.length===0||!p.current)return;B.current=!0;const t=p.current,r=t.clientWidth,s=t.clientHeight,c=(r-40)/v.width,x=(s-40)/v.height,g=Math.min(c,x,1),y=v.width*g,w=v.height*g;E(g),M({x:(r-y)/2,y:(s-w)/2})},[D,v]);const lt=(0,o.useCallback)(t=>{t.button===0&&(t.target.closest("[data-org-card]")||(O(!0),T.current={x:t.clientX,y:t.clientY,panX:l.x,panY:l.y}))},[l]),ut=(0,o.useCallback)(t=>{if(!H)return;const r=t.clientX-T.current.x,s=t.clientY-T.current.y;M({x:T.current.panX+r,y:T.current.panY+s})},[H]),q=(0,o.useCallback)(()=>{O(!1)},[]),dt=(0,o.useCallback)(t=>{t.preventDefault();const r=p.current;if(!r)return;const s=r.getBoundingClientRect(),c=t.clientX-s.left,x=t.clientY-s.top,g=t.deltaY<0?1.1:.9,y=A(h*g),w=y/h;M({x:c-w*(c-l.x),y:x-w*(x-l.y)}),E(y)},[h,l]),I=(0,o.useCallback)((t,r)=>{const s=A(t),c=s/h;M({x:r.x-c*(r.x-l.x),y:r.y-c*(r.y-l.y)}),E(s)},[h,l]),ht=(0,o.useCallback)(()=>{if(!p.current)return;const t=p.current.clientWidth,r=p.current.clientHeight,s=(t-40)/v.width,c=(r-40)/v.height,x=Math.min(s,c,1),g=v.width*x,y=v.height*x;E(x),M({x:(t-g)/2,y:(r-y)/2})},[v]),mt=(0,o.useCallback)(t=>{if(t.touches.length>=2&&p.current){const[s,c]=[t.touches[0],t.touches[1]];m.current={mode:"pinch",startPoint:{x:0,y:0},startPan:l,startZoom:h,startDistance:nt(s,c),startCenter:st(s,c,p.current),moved:!1};return}const r=t.touches[0];r&&(m.current={mode:"pan",startPoint:At(r),startPan:l,startZoom:h,startDistance:0,startCenter:{x:0,y:0},moved:!1})},[l,h]),ft=(0,o.useCallback)(t=>{const r=p.current;if(!r||!m.current.mode)return;if(t.touches.length>=2){const[g,y]=[t.touches[0],t.touches[1]],w=nt(g,y),_=st(g,y,r);if(m.current.mode!=="pinch"||m.current.startDistance===0){m.current={mode:"pinch",startPoint:{x:0,y:0},startPan:l,startZoom:h,startDistance:w,startCenter:_,moved:!1};return}const b=m.current,U=A(b.startZoom*(w/b.startDistance)),G=U/b.startZoom,xt=_.x-b.startCenter.x,gt=_.y-b.startCenter.y;b.moved=b.moved||Math.abs(w-b.startDistance)>R||Math.hypot(xt,gt)>R,E(U),M({x:_.x-G*(b.startCenter.x-b.startPan.x),y:_.y-G*(b.startCenter.y-b.startPan.y)});return}const s=t.touches[0];if(!s||m.current.mode!=="pan")return;const c=s.clientX-m.current.startPoint.x,x=s.clientY-m.current.startPoint.y;m.current.moved=m.current.moved||Math.hypot(c,x)>R,M({x:m.current.startPan.x+c,y:m.current.startPan.y+x})},[l,h]),F=(0,o.useCallback)(()=>{m.current.moved&&($.current=!0,Y.current!==null&&window.clearTimeout(Y.current),Y.current=window.setTimeout(()=>{$.current=!1,Y.current=null},400)),m.current={mode:null,startPoint:{x:0,y:0},startPan:l,startZoom:h,startDistance:0,startCenter:{x:0,y:0},moved:!1}},[l,h]);return e?k?(0,n.jsx)(Zt,{variant:"org-chart"}):j&&j.length===0?(0,n.jsx)(tt,{icon:rt,message:"No organizational hierarchy defined."}):(0,n.jsxs)("div",{className:"flex h-(--sz-calc-38) min-h-(--sz-420px) flex-col md:h-full md:min-h-0",children:[(0,n.jsxs)("div",{className:"mb-2 flex shrink-0 flex-wrap items-center justify-start gap-2",children:[C&&(0,n.jsx)(V,{to:"/company/import",children:(0,n.jsxs)(et,{variant:"outline",size:"sm",children:[(0,n.jsx)(zt,{className:"mr-1.5 h-3.5 w-3.5"}),"Import company"]})}),S&&(0,n.jsx)(V,{to:"/company/export",children:(0,n.jsxs)(et,{variant:"outline",size:"sm",children:[(0,n.jsx)(Tt,{className:"mr-1.5 h-3.5 w-3.5"}),"Export company"]})})]}),(0,n.jsxs)("div",{ref:p,"data-testid":"org-chart-viewport",className:"w-full flex-1 min-h-0 overflow-hidden relative bg-muted/20 border border-border rounded-lg",style:{cursor:H?"grabbing":"grab",touchAction:"none",overscrollBehavior:"contain"},onMouseDown:lt,onMouseMove:ut,onMouseUp:q,onMouseLeave:q,onWheel:dt,onTouchStart:mt,onTouchMove:ft,onTouchEnd:F,onTouchCancel:F,children:[(0,n.jsxs)("div",{className:"absolute top-3 right-3 z-10 flex flex-col gap-1.5",children:[(0,n.jsx)("button",{className:"flex size-9 items-center justify-center rounded border border-border bg-background text-sm transition-colors hover:bg-accent sm:size-7",onClick:u(()=>{const t=p.current;t&&I(h*1.2,{x:t.clientWidth/2,y:t.clientHeight/2})},"onClick"),title:"Zoom in","aria-label":"Zoom in",children:(0,n.jsx)(kt,{className:"h-4 w-4 sm:h-3.5 sm:w-3.5"})}),(0,n.jsx)("button",{className:"flex size-9 items-center justify-center rounded border border-border bg-background text-sm transition-colors hover:bg-accent sm:size-7",onClick:u(()=>{const t=p.current;t&&I(h*.8,{x:t.clientWidth/2,y:t.clientHeight/2})},"onClick"),title:"Zoom out","aria-label":"Zoom out",children:(0,n.jsx)(Pt,{className:"h-4 w-4 sm:h-3.5 sm:w-3.5"})}),(0,n.jsx)("button",{className:"flex size-9 items-center justify-center rounded border border-border bg-background text-(length:--text-nano) transition-colors hover:bg-accent sm:size-7",onClick:ht,title:"Fit to screen","aria-label":"Fit chart to screen",children:(0,n.jsx)(Et,{className:"h-4 w-4 sm:h-3.5 sm:w-3.5"})})]}),(0,n.jsx)("svg",{className:"absolute inset-0 pointer-events-none",style:{width:"100%",height:"100%"},children:(0,n.jsx)("g",{transform:`translate(${l.x}, ${l.y}) scale(${h})`,children:it.map(({parent:t,child:r})=>{const s=t.x+N/2,c=t.y+W,x=r.x+N/2,g=r.y,y=(c+g)/2;return(0,n.jsx)("path",{d:`M ${s} ${c} L ${s} ${y} L ${x} ${y} L ${x} ${g}`,fill:"none",stroke:"var(--border)",strokeWidth:1.5},`${t.id}-${r.id}`)})})}),(0,n.jsx)("div",{"data-testid":"org-chart-card-layer",className:"absolute inset-0",style:{transform:`translate(${l.x}px, ${l.y}px) scale(${h})`,transformOrigin:"0 0"},children:D.map(t=>{const r=ct.get(t.id),s=Ot[t.status]??Bt;return(0,n.jsx)(Yt,{"data-org-card":!0,className:"block absolute py-0 hover:shadow-md hover:border-foreground/20 transition-(--tp-box-shadow-border-color) duration-150 cursor-pointer select-none",style:{left:t.x,top:t.y,width:N,minHeight:W},onClick:u(()=>d(r?Ct(r):`/agents/${t.id}`),"onClick"),onClickCapture:u(c=>{$.current&&($.current=!1,c.preventDefault(),c.stopPropagation())},"onClickCapture"),children:(0,n.jsxs)("div",{className:"flex items-center px-4 py-3 gap-3",children:[(0,n.jsxs)("div",{className:"relative shrink-0",children:[(0,n.jsx)("div",{className:"w-9 h-9 rounded-full bg-muted flex items-center justify-center",children:(0,n.jsx)(Mt,{agent:r,size:16,className:"h-4.5 w-4.5 text-foreground/70"})}),(0,n.jsx)("span",{className:"absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2 border-card",style:{backgroundColor:s}})]}),(0,n.jsxs)("div",{className:"flex flex-col items-start min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"text-sm font-semibold text-foreground leading-tight",children:t.name}),(0,n.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground leading-tight mt-0.5",children:r?.title??It(t.role)}),r&&(0,n.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground/60 font-mono leading-tight mt-1",children:_t(r.adapterType)}),r&&r.capabilities&&(0,n.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground/80 leading-tight mt-1 line-clamp-2",children:r.capabilities})]})]})},t.id)})})]})]}):(0,n.jsx)(tt,{icon:rt,message:"Select a company to view the org chart."})}u(oe,"OrgChart");var qt=yt;function It(e){return qt[e]??e}u(It,"roleLabel");export{oe as OrgChart};
|
package/ui-dist/assets/{RoutineDetail.production-MBJ3aeg2.js → RoutineDetail.production-DOdpoBuO.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-CZEG6UJ7.js";import{Z as Ee,o as ht,r as oe,st as gt}from"./router-G1KztA90.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-Bj-Q_Ua3.js";import{Q as Nt}from"./mention-chips-BEaOTvHT.js";import{s as kt,t as St}from"./zap-CCqZhqc3.js";import{a as T,t as De}from"./MarkdownEditor-7JCtdEaZ.js";import{v as It}from"./sheet-H27vJn3G.js";import{t as _e}from"./AgentAvatar-CnpBTXF0.js";import{k as Ct}from"./checkbox-CLAkJpms.js";import{_ as At,s as Pt,t as O}from"./label-Dnc69R1W.js";import{t as Rt}from"./agents-ZcIBncVi.js";import{g as Tt}from"./StatusIcon-j05cEqDO.js";import{r as Et,t as te}from"./EmptyState-DeVTy8IU.js";import{c as de,i as ue,n as me,s as pe,t as he}from"./select-DSr2hsz2.js";import{r as Ot,t as Dt}from"./save-D9PtvKKu.js";import{k as _t,t as E}from"./button-LkWt40cm.js";import{n as Mt,t as qt}from"./clipboard-CjMs5cp9.js";import{t as Ft}from"./heartbeats-DFiFf4Zf.js";import{t as xe}from"./badge-B4sBXDQo.js";import{t as V}from"./input-a7SggR2b.js";import{i as Kt,o as Lt}from"./company-members-Dyq_pnza.js";import{r as Ut,t as Wt}from"./card-DbvoJZ3K.js";import{t as $t}from"./PageSkeleton-DRRnaWWU.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-DbWxivZc.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-CZEG6UJ7.js";import{Z as Ee,o as ht,r as oe,st as gt}from"./router-G1KztA90.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-Bj-Q_Ua3.js";import{Q as Nt}from"./mention-chips-BEaOTvHT.js";import{s as kt,t as St}from"./zap-CCqZhqc3.js";import{a as T,t as De}from"./MarkdownEditor-7JCtdEaZ.js";import{v as It}from"./sheet-H27vJn3G.js";import{t as _e}from"./AgentAvatar-CnpBTXF0.js";import{k as Ct}from"./checkbox-CLAkJpms.js";import{_ as At,s as Pt,t as O}from"./label-Dnc69R1W.js";import{t as Rt}from"./agents-ZcIBncVi.js";import{g as Tt}from"./StatusIcon-j05cEqDO.js";import{r as Et,t as te}from"./EmptyState-DeVTy8IU.js";import{c as de,i as ue,n as me,s as pe,t as he}from"./select-DSr2hsz2.js";import{r as Ot,t as Dt}from"./save-D9PtvKKu.js";import{k as _t,t as E}from"./button-LkWt40cm.js";import{n as Mt,t as qt}from"./clipboard-CjMs5cp9.js";import{t as Ft}from"./heartbeats-DFiFf4Zf.js";import{t as xe}from"./badge-B4sBXDQo.js";import{t as V}from"./input-a7SggR2b.js";import{i as Kt,o as Lt}from"./company-members-Dyq_pnza.js";import{r as Ut,t as Wt}from"./card-DbvoJZ3K.js";import{t as $t}from"./PageSkeleton-DRRnaWWU.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-Cf2CHzHP.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};
|