PageSourceSearch

https://app.gopitcrew.com/assets/CrewBuilderPage-ttwa04CV.js

js gopitcrew.com collected 2026-10-03 21:13:32 UTC 96,147 bytes, 108 lines download raw bytes

1import{n,l as e,a as It,t as ms,w as oa,q as ca,L as ts}from"./vendor-react-DqEQpdJ_.js";import{F as ye}from"./featureFlags-A8ff9_K1.js";import{B as L,y as vt,L as Y,a0 as da}from"./index-vP4jtEGS.js";import{P as ua}from"./PageHeader-B965E2Ue.js";import{boardAssistantService as se}from"./boardAssistantService-D2kdNCbr.js";import{f as rt}from"./factoryV2Service-C4Aj8KlR.js";import{C as pa}from"./ChatMarkdownRenderer-DIZgCIWX.js";import{l as kt,aW as yt,bd as Ye,at as ss,bv as Tt,y as ma,bl as fa,v as $e,j as xa,G as ha,ab as fs,d as ga,bp as ba,ax as Ve,b2 as ja,t as Je,f as wa,J as va,z as ka,D as ya,M as Na,bx as xs,X as Nt,F as _a,aR as Dt,ai as Sa,Q as Ca,bw as $a,bg as Ia,a4 as it,aN as hs,g as gs,s as Ta,by as Bt,aq as as,b0 as Da,I as Ba}from"./vendor-icons-B-8y0biV.js";import{C as Ee,b as Fe,a as Me}from"./collapsible-RWJIDDXJ.js";import{P as we}from"./pill-DLeX0aLu.js";import{H as Ra}from"./horizontal-scroll-BXKR3waA.js";import{T as Aa,b as Ea,c as ns}from"./tabs-B1w75L_L.js";import{L as Fa}from"./LayoutEngine-W4ig_vV_.js";import{c as _t,h as Ma,f as Oa,Q as Pa}from"./QuestionWizard-DxS5na43.js";import{a as La}from"./StartRunDialog-D5gNmecH.js";import{T as qa}from"./textarea-DZCwG0YZ.js";import{R as za}from"./RunStatusPill-CQ6-woxE.js";import{F as Va}from"./FinalOutputSection-B5uihO4s.js";import{F as bs}from"./file-input--HbJqV0v.js";import{B as Ua,c as Ga,a as St,b as rs,e as is,d as Wa}from"./breadcrumb-C4danDTy.js";import{P as Ct}from"./PanelLayout-hHT44NuR.js";import{p as Qa}from"./prdBuilderService-7XXT8Kyy.js";import"./vendor-radix-BAR1pTYe.js";import"./index-wwy72tYD.js";import"./ReportRenderer-CYVI4V5b.js";import"./ComponentRenderer-Cehciup5.js";import"./purify.es-A66Cw1IH.js";import"./index-BlgLXpZm.js";import"./select-rZYtSqBm.js";import"./label-BCI0a7yt.js";import"./checkbox-xLFPyWUR.js";import"./progress-Cc_o4Eyb.js";import"./AttachResourceModal-BDMha_2m.js";import"./resourceService-DSO0VkCM.js";import"./integrationService-DIx-bRY5.js";import"./HtmlReportRenderer-CNKCvm6q.js";import"./support-DH_BpLH3.js";import"./resizable-BuJlV3Zx.js";import"./react-resizable-panels.browser.esm-CFwgg02q.js";const Ha=[[{text:"Understanding your requirements",icon:kt},{text:"Analyzing workflow patterns",icon:yt},{text:"Processing your request",icon:Ye}],[{text:"Designing task structure",icon:ss},{text:"Mapping data flows",icon:yt},{text:"Selecting optimal tools",icon:Tt},{text:"Building swimlane layout",icon:kt},{text:"Crafting AI instructions",icon:Ye}],[{text:"Fine-tuning the workflow",icon:Tt},{text:"Optimizing task dependencies",icon:yt},{text:"Almost there",icon:ss},{text:"Adding finishing touches",icon:Ye},{text:"Polishing the design",icon:kt}]];function Ya({text:s}){const[i,l]=n.useState(s),[a,d]=n.useState(!1);return n.useEffect(()=>{if(s!==i){d(!0);const y=setTimeout(()=>{l(s),d(!1)},200);return()=>clearTimeout(y)}},[s,i]),e.jsx("span",{className:`transition-opacity duration-200 ${a?"opacity-0":"opacity-100"}`,children:i})}function Ja({speed:s}){const i=Math.max(80,150-s);return e.jsx("span",{className:"inline-flex gap-0.5 ml-1",children:[0,1,2].map(l=>e.jsx("span",{className:"w-1.5 h-1.5 bg-purple-500 rounded-full animate-bounce",style:{animationDelay:`${l*i}ms`,animationDuration:`${Math.max(400,600-s*2)}ms`}},l))})}function Ka({icon:s,speed:i}){const l=Math.max(.8,1.5-i/100);return e.jsxs("div",{className:"relative",style:{animation:`pulse ${l}s ease-in-out infinite`},children:[e.jsx("div",{className:"absolute inset-0 bg-purple-400 rounded-full blur-md opacity-40"}),e.jsx("div",{className:"relative p-2 bg-gradient-to-br from-purple-500 to-blue-500 rounded-full",children:e.jsx(s,{className:"w-4 h-4 text-white"})})]})}function Xa({elapsedSeconds:s}){const i=Math.min(95,s/30*100);return e.jsx("div",{className:"w-full h-1 bg-slate-200 rounded-full overflow-hidden mt-3",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-purple-500 to-blue-500 transition-all duration-1000 ease-out",style:{width:`${i}%`}})})}function Za({startTime:s}){const[i,l]=n.useState(0),[a,d]=n.useState(0);n.useEffect(()=>{const f=s||new Date,_=setInterval(()=>{const v=Math.floor((new Date().getTime()-f.getTime())/1e3);l(v)},1e3);return()=>clearInterval(_)},[s]);const y=n.useMemo(()=>i<5?0:i<15?1:2,[i]),j=Ha[y];n.useEffect(()=>{const f=Math.max(2e3,4e3-i*100),_=setInterval(()=>{d(T=>{let v;do v=Math.floor(Math.random()*j.length);while(v===T%j.length&&j.length>1);return v})},f);return()=>clearInterval(_)},[j.length,i]);const C=j[a%j.length],w=Math.min(50,20+i*2);return e.jsx("div",{className:"bg-gradient-to-r from-slate-50 to-purple-50 rounded-lg px-4 py-4 border border-purple-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ka,{icon:C.icon,speed:w}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1 text-sm text-slate-700 font-medium min-h-[24px]",children:[e.jsx(Ya,{text:C.text}),e.jsx(Ja,{speed:w})]}),i>=10&&e.jsx("p",{className:"text-xs text-slate-400 mt-1 animate-fade-in",children:"Complex workflows take a moment to design properly"}),e.jsx(Xa,{elapsedSeconds:i})]})]})})}const ls={llm_call:{label:"AI",pillColor:"pink"},tool_call:{label:"Tool",pillColor:"sky"},human_review:{label:"Review",pillColor:"orange"}};function js({task:s,index:i}){const[l,a]=n.useState(!1),d=ls[s.task_type]||ls.llm_call,y=s.instructions||Object.keys(s.input_mapping||{}).length>0;return e.jsxs(Ee,{open:l,onOpenChange:j=>y&&a(j),className:"bg-white dark:bg-pc-bg rounded-lg border border-slate-200 dark:border-pc-border shadow-sm overflow-hidden",children:[e.jsx(Fe,{className:`w-full p-2.5 text-left ${y?"cursor-pointer hover:bg-slate-50 dark:hover:bg-pc-surface":"cursor-default"} transition-colors`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-slate-200 dark:bg-pc-surface text-[10px] font-bold text-slate-600 dar
1k:text-pc-text-2 flex-shrink-0 mt-0.5",children:i+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[13px] font-semibold text-slate-800 dark:text-pc-text truncate",children:s.name}),y&&e.jsx(Je,{className:`h-3 w-3 text-slate-400 dark:text-pc-text-3 transition-transform flex-shrink-0 ${l?"rotate-180":""}`})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[e.jsx(we,{variant:"custom",color:d.pillColor,size:"sm",showDot:!1,children:d.label}),s.tool_config?.tool_name&&e.jsx("span",{className:"text-[10px] text-slate-500 dark:text-pc-text-3 font-mono truncate",children:s.tool_config.tool_name})]})]})]})}),e.jsx(Me,{children:e.jsxs("div",{className:"px-2.5 pb-2.5 pt-0 border-t border-slate-100 dark:border-pc-border bg-slate-50/50 dark:bg-pc-surface/50 space-y-2",children:[s.instructions&&e.jsxs("div",{className:"mt-2",children:[e.jsx("span",{className:"font-semibold text-slate-500 dark:text-pc-text-3 text-[11px] uppercase tracking-wide",children:"Instructions"}),e.jsx("p",{className:"text-[12px] text-slate-700 dark:text-pc-text-2 mt-0.5 leading-relaxed overflow-hidden line-clamp-5",children:s.instructions})]}),Object.keys(s.input_mapping||{}).length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-slate-500 dark:text-pc-text-3 text-[11px] uppercase tracking-wide",children:"Inputs"}),e.jsx("div",{className:"mt-1 space-y-1",children:Object.entries(s.input_mapping).slice(0,3).map(([j,C])=>e.jsxs("div",{className:"flex items-center gap-1 text-[10px]",children:[e.jsx("code",{className:"font-mono bg-sky-100 dark:bg-sky-900/40 text-sky-700 dark:text-sky-400 px-1 py-0.5 rounded truncate max-w-[60px]",children:j}),e.jsx(wa,{className:"h-2 w-2 text-slate-400 dark:text-pc-text-4 flex-shrink-0"}),e.jsx("code",{className:"font-mono bg-slate-200 dark:bg-pc-surface-2 text-slate-600 dark:text-pc-text-2 px-1 py-0.5 rounded truncate max-w-[80px]",children:typeof C=="string"?C:"..."})]},j))})]})]})})]})}function en({swimlane:s,phaseNumber:i}){return e.jsxs("div",{className:"w-56 flex-shrink-0 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2.5 mb-3",children:[e.jsx("div",{className:"flex items-center justify-center w-7 h-7 rounded-lg bg-gradient-to-br from-slate-700 to-slate-900 dark:from-slate-600 dark:to-slate-800 text-white text-[12px] font-bold shadow",children:i}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-[13px] font-semibold text-slate-900 dark:text-pc-text truncate",children:s.name}),e.jsxs("p",{className:"text-[10px] text-slate-500 dark:text-pc-text-3",children:[s.tasks.length," task",s.tasks.length!==1?"s":""]})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[s.tasks.map((l,a)=>e.jsx(js,{task:l,index:a},a)),s.tasks.length===0&&e.jsx("div",{className:"flex items-center justify-center py-8 text-slate-400 dark:text-pc-text-4 text-[11px] italic border-2 border-dashed border-slate-200 dark:border-pc-border rounded-lg",children:"No tasks"})]})]})}function tn({branches:s,exitCriteria:i}){const[l,a]=n.useState(null);return e.jsxs("div",{className:"w-60 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2.5 mb-3",children:[e.jsx("div",{className:"flex items-center justify-center w-7 h-7 rounded-lg bg-pc-violet text-white shadow",children:e.jsx(fs,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"text-[13px] font-semibold text-pc-violet",children:"Conditional"}),e.jsxs("p",{className:"text-[10px] text-pc-violet/70",children:[s.length," paths"]})]})]}),e.jsx("div",{className:"space-y-2 p-3 bg-pc-violet/10 dark:bg-pc-violet/15 rounded-xl border border-pc-violet/20 dark:border-pc-violet/30",children:s.map(d=>{const y=i?.branches?.find(_=>_.target_swimlane_position===d.position),j=i?.default_branch?.target_swimlane_position===d.position,C=y?.label||(j?i?.default_branch?.label:null)||d.name,w=y?.condition,f=l===d.position;return e.jsxs(Ee,{open:f,onOpenChange:_=>a(_?d.position:null),className:"bg-white dark:bg-pc-surface rounded-lg border border-pc-violet/20 dark:border-pc-violet/30 overflow-hidden shadow-sm",children:[e.jsxs(Fe,{className:"w-full px-3 py-2 flex items-center gap-2 hover:bg-pc-violet/5 dark:hover:bg-pc-violet/10 transition-colors text-left",children:[e.jsx(ga,{className:"h-3.5 w-3.5 text-pc-violet/70 flex-shrink-0"}),e.jsx("span",{className:"text-[12px] font-medium text-slate-800 dark:text-pc-text flex-1 truncate",children:C}),j&&e.jsx("span",{className:"text-[8px] font-bold px-1.5 py-0.5 rounded bg-slate-100 dar
1k:bg-pc-surface-2 text-slate-500 dark:text-pc-text-3 uppercase",children:"Default"}),e.jsx("span",{className:"text-[10px] text-slate-400 dark:text-pc-text-4",children:d.tasks.length})]}),w&&e.jsx("div",{className:"px-3 pb-2 -mt-0.5",children:e.jsx("code",{className:"text-[9px] font-mono text-pc-violet bg-pc-violet/10 dark:bg-pc-violet/20 px-1.5 py-0.5 rounded block truncate",children:w.replace(/\$\.(state|run_input)\./,"").replace(/\s*==\s*/," = ")})}),e.jsx(Me,{children:d.tasks.length>0&&e.jsx("div",{className:"px-2 pb-2 pt-1 border-t border-pc-violet/10 dark:border-pc-violet/20 space-y-1.5",children:d.tasks.map((_,T)=>e.jsx(js,{task:_,index:T},T))})})]},d.position)})})]})}function sn({intent:s}){const[i,l]=n.useState(!1);return e.jsxs(Ee,{open:i,onOpenChange:l,className:"bg-white dark:bg-pc-surface border border-pc-border dark:border-pc-border rounded-lg overflow-hidden shadow-pc-1",children:[e.jsxs(Fe,{className:"w-full flex items-center gap-3 px-4 py-3 hover:bg-slate-50 dark:hover:bg-pc-surface-2 transition-colors text-left",children:[e.jsx(fa,{className:"h-4 w-4 text-pc-primary flex-shrink-0"}),e.jsx("span",{className:"text-[14px] font-semibold text-slate-800 dark:text-pc-text flex-1",children:"Intent"}),e.jsx($e,{className:`h-4 w-4 text-slate-400 dark:text-pc-text-3 transition-transform ${i?"rotate-90":""}`})]}),e.jsx(Me,{children:e.jsxs("div",{className:"px-4 pb-3 space-y-3 border-t border-pc-border dark:border-pc-border",children:[e.jsxs("div",{className:"pt-3",children:[e.jsx("span",{className:"text-[11px] font-semibold text-pc-violet uppercase tracking-wide",children:"Goal"}),e.jsx("span",{className:"block text-[12px] text-slate-700 dark:text-pc-text-2 leading-relaxed mt-1",children:s.statement})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[11px] font-semibold text-emerald-600 dark:text-emerald-400 uppercase tracking-wide",children:"Success"}),e.jsx("span",{className:"block text-[12px] text-slate-700 dark:text-pc-text-2 leading-relaxed mt-1",children:s.success})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[11px] font-semibold text-sky-600 dark:text-sky-400 uppercase tracking-wide",children:"Approach"}),e.jsx("span",{className:"block text-[12px] text-slate-700 dark:text-pc-text-2 leading-relaxed mt-1",children:s.approach})]})]})})]})}function an({configurations:s,values:i,onChange:l,onSave:a,isSaving:d,hasChanges:y}){const j=s.fields.filter(w=>!(!w.enabled||w.visibility==="preset_only"||w.visibility==="internal"));if(j.length===0)return e.jsx("div",{className:"text-center py-8 text-pc-text-3 text-sm",children:"No configurable fields available"});const C=j.filter(w=>{if(!(w.default===null||w.default===void 0))return!1;const _=i[w.key];return _==null||_===""||Array.isArray(_)&&_.length===0});return e.jsxs("div",{children:[e.jsx(Fa,{configurations:s,values:i,onChange:l}),C.length>0&&e.jsx("div",{className:"mt-4 p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-700",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ba,{className:"h-4 w-4 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-amber-800 dark:text-amber-300",children:"Required fields must be configured before running"}),e.jsx("p",{className:"text-xs text-amber-700 dark:text-amber-400 mt-1",children:C.map(w=>w.label).join(", ")})]})]})}),e.jsx("p",{className:"text-[11px] text-pc-text-4 mt-4",children:a?"Configure these values before running the agent. Save to apply changes.":"Configure these values before running the agent. Values will be saved when you start the test run."}),a&&e.jsx("div",{className:"mt-4 flex justify-end",children:e.jsx(L,{onClick:a,disabled:d||!y,size:"sm",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Ve,{className:"h-4 w-4 animate-spin mr-2"})," Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ja,{className:"h-4 w-4 mr-2"})," Save Configuration"]})})})]})}function nn({knowledge:s}){const[i,l]=n.useState(!1),a=f=>f==null?"":typeof f=="object"?JSON.stringify(f):String(f),d=s&&typeof s=="object"?s:{},y=Array.isArray(d.good_examples)?d.good_examples:[],j=Array.isArray(d.careful_zones)?d.careful_zones:[],C=Array.isArray(d.known_limitations)?d.known_limitations:[],w=[y.length>0&&`${y.length} examples`,j.length>0&&`${j.length}
1 zones`,C.length>0&&`${C.length} limitations`].filter(Boolean).join(" · ");return e.jsxs(Ee,{open:i,onOpenChange:l,className:"bg-white dark:bg-pc-surface border border-pc-border dark:border-pc-border rounded-lg overflow-hidden shadow-pc-1",children:[e.jsxs(Fe,{className:"w-full flex items-center gap-3 px-4 py-3 hover:bg-slate-50 dark:hover:bg-pc-surface-2 transition-colors text-left",children:[e.jsx(xa,{className:"h-4 w-4 text-pc-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-[14px] font-semibold text-slate-800 dark:text-pc-text",children:"Knowledge"}),w&&e.jsx("span",{className:"ml-2 text-[11px] text-slate-500 dark:text-pc-text-3",children:w})]}),e.jsx($e,{className:`h-4 w-4 text-slate-400 dark:text-pc-text-3 transition-transform ${i?"rotate-90":""}`})]}),e.jsx(Me,{children:e.jsxs("div",{className:"px-4 pb-3 space-y-3 border-t border-pc-border dark:border-pc-border",children:[y.length>0&&e.jsxs("div",{className:"pt-3",children:[e.jsx("span",{className:"text-[11px] font-semibold text-emerald-600 dark:text-emerald-400 uppercase tracking-wide",children:"Good Examples"}),e.jsx("div",{className:"mt-1.5 space-y-2",children:y.map((f,_)=>e.jsxs("div",{className:"bg-slate-50 dark:bg-pc-surface-2 rounded-lg p-2.5 leading-relaxed overflow-hidden",children:[e.jsx("span",{className:"block text-[12px] font-medium text-slate-700 dark:text-pc-text break-words",children:a(f.scenario)}),e.jsxs("span",{className:"block text-[12px] text-slate-600 dark:text-pc-text-2 mt-1 break-all",children:[e.jsx("span",{className:"font-medium",children:"In:"})," ",a(f.input)]}),e.jsxs("span",{className:"block text-[12px] text-slate-600 dark:text-pc-text-2 break-all",children:[e.jsx("span",{className:"font-medium",children:"Out:"})," ",a(f.expected_output)]})]},_))})]}),j.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[11px] font-semibold text-amber-600 dark:text-amber-400 uppercase tracking-wide",children:"Careful Zones"}),e.jsx("div",{className:"mt-1.5 space-y-2",children:j.map((f,_)=>e.jsxs("div",{className:"bg-slate-50 dark:bg-pc-surface-2 rounded-lg p-2.5 leading-relaxed overflow-hidden",children:[e.jsx("span",{className:"block text-[12px] font-medium text-slate-700 dark:text-pc-text break-words",children:a(f.scenario)}),e.jsxs("span",{className:"block text-[12px] text-slate-600 dark:text-pc-text-2 mt-1 break-words",children:[e.jsx("span",{className:"font-medium",children:"Risk:"})," ",a(f.risk)]})]},_))})]}),C.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[11px] font-semibold text-slate-500 dark:text-pc-text-3 uppercase tracking-wide",children:"Limitations"}),e.jsx("div",{className:"mt-1.5 space-y-2",children:C.map((f,_)=>e.jsx("div",{className:"bg-slate-50 dark:bg-pc-surface-2 rounded-lg p-2.5 leading-relaxed overflow-hidden",children:e.jsx("span",{className:"block text-[12px] text-slate-700 dark:text-pc-text-2 break-words",children:a(f.limitation)})},_))})]})]})})]})}function rn({schema:s}){if(!s?.properties||Object.keys(s.properties).length===0)return null;const i=s.required||[];return e.jsxs("div",{className:"bg-white dark:bg-pc-surface border border-pc-border dark:border-pc-border rounded-lg px-4 py-3 shadow-pc-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsx(ha,{className:"h-4 w-4 text-pc-primary"}),e.jsx("span",{className:"text-[14px] font-semibold text-slate-800 dark:text-pc-text",children:"Required Inputs"})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(s.properties).map(([l,a])=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 bg-slate-50 dark:bg-pc-surface-2 border border-pc-border dark:border-pc-border rounded-lg text-[11px]",children:[e.jsx("span",{className:"font-medium text-slate-700 dark:text-pc-text",children:a.displayName||l}),e.jsx("span",{className:"text-[10px] font-mono text-slate-400 dark:text-pc-text-4",children:a.type}),i.includes(l)&&e.jsx("span",{className:"text-pc-error font-bold",children:"*"})]},l))})]})}function ln({boardDraft:s,configurations:i,configValues:l,onConfigValuesChange:a,onSaveConfig:d,isSavingConfig:y}){const[j,C]=n.useState("overview"),[w,f]=n.useState({}),[_,T]=n.useState(!1),v=s.swimlanes.reduce((B,S)=>B+S.tasks.length,0),J=i??s.configurations,V=l??w;n.useEffect(()=>{if(!J?.fields||l&&Object.keys(l).length>0)return;const B={};for(const S of J.fields)S.enabled&&S.default!==void 0&&(B[S.key]=S.default);a?a(B):f(B),T(!1)},[J,l]);const M=(B,S)=>{const D={...V,[B]:S};a?a(D):f(D),T(!0)},E=async()=>
1{if(!d||!J?.fields)return;const B=J.fields.filter(S=>S.enabled&&V[S.key]!==void 0).map(S=>({key:S.key,value:V[S.key],targets:S.targets}));await d(B),T(!1)},N=J?.fields?.some(B=>B.enabled&&B.visibility!=="preset_only"&&B.visibility!=="internal"),U=[],Q=new Set,q=[...s.swimlanes].sort((B,S)=>B.position-S.position);for(let B=0;B<q.length;B++){const S=q[B];if(S.branch_group){if(!Q.has(S.branch_group)){Q.add(S.branch_group);const D=q.filter(X=>X.branch_group===S.branch_group),H=Math.min(...D.map(X=>X.position)),ie=q.filter(X=>!X.branch_group&&X.position<H&&X.exit_criteria?.type==="conditional_routing").pop();U.push({type:"branch_group",swimlanes:D,exitCriteria:ie?.exit_criteria})}}else U.push({type:"swimlane",swimlane:S,index:B})}let ce=0;return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900 dark:text-pc-text leading-tight mb-1.5",children:s.name}),e.jsx("p",{className:"text-[13px] text-slate-600 dark:text-pc-text-2 leading-relaxed",children:s.description})]}),N&&e.jsx("div",{className:"mb-5",children:e.jsx(Aa,{variant:"boxed",value:j,onValueChange:B=>C(B),children:e.jsxs(Ea,{children:[e.jsx(ns,{value:"overview",children:"Overview"}),e.jsx(ns,{value:"configuration",children:"Configuration"})]})})}),j==="overview"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2 mb-5",children:[s.intent&&e.jsx(sn,{intent:s.intent}),s.knowledge&&e.jsx(nn,{knowledge:s.knowledge}),s.input_schema&&e.jsx(rn,{schema:s.input_schema})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline gap-2 mb-3",children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-pc-text-3",children:"Workflow"}),e.jsxs("span",{className:"text-[11px] text-slate-400 dark:text-pc-text-3",children:[s.swimlanes.length," lanes • ",v," tasks"]})]}),e.jsx(Ra,{className:"pb-4",children:e.jsx("div",{className:"inline-flex items-start gap-4",children:U.map((B,S)=>B.type==="branch_group"?e.jsx(tn,{branches:B.swimlanes,exitCriteria:B.exitCriteria},`branch-${S}`):(ce++,e.jsx(en,{swimlane:B.swimlane,phaseNumber:ce},S)))})}),s.swimlanes.length===0&&e.jsxs("div",{className:"text-center py-12 text-slate-400 dark:text-pc-text-4",children:[e.jsx(ma,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-[13px]",children:"No phases defined yet"})]})]})]}):J&&e.jsx(an,{configurations:J,values:V,onChange:M,onSave:d?E:void 0,isSaving:y,hasChanges:_})]})}function on({status:s}){const i={pending:{variant:"neutral",icon:e.jsx(Na,{strokeWidth:2.5})},running:{variant:"running",icon:e.jsx(Ve,{strokeWidth:2.5,className:"animate-spin"})},completed:{variant:"success",icon:e.jsx(ya,{strokeWidth:2.5})},failed:{variant:"error",icon:e.jsx(ka,{strokeWidth:2.5})},skipped:{variant:"neutral",icon:e.jsx(va,{strokeWidth:2.5})}},{variant:l,icon:a}=i[s];return e.jsxs(we,{variant:l,showDot:!1,children:[a,s]})}function lt(s,i){if(!s||!i)return"-";const l=new Date(s).getTime(),d=new Date(i).getTime()-l;if(d<1e3)return`${d}ms`;const y=Math.floor(d/1e3);if(y<60)return`${y}s`;const j=Math.floor(y/60),C=y%60;if(j<60)return C>0?`${j}m ${C}s`:`${j}m`;const w=Math.floor(j/60),f=j%60;return f>0?`${w}h ${f}m`:`${w}h`}function ws(s){const i=new Map;for(const l of s.swimlanes||[])for(const a of l.tasks||[])i.set(a.task_id,a),a.name&&i.set(a.name,a);return i}function vs(s,i,l){const a=new Map,d=new Map;for(const w of s)w.task_id&&a.set(w.task_id,w),w.task_name&&d.set(w.task_name,w);const y=[],j=new Set;for(const w of i.swimlanes||[]){const f=[];for(const _ of w.tasks||[]){const T=a.get(_.task_id)??d.get(_.name);T&&(f.push(T),j.add(T.execution_id))}f.length>0&&y.push({swimlane:w,executions:f})}const C=s.filter(w=>!j.has(w.execution_id));return C.length>0&&y.push({swimlane:{swimlane_id:"_orphaned",board_id:"",name:"Other Tasks",instructions:"",position:999,tasks:[],exit_criteria:{type:"all_tasks_success",condition:null,on_failure:"stop"},created_at:"",updated_at:""},executions:C}),y}function ot(s,i=500){if(s==null)return"-";const l=typeof s=="string"?s:JSON.stringify(s,null,2);return l.length<=i?l:l.slice(0,i)+`
2... (truncated)`}function cn(s,i){const l=ws(i),a=s.task_executions||[],d=a.filter(v=>v.status==="completed").length,y=a.filter(v=>v.status==="failed").length,j=a.filter(v=>v.status==="skipped").length,C=a.length,w=lt(s.started_at,s.completed_at);let f=`## Test Run Trace (run_id: ${s.run_id})
3`;f+=`Status: ${s.status.toUpperCase()} | ${d}/${C} tasks completed, ${y} failed${j>0?`, ${j} not reached`:""} | Duration: ${w}
4
5`;const _=vs(a,i);let T=0;return _.forEach((v,J)=>{const V=v.executions.filter(E=>E.status==="completed").length,M=v.executions.filter(E=>E.status==="failed").length;f+=`### Swimlane ${J+1}: "${v.swimlane.name}" (${V}/${v.executions.length} passed${M>0?`, ${M} failed`:""})
6`,v.executions.forEach(E=>{T++;const N=E.task_id?l.get(E.task_id):null,U=N?.task_type||"unknown",Q=N?.tool_config&&typeof N.tool_config=="object"?N.tool_config.tool_name:null,q=Q?`${U}: ${Q}`:U,ce=lt(E.started_at,E.completed_at);if(f+=`#### Task ${T}: "${E.task_name||"Unknown"}" [${q}] -- ${E.status.toUpperCase()} (${ce})
7`,N?.dependencies&&N.dependencies.length>0){const B=N.dependencies.map(S=>l.get(S.target_task_id)?.name||"?").join(", ");f+=`  Depends on: ${B}
8`}E.input_data&&Object.keys(E.input_data).length>0&&(f+=`  Inputs: ${ot(E.input_data)}
9`),E.output_data&&(E.status==="completed"||E.status==="failed")&&(f+=`  Output: ${ot(E.output_data)}
10`),E.status==="failed"&&E.error_message&&(f+=`  Error: "${E.error_message}"
11`),f+=`
12`})}),f.trimEnd()}function os({execution:s,task:i,taskLookup:l}){const[a,d]=n.useState(s.status==="failed"),y=i?.task_type||"unknown",j=i?.tool_config&&typeof i.tool_config=="object"?i.tool_config.tool_name:null,C=lt(s.started_at,s.completed_at),w=i?.dependencies&&i.dependencies.length>0&&l?i.dependencies.map(_=>l.get(_.target_task_id)?.name).filter(Boolean).join(", "):null,f=y==="tool_call"?e.jsx(Sa,{className:"w-3 h-3"}):y==="llm_call"?e.jsx(Ca,{className:"w-3 h-3"}):e.jsx($a,{className:"w-3 h-3"});return e.jsxs(Ee,{open:a,onOpenChange:d,className:"border rounded-lg overflow-hidden",children:[e.jsxs(Fe,{className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-slate-50 transition-colors",children:[a?e.jsx(Je,{className:"w-3.5 h-3.5 text-muted-foreground flex-shrink-0"}):e.jsx($e,{className:"w-3.5 h-3.5 text-muted-foreground flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium truncate block",children:s.task_name||"Unknown Task"}),w&&e.jsxs("span",{className:"text-[11px] text-muted-foreground truncate block",children:["depends on: ",w]})]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs text-muted-foreground flex-shrink-0",children:[f,j||y]}),e.jsx(on,{status:s.status}),C!=="-"&&e.jsx("span",{className:"text-xs text-muted-foreground flex-shrink-0",children:C})]}),e.jsx(Me,{children:e.jsxs("div",{className:"border-t bg-slate-50/50 px-3 py-2 space-y-2",children:[s.input_data&&Object.keys(s.input_data).length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Input"}),e.jsx("pre",{className:"text-xs bg-white border rounded p-2 overflow-auto max-h-40 whitespace-pre-wrap",children:ot(s.input_data,1e3)})]}),s.status==="completed"&&s.output_data&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Output"}),e.jsx("pre",{className:"text-xs bg-white border rounded p-2 overflow-auto max-h-40 whitespace-pre-wrap",children:ot(s.output_data,1e3)})]}),s.error_message&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-pc-error mb-1",children:"Error"}),e.jsx("pre",{className:"text-xs bg-pc-error-bg border border-pc-error-border rounded p-2 overflow-auto max-h-40 whitespace-pre-wrap text-pc-error",children:s.error_message})]})]})})]})}function dn({run:s,board:i,onFixWithAI:l,onRunAgain:a,onDismiss:d}){const[y,j]=n.useState(""),[C,w]=n.useState(!1),f=n.useMemo(()=>ws(i),[i]),_=s.task_executions||[],T=_.filter(Q=>Q.status==="completed").length,v=_.filter(Q=>Q.status==="failed").length,J=_.filter(Q=>Q.status==="skipped").length,V=_.length,M=["completed","failed","cancelled"].includes(s.status),E=lt(s.started_at,s.completed_at),N=n.useMemo(()=>vs(_,i),[_,i,f]),U=()=>{if(!l)return;const Q=cn(s,i),q=y.trim()?`${y.trim()}
13
14${Q}`:`Fix the issues found in the test run:
15
16${Q}`;l(q),j("")};return e.jsxs(Ee,{open:!C,onOpenChange:Q=>w(!Q),className:"border rounded-lg bg-white dark:bg-pc-surface shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-pc-border",children:[e.jsxs(Fe,{className:"flex-1 flex items-center justify-between hover:bg-slate-50 dark:hover:bg-pc-surface-2 transition-colors cursor-pointer -mx-4 -my-3 px-4 py-3 rounded-t-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Je,{className:`w-4 h-4 text-muted-foreground transition-transform ${C?"-rotate-90":""}`}),e.jsx("h3",{className:"text-sm font-semibold",children:"Test Run Results"}),e.jsx(za,{status:s.status})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[T,"/",V," passed",v>0&&e.jsxs("span",{className:"text-pc-error ml-1",children:["(",v," failed)"]}),J>0&&e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",J," not reached)"]})]}),E!=="-"&&e.jsx("span",{children:E})]})]}),d&&e.jsx(L,{variant:"ghost",size:"icon",onClick:d,className:"ml-2 flex-shrink-0",children:e.jsx(xs,{})})]}),e.jsxs(Me,{children:[e.jsxs("div",{className:"p-3 space-y-3 max-h-[400px] overflow-y-auto",children:[_.length===0&&!M&&e.jsx("div",{className:"text-sm text-muted-foreground text-center py-4",children:"Waiting for tasks to start..."}),(()=>{const Q=new Set,q=[...i.swimlanes||[]].sort((D,H)=>D.position-H.position),ce=new Map;for(const D of q)if(D.branch_group&&(Q.add(D.swimlane_id),!ce.has(D.branch_group))){const H=q.filter(O=>O.branch_group===D.branch_group),ie=Math.min(...H.map(O=>O.position)),X=q.filter(O=>!O.branch_group&&O.position<ie&&O.exit_criteria?.type==="conditional_routing").pop();ce.set(D.branch_group,{sourceSwimlanId:X?.swimlane_id||"",swimlaneIds:new Set(H.map(O=>O.swimlane_id))})}const B=D=>D.replace(/\$\.(state|run_input)\./,"").replace(/\s*==\s*/," = "),S=new Set;return N.map(D=>{const H=D.swimlane,ie=D.executions.filter(O=>O.status==="completed").length,X=D.executions.filter(O=>O.status==="failed").length;if(H.branch_group&&!S.has(H.branch_group)){S.add(H.branch_group);const O=ce.get(H.branch_group),me=O?.sourceSwimlanId?s.routing_decisions?.[O.sourceSwimlanId]:null,I=q.find(R=>R.swimlane_id===O?.sourceSwimlanId)?.exit_criteria,z=N.filter(R=>O?.swimlaneIds.has(R.swimlane.swimlane_id)),ae=me?z.find(R=>R.swimlane.position===me.target_position):z.find(R=>R.executions.length>0)||null,de=ae?.swimlane.position,Oe=I?.branches?.find(R=>R.target_swimlane_position===de),Ne=Oe?B(Oe.condition):I?.default_branch?.target_swimlane_position===de?"Default path":null,P=Oe?.label||(I?.default_branch?.target_swimlane_position===de?I?.default_branch?.label:null)||me?.branch_taken;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx(fs,{className:"w-3.5 h-3.5 text-pc-violet flex-shrink-0"}),e.jsx("span",{className:"text-xs font-semibold text-pc-violet uppercase tracking-wide",children:P||(ae?ae.swimlane.name:"Routing")}),Ne&&e.jsx("span",{className:"text-[10px] font-mono text-pc-violet/60",children:Ne}),me?.is_board_chain&&e.jsxs("div",{className:"flex items-center gap-1 text-[10px] text-indigo-600",children:[e.jsx(Nt,{className:"w-3 h-3"}),e.jsx("span",{children:"Board chain"})]})]}),me?.is_board_chain?e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-indigo-50 border border-indigo-200 rounded-lg text-sm",children:[e.jsx(Nt,{className:"w-4 h-4 text-indigo-500 flex-shrink-0"}),e.jsx("span",{className:"text-indigo-700",children:"Run completed — chained to target board"})]}):ae&&ae.executions.map(R=>e.jsx(os,{execution:R,task:R.task_id?f.get(R.task_id)??f.get(R.task_name??""):f.get(R.task_name??""),taskLookup:f},R.execution_id)),(()=>{const fe=q.filter(ne=>O?.swimlaneIds.has(ne.swimlane_id)).filter(ne=>ne.swimlane_id!==ae?.swimlane.swimlane_id);return fe.length===0?null:e.jsx("div",{className:"pl-2 space-y-0.5",children:fe.map(ne=>{const re=I?.branches?.find(xe=>xe.target_swimlane_position===ne.position)?.label||(I?.default_branch?.target_swimlane_position===ne.position?I?.default_branch?.label:ne.name),be=!!I?.branches?.find(xe=>xe.target_swimlane_position===ne.position)?.target_board_id||I?.default_branch?.target_swimlane_position===ne.position&&!!I?.default_branch?.target_board_id;return e.jsx("div",{className:"flex items-center gap-1.5 py-0.5",children:be?e.jsxs(e.Fragment,{children:[e.jsx(Nt,{className:"w-2.5 h-2.5 text-indigo-300 flex-shrink-0"}),e.jsx("span",{className:"text-[11px] text-slate-400",children:re}),e.jsx("span",{className:"text-[10px] text-indigo-400",children:"(board chain — not taken)"})]}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"w-2.5 h-2.5 text-slate-300 flex-shrink-0"}),e.jsx("span",{className:"text-[11px] text-slate-400",children:re}),e.jsx("span",{className:"text-[10px] text-slate-300",children:"— not required"})]})},ne.swimlane_id)})})})()]},`branch-${H.branch_group}`)}return H.branch_group&&S.has(H.branch_group)?null:e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx("span",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:H.name}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[ie,"/",D.executions.length,X>0&&e.jsxs("span",{className:"text-pc-error ml-1",children:["(",X," failed)"]})]})]}),D.executions.map(O=>e.jsx(os,{execution:O,task:O.task_id?f.get(O.task_id)??f.get(O.task_name??""):f.get(O.task_name??""),taskLookup:f},O.execution_id))]},H.swimlane_id)})})()]}),M&&e.jsxs("div",{className:"border-t px-4 py-3 space-y-3",children:[l&&s.status==="failed"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(qa,{value:y,onChange:Q=>j(Q.target.value),placeholder:"Describe what to fix or leave blank for auto-fix...",className:"text-sm min-h-[60
16px] resize-none",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(L,{size:"sm",onClick:U,className:"gap-1.5",children:[e.jsx(Ye,{className:"w-3.5 h-3.5"}),"Fix with AI"]}),a&&e.jsxs(L,{size:"sm",variant:"outline",onClick:a,className:"gap-1.5",children:[e.jsx(Dt,{className:"w-3.5 h-3.5"}),"Run Again"]})]})]}),a&&(s.status==="completed"||!l)&&e.jsxs(L,{size:"sm",variant:"outline",onClick:a,className:"gap-1.5",children:[e.jsx(Dt,{className:"w-3.5 h-3.5"}),"Run Again"]})]})]})]})}function un(s){const i=new Date,l=new Date(s),a=Math.floor((i.getTime()-l.getTime())/6e4);if(a<1)return"just now";if(a<60)return`${a}m ago`;const d=Math.floor(a/60);if(d<24)return`${d}h ago`;const y=Math.floor(d/24);if(y<30)return`${y}d ago`;const j=Math.floor(y/30);return j<12?`${j}mo ago`:`${Math.floor(j/12)}y ago`}function pn({spec:s,onBuild:i,onFinish:l}){const a=s.status==="ready";return e.jsxs("div",{className:"flex-1 min-w-0 p-4 rounded-pc-md bg-pc-surface border border-pc-border flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[e.jsxs("span",{className:`inline-flex items-center gap-1.5 font-semibold uppercase tracking-wide ${a?"text-pc-success":"text-pc-warning"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${a?"bg-pc-success":"bg-pc-warning"}`}),a?"Ready":"Draft"]}),e.jsx("span",{className:"text-pc-text-4",children:"·"}),e.jsx("span",{className:"text-pc-text-4",children:un(s.updatedAt)})]}),e.jsx("span",{className:"text-[15px] font-semibold text-pc-text line-clamp-2 leading-snug",children:s.title||"Untitled spec"}),e.jsx("div",{className:"flex items-center justify-end mt-auto pt-1",children:a?e.jsx(L,{variant:"link",size:"sm",onClick:()=>i(s.id,s.title||"Untitled spec"),children:"View spec"}):e.jsx(L,{variant:"link",size:"sm",onClick:()=>l(s.id),children:"Resume"})})]})}function mn({board:s,onView:i,onCustomize:l}){return e.jsxs("div",{className:"bg-pc-surface border border-pc-border rounded-pc-md p-5 flex flex-col gap-3 w-full",children:[e.jsx("h3",{className:"text-[15px] font-semibold text-pc-text leading-snug line-clamp-2 min-h-[2.5rem]",children:s.name}),e.jsx("p",{className:"text-[13px] text-pc-text-3 line-clamp-2 leading-relaxed min-h-[2.5rem]",children:s.description||"No description"}),s.flow_steps.length>0&&e.jsx("div",{className:"overflow-x-auto [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]",children:e.jsx("div",{className:"flex items-center gap-1.5 min-w-0 pb-0.5",children:s.flow_steps.map((a,d)=>e.jsxs(It.Fragment,{children:[e.jsx("span",{className:"px-2 py-0.5 rounded-full border border-pc-border bg-pc-surface text-[9px] font-medium text-pc-text-2 whitespace-nowrap flex-shrink-0",children:a.label}),d<s.flow_steps.length-1&&e.jsx("span",{className:"text-pc-text-4 text-[9px] flex-shrink-0",children:"→"})]},d))})}),e.jsxs("div",{className:"flex items-center justify-between mt-auto pt-2.5 border-t border-pc-border/50",children:[e.jsx(L,{variant:"ghost",size:"sm",onClick:()=>i(s.board_id),children:"View agent"}),e.jsx(L,{variant:"link",size:"sm",onClick:()=>l(s.board_id),children:"Customize"})]})]})}function fn(s){const i=new Date,l=new Date(s),a=Math.floor((i.getTime()-l.getTime())/6e4);if(a<1)return"just now";if(a<60)return`${a}m ago`;const d=Math.floor(a/60);if(d<24)return`${d}h ago`;const y=Math.floor(d/24);if(y<30)return`${y}d ago`;const j=Math.floor(y/30);return j<12?`${j}mo ago`:`${Math.floor(j/12)}y ago`}function xn({build:s,onResume:i,onDeploy:l}){const a=s.is_complete;return e.jsxs("div",{className:"flex-1 min-w-0 p-4 rounded-pc-md bg-pc-surface border border-pc-border flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[e.jsxs("span",{className:`inline-flex items-center gap-1.5 font-semibold uppercase tracking-wide ${a?"text-pc-success":"text-pc-warning"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${a?"bg-pc-success":"bg-pc-warning"}`}),a?"Build ready":"In progress"]}),s.mode==="edit"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-pc-text-4",children:"·"}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 font-semibold uppercase tracking-wide text-pc-primary",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-pc-primary"}),"Edit"]})]}),s.mode==="fix"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-pc-text-4",children:"·"}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 font-semibold uppercase tracking-wide text-pc-pink",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-pc-pink"}),"Fix"]})]}),e.jsx("span",{className:"text-pc-text-4",children:"·"}),e.jsx("span",{className:"text-pc-text-4",children:fn(s.updated_at)})]}),e.jsx("span",{className:"text-[15px] font-semibold text-pc-text line-clamp-2 leading-snug",children:s.title||"Untitled build"}),e.jsxs("div",{className:"flex items-center justify-between mt-auto pt-1",children:[e.jsx(L,{variant:"ghost",size:"sm",onClick:()=>i(s.id),children:"Resume"}),a&&e.jsx(L,{variant:"link",size:"sm",onClick:()=>l(s.id),children:"Deploy"})]})]})}function $t({label:s,sub:i,action:l}){return e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-pc-text-3",children:s}),i&&e.jsx("span",{className:"text-xs text-pc-text-4",children:i})]}),l]})}function hn({specs:s,popularBoards:i,recentBuilds:l,totalBuildCount:a,isLoadingBuilds:d=!1,totalBoardCount:y,onBuildFromSpec:j,onFinishSpec:C,onViewAllSpecs:w,onViewBoard:f,onCustomizeBoard:_,onViewAllBoards:T,onResumeBuild:v,onDeployBuild:J,onScratchBuild:V,initialInputValue:M="",initialInputTrigger:E=0,attachedSpec:N,onRemoveAttachedSpec:U}){const Q=ms(),[q,ce]=n.useState(M),[B,S]=n.useState([]),D=n.useRef([]),H=n.useRef(null),ie=n.useRef(null);It.useEffect(()=>{ie.current?.focus()},[]),It.useEffect(()=>{M&&(ce(M),ie.current?.focus())},[M,E]);const X=()=>{const I=q.trim(),z=D.current;if(I||N||z.length>0){let ae=I;N&&(ae=I?`${I}
17
18${N.content}`:`Build an agent from the attached spec:
19
20${N.content}`),V(ae,z.length?z:void 0),ce(""),D.current=[],S([]),U?.()}}
20,O=I=>{I.key==="Enter"&&!I.shiftKey&&(I.preventDefault(),X())},me=I=>{if(I.target.files){const z=[...D.current,...Array.from(I.target.files)];D.current=z,S(z)}I.target.value=""},Z=q.trim().length>0||!!N;return e.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[e.jsx("div",{className:"flex-1 overflow-auto chat-scroll py-6",children:e.jsxs("div",{className:"max-w-page-content mx-auto w-full",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("h2",{className:"text-[22px] font-semibold text-pc-text tracking-tight",children:"What will you automate first?"}),e.jsx("p",{className:"text-[13.5px] text-pc-text-3 mt-2",children:"Pick a spec, adapt an example, or describe something new below."})]}),e.jsxs("div",{className:"mb-10",children:[e.jsx($t,{label:"Your recent builds",action:l.length>0?e.jsxs(L,{variant:"link",size:"sm",onClick:()=>Q("/factory/history"),children:["All builds (",a,") ",e.jsx($e,{className:"w-3 h-3"})]}):null}),d?e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(I=>e.jsxs("div",{className:"flex-1 min-w-0 p-4 rounded-pc-md bg-pc-surface border border-pc-border flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-12 h-3 bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse"}),e.jsx("div",{className:"w-1 h-1 bg-slate-200 dark:bg-pc-surface-2 rounded-full"}),e.jsx("div",{className:"w-10 h-3 bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse"})]}),e.jsx("div",{className:"w-full h-5 bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse"}),e.jsx("div",{className:"w-3/4 h-5 bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse"}),e.jsx("div",{className:"flex items-center justify-end mt-auto pt-1",children:e.jsx("div",{className:"w-16 h-6 bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse"})})]},I))}):l.length===0?e.jsxs("div",{className:"border-2 border-dashed border-pc-border rounded-pc-md p-6 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 mb-1",children:[e.jsx(Tt,{className:"w-5 h-5 text-pc-text-4"}),e.jsx("p",{className:"text-lg font-medium text-pc-text-3",children:"No builds yet"})]}),e.jsx("p",{className:"text-xs text-pc-text-4",children:"Describe a workflow below to start your first build"})]}):e.jsx("div",{className:"grid grid-cols-3 gap-4",children:l.slice(0,3).map(I=>e.jsx(xn,{build:I,onResume:v,onDeploy:J},I.id))})]}),i.length>0&&e.jsxs("div",{className:"mb-10",children:[e.jsx($t,{label:"Popular in Agent Crew",sub:"already running at your firm — make one yours",action:e.jsxs(L,{variant:"link",size:"sm",onClick:T,children:["All agents (",y||i.length,") ",e.jsx($e,{className:"w-3 h-3"})]})}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:i.map(I=>e.jsx(mn,{board:I,onView:f,onCustomize:_},I.board_id))})]}),e.jsxs("div",{className:"mb-10",children:[e.jsx($t,{label:"Your Specs",action:s.length>0?e.jsxs(L,{variant:"link",size:"sm",onClick:w,children:["All specs (",s.length,") ",e.jsx($e,{className:"w-3 h-3"})]}):null}),s.length===0?e.jsxs("div",{className:"border-2 border-dashed border-pc-border rounded-pc-md p-6 relative",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 mb-1",children:[e.jsx(Ia,{className:"w-5 h-5 text-pc-text-4"}),e.jsx("p",{className:"text-lg font-medium text-pc-text-3",children:"No specs yet"})]}),e.jsx("p",{className:"text-xs text-pc-text-4 text-center",children:"Define your agent requirements before building"}),e.jsxs(L,{variant:"ghost",size:"sm",onClick:w,className:"absolute right-6 bottom-6",children:["Start a Spec ",e.jsx($e,{className:"w-3 h-3"})]})]}):e.jsx("div",{className:"grid grid-cols-3 gap-4",children:s.slice(0,3).map(I=>e.jsx(pn,{spec:I,onBuild:j,onFinish:C},I.id))})]})]})}),e.jsx("div",{className:"flex-shrink-0 sticky bottom-0 bg-pc-bg pb-6",children:e.jsx("div",{className:"max-w-page-content mx-auto w-full",children:e.jsxs("div",{className:"bg-pc-surface border border-pc-border rounded-pc-md shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"bg-pc-primary/[0.08] border-b border-pc-primary/[0.12] px-6 py-4 flex items-center gap-2",children:[e.jsx(Ye,{className:"w-4 h-4 text-pc-primary flex-shrink-0"}),e.jsx("span",{className:"text-sm font-medium text-pc-primary whitespace-nowrap",children:"Build Kitt"}),e.jsx("span",{className:"text-pc-primary/50 flex-shrink-0",children:"•"}),e.jsx("span",{className:"text-xs font-medium text-pc-primary/70 truncate",children:"Describe any workflow — Kitt builds it into an agent."})]}),e.jsx(bs,{ref:H,multiple:!0,onChange:me}),e.jsxs("div",{className:"relative bg-white dark:bg-pc-surface rounded-b-pc-md",children:[(N||B.length>0)&&e.jsxs("div",{className:"flex flex-wrap gap-2 px-4 pt-3 pb-1",children:[N&&e.jsxs("div",{className:"inline-flex items-center gap-2.5 bg-pc-chart-grid/30 border border-pc-chart-grid rounded-lg px-3 py-2",children:[e.jsx(it,{className:"w-4 h-4 text-pc-text-3 flex-shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[9px] font-semibold uppercase tracking-wide text-pc-text-3",children:"Spec attached"}),e.jsx("div",{className:"text-[13px] font-medium text-pc-text max-w-[200px] truncate",children:N.title})]}),e.jsx(L,{variant:"outline",size:"icon",onClick:()=>U?.(),children:e.jsx(xs,{className:"w-3.5 h-3.5"})})]}),B.map((I,z)=>e.jsxs(we,{variant:"running",showDot:!1,className:"normal-case",onRemove:()=>{const ae=D.current.filter((de,Oe)=>Oe!==z);D.current=ae,S(ae)},children:[e.jsx(it,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"max-w-[140px] truncate",children:I.name})]},z))]}),e.jsx("textarea",{ref:ie,value:q,onChange:I=>ce(I.target.value),onKeyDown:O,placeholder:"e.g. Every Monday, pull new accounts from Redtail CRM and generate a welcome email sequence...",rows:1,className:`
21                  w-full resize-none bg-transparent text-[14px] text-pc-text
22                  placeholder:text-pc-text-4 outline-none
23                  px-4 py-3.5
24                  min-h-[52px] max-h-[200px]
25                  ${B.length>0||N?"pt-2":""}
26                `,style:{fieldSizing:"content"}}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-3",children:[e.jsx("div",{className:"flex items-center gap-1",children:e.jsx(L,{variant:"ghost",size:"icon",onClick:()=>H.current?.click(),children:e.jsx(hs,{})})}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(L,{onClick:X,disabled:!Z,children:["Send",e.jsx(gs,{})]})})]})]})]})})})]})}const cs="/api/factory",gn="/api/prd",ds={async getPopularBoards(){const s=await vt.get(`${cs}/popular-boards`);return!s.success||!s.data?[]:s.data},async getExamples(){const s=await vt.get(`${cs}/examples`);return!s.success||!s.data?[]:s.data},async getSpecs(){const s=await vt.get(`${gn}/conversations`);return!s.success||!s.data?[]:s.data.map(i=>({id:i.id,title:i.title,status:i.status==="ready"||i.status==="draft"?i.status:i.is_complete||i.has_generated_prd?"ready":"draft",requirementCount:i.requirement_c
26ount||0,answeredCount:i.answered_count||0,updatedAt:i.updated_at}))}};function bn(s,i,l,a,d,y,j){const C=y==="failed";return Object.entries(s).map(([w,f])=>{const _=!!l[w],T=!!a?.[w];let v=f;return f==="running"&&C?v="failed":f==="failed"&&!_&&!T&&(v="skipped"),{execution_id:w,run_id:d??"",task_id:w,task_name:i[w]?.task_name??w,status:v,input_data:null,output_data:a?.[w]??null,error_message:v==="failed"&&j?j:null,started_at:null,completed_at:l[w]??null}})}function jn(s){if(!s||s.length===0)return"";const i=a=>a==="builtin"?"Built-in":a==="custom_scripts"?"Custom":a.startsWith("composio:")?a.replace("composio:",""):a,l=["## Stage Details",""];for(const a of s)l.push(`### ${String(a.stage_id).padStart(2,"0")}. ${a.tool_name}`),l.push(`**Source:** ${i(a.source)}`),a.key_inputs.length>0&&l.push(`**Inputs:** ${a.key_inputs.join(", ")}`),a.key_outputs.length>0&&l.push(`**Outputs:** ${a.key_outputs.join(", ")}`),a.constraint&&l.push(`**Constraint:** ${a.constraint}`),l.push("");return l.join(`
27`)}function wn(s){if(s.startsWith("[EDIT_EXISTING_BOARD]")){const i=`
28User request: `,l=s.indexOf(i);return l!==-1?s.substring(l+i.length):"Editing this agent..."}return s}const us={gather_requirements:"Analyzing requirements",select_tools:"Selecting tools",search_tools:"Searching tools",get_tool_schemas:"Loading tool specs",list_examples:"Finding examples",get_example:"Loading example",build_board:"Building board",refine_board:"Refining board",ask_clarification:"Asking questions",respond:"Responding",complete:"Complete"};function vn(s){const i=Date.now()-s.getTime(),l=Math.floor(i/1e3);if(l<60)return"just now";const a=Math.floor(l/60);if(a<60)return`${a}m ago`;const d=Math.floor(a/60);return d<24?`${d}h ago`:s.toLocaleDateString(void 0,{month:"short",day:"numeric"})}const ps=[".csv",".xlsx",".xls",".json",".txt",".md",".pdf",".doc",".docx",".html",".png",".jpg",".jpeg",".gif",".webp"],kn=10*1024*1024,ze=5;function yn(s){const i=[],l=s.name.includes(".")?"."+s.name.split(".").pop().toLowerCase():"";return ps.includes(l)||i.push(`Unsupported file type "${l||"(none)"}". Allowed: ${ps.join(", ")}`),s.size>kn&&i.push(`File exceeds 10MB limit (${(s.size/(1024*1024)).toFixed(1)}MB)`),i.length>0?i.join("; "):null}function ks(s){return s==="Orchestrator"?{variant:"running"}:s==="Requirements Agent"?{variant:"custom",color:"sky"}:s==="Board Builder"?{variant:"custom",color:"teal"}:s==="Tool Selector"||s==="Tool Discovery"?{variant:"custom",color:"orange"}:s==="Schema Loader"?{variant:"custom",color:"violet"}:s==="Example Boards"?{variant:"custom",color:"indigo"}:{variant:"neutral"}}function Nn({messages:s}){const[i,l]=n.useState(!1);return e.jsxs(Ee,{open:i,onOpenChange:l,className:"mt-3 border-t border-pc-border pt-2",children:[e.jsxs(Fe,{className:"flex items-center gap-1 text-xs text-pc-text-3 hover:text-pc-text-2 transition-colors",children:[e.jsx(Je,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`}),e.jsx(Bt,{className:"h-3 w-3 text-pc-warning"}),e.jsxs("span",{children:["View ",s.length," agent steps"]})]}),e.jsx(Me,{className:"mt-2 space-y-2",children:s.map((a,d)=>{const y=ks(a.agent);return e.jsxs("div",{className:"text-xs rounded-pc-sm p-2 border border-pc-border bg-pc-surface",children:[e.jsx("div",{className:"mb-1",children:e.jsxs(we,{...y,showDot:!1,children:[e.jsx(Bt,{className:"h-3 w-3"}),a.agent]})}),e.jsx("div",{className:"text-pc-text-2",children:a.content})]},d)})})]})}function dr(){const{conversationId:s}=oa(),i=ca(),l=ms(),{toast:a}=da(),d=i.state,[y,j]=n.useState(null),[C,w]=n.useState(ye.CREW_BUILDER_DEFAULT_MODE),[f,_]=n.useState(null),[T,v]=n.useState([]),[J,V]=n.useState(""),[M,E]=n.useState(!1),[N,U]=n.useState(null),[Q,q]=n.useState(null),[ce,B]=n.useState("new"),[S,D]=n.useState([]),[H,ie]=n.useState(!1),[X,O]=n.useState(!1),[me,Z]=n.useState(null),[I,z]=n.useState(""),[ae,de]=n.useState([]),[Oe,Ne]=n.useState(!1),[P,R]=n.useState(null),[fe,ne]=n.useState(!1),re=n.useRef(null),[ee,be]=n.useState(null),[xe,_e]=n.useState(null),[ve,ke]=n.useState(null),[Ke,ue]=n.useState(null),[Rt,he]=n.useState(null),[At,Et]=n.useState(!1),[ys,Se]=n.useState(!1),[Ue,Ft]=n.useState(!1),[Mt,ct]=n.useState(null),[dt,Ot]=n.useState(!1),[ge,Ie]=n.useState({}),[Ns,Pt]=n.useState(!1),je=n.useRef(null),Te=n.useRef(!0),ut=n.useRef(null),Lt=n.useRef(null),[_s,qt]=n.useState(null),[pt,zt]=n.useState(!1),Vt=n.useRef(null),Ss=n.useRef(null),[Cs,mt]=n.useState(!1),[Ge,le]=n.useState(!1),[$s,ft]=n.useState(!1),[Xe,De]=n.useState([]),[Is,Ts]=n.useState([]),[Ut,Ds]=n.useState([]),[Bs,Gt]=n.useState([]),[Rs,Wt]=n.useState(0),[As,Qt]=n.useState(!0),[Es,Fs]=n.useState(0),[Ms,xt]=n.useState(""),[Os,Ht]=n.useState(0),[Ps,Ze]=n.useState(null),[Yt,Be]=n.useState(!1),[Jt,Pe]=n.useState(null),oe=Yt?"create":Jt?"improve":d?.mode||"create",G=Yt?void 0:Jt??(d?.boardId?{boardId:d.boardId,boardName:d.boardName||"",boardDescription:d.boardDescription}:void 0),K=d?.evaluationContext;n.useEffect(()=>(Te.current=!0,()=>{Te.current=!1,je.current&&(je.current.abort(),je.current=null)}),[]),n.useEffect(()=>{d?.newBuild&&(v([]),U(null),q(null),R(null),V(""),D([]),Z(null),z(""),de([]),le(!1),Be(!0),Pe(null),j(null),_(null),l("/factory",{replace:!0,state:null}))},[d?.newBuild,l]);const et=i.pathname==="/factory";n.useEffect(()=>{et&&ds.getSpecs().then(Ts).catch(()=>{})},[et]),n.useEffect(()=>{ds.getPopularBoards().then(Ds).catch(()=>{}),Y.getBoards().then(t=>{t.success&&t.boards&&Fs(t.boards.length)}).catch(()=>{})},[]),n.useEffect(()=>{if(!et)return;Qt(!0);const t=se.listConversationsV2().then(o=>o.conversations).catch(()=>[]),r=Promise.resolve([]);Promise.all([t,r]).then(([o,p])=>{const u=new Set,c=[...p,...o].filter(g=>u.has(g.id)?!1:(u.add(g.id),!0)),x=c.sort((g,b)=>new Date(b.updated_at).getTime()-new Date(g.updated_at).getTime()),h=x.slice(0,3);
28if(!h.some(g=>g.is_complete&&g.board_created_id)){const g=x.find(b=>b.is_complete&&b.board_created_id&&!h.includes(b));if(g){const b=h.length>=3?[...h.slice(0,2),g]:[...h,g];Gt(b),Wt(c.length);return}}Gt(h),Wt(c.length)}).finally(()=>Qt(!1))},[et]);const pe="crewBuilder_activeConversationId";n.useEffect(()=>{N&&(sessionStorage.setItem(pe,N),i.pathname==="/factory"&&l(`/factory/${N}`,{replace:!0}))},[N,i.pathname,l]);const We=n.useRef(null);n.useEffect(()=>{d?.mode==="improve"&&d?.boardId&&We.current!==d.boardId&&(We.current=d.boardId,Be(!1),v([]),U(null),R(null),Z(null),z(""),de([]),V(""),D([]),sessionStorage.removeItem(pe),_(null),be(null),_e(null),ke(null),ue(null),he(null),Se(!1),Ie({}))},[d?.mode,d?.boardId]),n.useEffect(()=>{if(d?.mode==="improve"&&d?.boardId)return;const t=sessionStorage.getItem(pe);if(!t)return;let r=!1,o=null;ie(!0);const p=async u=>{try{let c=!1,x=null;try{x=await se.getConversationV2(t)}catch{if(!ye.FACTORY_V2_ENABLED){sessionStorage.removeItem(pe),ie(!1);return}}if(!x||r)return;const h=new Map;try{const b=await se.getEvents(t);for(const A of b){if(!A.content||!A.message_id)continue;let W="Orchestrator",m=A.content||"";if(A.event_type==="thinking")m=`💭 ${m}`;else if(A.event_type==="action")m=`⚡ ${A.metadata?.action||""}`;else if(A.event_type==="observation"){const k=A.metadata?.result,te=A.metadata?.action;m=k?.success?`✓ ${te} completed`:`✗ ${te} failed`}else if(A.event_type==="agent_message"){const k=A.metadata?.agent;W=k==="requirement_gatherer"?"Requirements Agent":k==="board_builder"?"Board Builder":k==="orchestrator"?"Orchestrator":k||"Orchestrator"}else if(A.event_type==="tool_result"){const k=A.metadata?.agent;W=k==="tool_selector"?"Tool Selector":k==="tool_discovery"?"Tool Discovery":k==="schema_fetcher"?"Schema Loader":k==="example_boards"?"Example Boards":k||"Tool",m=`🔧 ${m}`}const $=h.get(A.message_id)||[];$.push({agent:W,content:m}),h.set(A.message_id,$)}}catch(b){console.warn("Failed to fetch events:",b)}w("v2");const F=x.messages.filter(b=>b.role==="user"||b.role==="assistant").map(b=>{const A={id:b.id,role:b.role,content:b.content,timestamp:new Date(b.created_at)},W=b.metadata?.clarifying_questions;W&&W.length>0&&(A.clarifyingQuestions=W.map($=>typeof $=="string"?{question:$,type:"free_text"}:$));const m=h.get(b.id);return m&&m.length>0&&(A.subAgentMessages=m),A});v(F),U(x.id),q(x.title||null),B(x.mode||"new"),R(x.state?.board_draft||null),x.state?.board_draft&&le(!0),x.state?.config_values&&Ie(x.state.config_values),ie(!1),F[F.length-1]?.role==="user"&&u>0&&(o=setTimeout(()=>{r||p(u-1)},3e3))}catch(c){console.error("Failed to restore conversation:",c),sessionStorage.removeItem(pe),r||ie(!1)}};return p(5),()=>{r=!0,o&&clearTimeout(o)}},[]),n.useEffect(()=>{if(Object.keys(ge).length===0||!N)return;const t=setTimeout(async()=>{try{await se.updateConfigValues(N,ge)}catch(r){console.warn("Failed to persist config values:",r)}},1e3);return()=>clearTimeout(t)},[N,ge]),n.useEffect(()=>{if(oe==="improve"&&T.length===0){const t=[];if(d?.runFailureContext){const r=d.runFailureContext;if(t.push(`I'm helping you fix the board "${G?.boardName||"your board"}" after a failed run.`),t.push(`
29
30**Run Failure Details:**`),t.push(`
31- Failed task: **${r.failedTaskName}**`),t.push(`
32- Error: \`${r.errorMessage}\``),r.completedTasks.length>0&&t.push(`
33- Tasks that completed successfully: ${r.completedTasks.join(", ")}`),r.effectiveConfig&&Object.keys(r.effectiveConfig).length>0){t.push(`
34
35**Configuration values active during this run:**`);for(const[o,p]of Object.entries(r.effectiveConfig)){const u=typeof p=="object"?JSON.stringify(p,null,2):String(p);t.push(`
36- ${o}:
37\`\`\`json
38${u}
39\`\`\``)}}if(r.taskOutputs&&Object.keys(r.taskOutputs).length>0){t.push(`
40
41**Outputs from completed tasks** (use these to understand what each task produced and why the failing task errored):`);for(const[,{taskName:o,output:p}]of Object.entries(r.taskOutputs)){const u=p?JSON.stringify(p,null,2):"null";t.push(`
42- ${o}:
43\`\`\`json
44${u}
45\`\`\``)}}r.boardStructure&&t.push(`
46
47**Board Structure:**
48${r.boardStructure}`),t.push(`
49
50I can help you fix the failing task or restructure the workflow. What would you like to change?`)}else K?(t.push(`I'm helping you improve the board "${G?.boardName||"your board"}".`),t.push(`
51
52**Evaluation Results:** ${K.overallStatus.toUpperCase()} (${K.passedTests}/${K.totalTests} tests passed)`),K.criticalIssues.length>0&&(t.push(`
53
54**Critical Issues Found:**`),K.criticalIssues.forEach((r,o)=>{t.push(`
55${o+1}. ${r}`)})),t.push(`
56
57How would you like me to help improve this board? You can ask me to fix specific issues or make other changes.`)):(t.push(`I'm helping you improve the board "${G?.boardName||"your board"}".`),t.push(`
58
59What changes would you like to make?`));if(t.length>0){const r={id:"initial-context",role:"assistant",content:t.join(""),timestamp:new Date};v([r])}d?.initialPrompt&&V(d.initialPrompt)}},[oe,K,d?.runFailureContext,G?.boardName,d?.initialPrompt,T.length]);const[Kt,Qe]=n.useState(()=>{const t=new URLSearchParams(window.location.search);return t.get("from_spec")==="1"&&!!sessionStorage.getItem("factory-spec-id")||t.get("from_spec_content")==="1"&&!!sessionStorage.getItem("factory-spec-content")});n.useEffect(()=>{if(!(new URLSearchParams(i.search).get("from_spec_content")==="1"))return;const o=sessionStorage.getItem("factory-spec-content");if(!o){Qe(!1);return}v([]),U(null),_(null),R(null),V(""),D([]),Be(!0),Pe(null),le(!1),re.current=null,sessionStorage.removeItem(pe),sessionStorage.removeItem("factory-spec-content");try{const{title:p,content:u}=JSON.parse(o);Ze({title:p,content:u}),xt("Build an agent from the attached spec"),Ht(c=>c+1)}catch(p){console.error("Failed to parse spec content:",p)}Qe(!1),l(i.pathname,{replace:!0})},[i.search,l,i.pathname]),n.useEffect(()=>{if(!(new URLSearchParams(i.search).get("from_spec")==="1"))return;const o=sessionStorage.getItem("factory-spec-id");if(!o){Qe(!1);return}v([]),U(null),_(null),R(null),V(""),D([]),Be(!0),Pe(null),le(!1),re.current=null,sessionStorage.removeItem(pe),Qe(!0),sessionStorage.removeItem("factory-spec-id"),l(i.pathname,{replace:!0}),(async()=>{try{const p=await Qa.getConversation(o),u=p.messages.find(c=>c.messageType==="prd_document");if(u?.content){let c=u.content;const x=`
60
61---STAGE METADATA---
62`;if(c.includes(x)){const[F,g]=c.split(x);try{const b=JSON.parse(g),A=jn(b);c=`${F}
63
64${A}`}catch{c=F}}const h=p.title||"Untitled Spec";Ze({title:h,content:c}),xt("Build an agent from the attached spec"),Ht(F=>F+1)}}catch(p){console.error("Failed to load spec for Factory:",p),a({title:"Failed to load spec",description:"Could not load the spec from Spec Builder",variant:"destructive"})}finally{Qe(!1)}})()},[i.search,T.length,l,i.pathname,a]);const tt=n.useRef(null);n.useEffect(()=>{if(!s){tt.current=null;return}tt.current!==s&&(tt.current=s,O(!0),v([]),U(null),q(null),R(null),sessionStorage.removeItem(pe),be(null),_e(null),ke(null),ue(null),he(null),Se(!1),Ie({}),(async()=>{try{let t=!1,r=null;try{r=await se.getConversationV2(s)}catch{throw ye.FACTORY_V2_ENABLED,new Error("Session not found")}if(!r)throw new Error("Session not found");const o=new Map;try{const u=await se.getEvents(s);for(const c of u){if(!c.content||!c.message_id)continue;let x="Orchestrator",h=c.content||"";if(c.event_type==="thinking")h=`💭 ${h}`;else if(c.event_type==="action")h=`⚡ ${c.metadata?.action||""}`;else if(c.event_type==="observation"){const g=c.metadata?.result,b=c.metadata?.action;h=g?.success?`✓ ${b} completed`:`✗ ${b} failed`}else if(c.event_type==="agent_message"){const g=c.metadata?.agent;x=g==="requirement_gatherer"?"Requirements Agent":g==="board_builder"?"Board Builder":g==="orchestrator"?"Orchestrator":g||"Orchestrator"}else if(c.event_type==="tool_result"){const g=c.metadata?.agent;x=g==="tool_selector"?"Tool Selector":g==="tool_discovery"?"Tool Discovery":g==="schema_fetcher"?"Schema Loader":g==="example_boards"?"Example Boards":g||"Tool",h=`🔧 ${h}`}const F=o.get(c.message_id)||[];F.push({agent:x,content:h}),o.set(c.message_id,F)}}catch(u){console.warn("Failed to fetch events:",u)}w("v2");const p=r.messages.filter(u=>u.role==="user"||u.role==="assistant").map(u=>{const c={id:u.id,role:u.role,content:u.content,timestamp:new Date(u.created_at)},x=u.metadata?.clarifying_questions;x&&x.length>0&&(c.clarifyingQuestions=x.map(F=>typeof F=="string"?{question:F,type:"free_text"}:F));const h=o.get(u.id);return h&&h.length>0&&(c.subAgentMessages=h),c});
64v(p),U(r.id),q(r.title||null),B(r.mode||"new"),R(r.state?.board_draft||null),r.state?.board_draft&&le(!0),r.state?.config_values&&Ie(r.state.config_values),Z(null),z(""),de([]),V(""),D([]),sessionStorage.setItem(pe,r.id)}catch(t){console.error("Failed to load conversation:",t),a({title:"Failed to load build",description:"Could not load the conversation",variant:"destructive"}),tt.current=null,l("/factory",{replace:!0})}finally{O(!1)}})())},[s,l,a]);const[ht,gt]=n.useState(!1);n.useEffect(()=>{if(oe!=="improve"||!G?.boardId)return;let t=!1;return gt(!0),(async()=>{try{const[r,o,p]=await Promise.all([Y.getBoardDraft(G.boardId),Y.getConfigurations(G.boardId),Y.getLatestRunConfig(G.boardId).catch(()=>null)]);if(t||!r.success||!r.board_draft)return;re.current=G.boardId;const u={...r.board_draft,...o&&{configurations:o},source_board_id:G.boardId};R(u),p?.config_values&&Ie(p.config_values)}catch(r){console.error("Failed to fetch board draft for improve mode:",r)}finally{t||gt(!1)}})(),()=>{t=!0,gt(!1)}},[oe,G?.boardId]),n.useEffect(()=>{pt||ut.current?.scrollIntoView({behavior:"smooth"})},[T,M,I,pt]);const Ls=n.useCallback(()=>{const t=Lt.current;if(!t)return;const r=t.scrollHeight-t.scrollTop-t.clientHeight;zt(r>100)},[]),qs=n.useCallback(()=>{ut.current?.scrollIntoView({behavior:"smooth"}),zt(!1)},[]);n.useEffect(()=>{qt(M?new Date:null)},[M]);const Le=n.useCallback(async(t,r)=>{let o;if(N)o=await se.refine(t,N);else{let u=t;if(oe==="improve"&&G){const c=[];c.push(`I need to improve an existing board called "${G.boardName}".`),G.boardDescription&&c.push(`Board description: ${G.boardDescription}`),K&&(c.push(`
65Evaluation Results: ${K.overallStatus} (${K.passedTests}/${K.totalTests} tests passed)`),K.criticalIssues.length>0&&(c.push(`
66Critical Issues:`),K.criticalIssues.forEach(x=>{c.push(`- ${x}`)}))),c.push(`
67User request: ${t}`),u=c.join(`
68`)}o=await se.generate(u,void 0,r)}U(o.conversation_id);const p={id:(Date.now()+1).toString(),role:"assistant",content:o.message,timestamp:new Date,boardDraft:o.board_draft||void 0};if(v(u=>[...u,p]),o.board_draft){const u=re.current?{...o.board_draft,source_board_id:re.current}:o.board_draft;R(u)}if(o.clarifying_questions&&o.clarifying_questions.length>0){const u=o.clarifying_questions.map(h=>typeof h=="string"?{question:h,type:"free_text"}:h),x={id:(Date.now()+2).toString(),role:"assistant",content:"I have a few questions to help me design the best workflow for you:",timestamp:new Date,clarifyingQuestions:u};v(h=>[...h,x]),De(_t(u))}},[N,oe,G,K]),qe=n.useCallback(async(t,r)=>{let o=t;if(oe==="improve"&&G&&P){const m=[];if(m.push("[EDIT_EXISTING_BOARD]"),m.push(`I need to fix/improve an existing board called "${G.boardName}".`),G.boardDescription&&m.push(`Board description: ${G.boardDescription}`),d?.runFailureContext){const k=d.runFailureContext;if(m.push(`
69Run Failure Details:`),m.push(`- Failed task: ${k.failedTaskName}`),m.push(`- Error: ${k.errorMessage}`),k.completedTasks.length>0&&m.push(`- Completed tasks: ${k.completedTasks.join(", ")}`),k.effectiveConfig&&Object.keys(k.effectiveConfig).length>0&&(m.push(`
70Configuration values that were active during this run (these are the one-time board settings applied — check if any contributed to the failure):`),m.push(JSON.stringify(k.effectiveConfig,null,2))),k.taskOutputs&&Object.keys(k.taskOutputs).length>0){m.push(`
71Outputs from completed tasks (use these to diagnose the root cause — the failing task may have received wrong/null data from a prior task):`);for(const[,{taskName:te,output:Re}]of Object.entries(k.taskOutputs)){const Ae=Re?JSON.stringify(Re,null,2):"null";m.push(`- ${te}: ${Ae}`)}}}K&&(m.push(`
72Evaluation Results: ${K.overallStatus} (${K.passedTests}/${K.totalTests} tests passed)`),K.criticalIssues.length>0&&(m.push(`
73Critical Issues:`),K.criticalIssues.forEach(k=>{m.push(`- ${k}`)})));let $=P;if(!$&&G?.boardId)try{const k=await Y.getBoardDraft(G.boardId);k.success&&k.board_draft&&($=k.board_draft,R(k.board_draft))}catch{}$&&m.push(`
74Existing Board JSON:
75\`\`\`json
76${JSON.stringify($,null,2)}
77\`\`\``),m.push(`
78User request: ${t}`),o=m.join(`
79`)}let u="",c=null;const x=[],h=[],F=(m,$)=>
79{const k=`stream-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;v(te=>[...te,{id:k,role:"assistant",content:m,timestamp:new Date,isStreaming:!0,agentName:$}]),$&&h.push({agent:$,content:m})},g=m=>{switch(m.type){case"thinking":z(m.content),m.content&&F(`💭 ${m.content}`,"Orchestrator");break;case"action":{const $=m.metadata?.action;if($){Z($);const k=us[$]||$;F(`⚡ ${k}`,"Orchestrator")}break}case"observation":{const $=m.metadata?.action,k=m.metadata?.result;if($&&k){const te=k.success?`✓ ${$} completed`:`✗ ${$} failed: ${k.error||"unknown error"}`;F(te,"Orchestrator")}break}case"agent_message":{const $=m.metadata?.agent;if($&&m.content){const k=$==="requirement_gatherer"?"Requirements Agent":$==="board_builder"?"Board Builder":$==="orchestrator"?"Orchestrator":$;F(m.content,k)}u=m.content,z(m.content);break}case"tool_result":{if(m.metadata?.top_tools){const $=m.metadata.top_tools;de($)}if(m.metadata?.selected_tools){const $=m.metadata.selected_tools;de($.map(k=>({name:k.name,description:k.reason||""})))}if(m.content){const $=m.metadata?.agent,k=$==="tool_selector"?"Tool Selector":$==="tool_discovery"?"Tool Discovery":$==="schema_fetcher"?"Schema Loader":$==="example_boards"?"Example Boards":$||"Tool";F(`🔧 ${m.content}`,k)}break}case"board_draft":if(m.metadata?.board_draft){const $=m.metadata?.is_retry,k=m.metadata?.validation_errors;if($){const te=m.metadata?.attempt,Re=m.metadata?.max_retries,Ae=k?.length||0;F(`🔄 Fixing ${Ae} validation issue(s) (attempt ${te}/${Re})...${k?.length?`
80`+k.slice(0,3).map(wt=>`  • ${wt}`).join(`
81`):""}`,"Board Builder"),c=m.metadata.board_draft,re.current&&(c={...c,source_board_id:re.current}),R(c)}else{c=m.metadata.board_draft,re.current&&(c={...c,source_board_id:re.current}),R(c);const te=c.swimlanes?.length||0,Re=c.swimlanes?.reduce((Ae,wt)=>Ae+(wt.tasks?.length||0),0)||0;k&&k.length>0?F(`📋 Generated board: "${c.name}" (${te} phases, ${Re} tasks)
82⚠️ ${k.length} validation issue(s):
83${k.slice(0,5).map(Ae=>`  • ${Ae}`).join(`
84`)}`,"Board Builder"):F(`📋 Generated board: "${c.name}" (${te} phases, ${Re} tasks)`,"Board Builder")}}break;case"clarification_needed":m.metadata?.questions&&x.push(...m.metadata.questions);break;case"title":m.content&&q(m.content);break;case"complete":m.metadata?.conversation_id&&U(m.metadata.conversation_id),m.metadata?.board_draft&&(c=m.metadata.board_draft,re.current&&(c={...c,source_board_id:re.current}),R(c)),m.metadata?.clarifying_questions&&x.push(...m.metadata.clarifying_questions),u=m.content||u;break;case"error":throw new Error(m.content)}},b=new AbortController;je.current=b,Ne(!0);const A=N?void 0:oe==="improve"?d?.runFailureContext?"fix":"edit":"new";A&&B(A);try{for await(const m of se.streamGenerate(o,N||void 0,r,g,b.signal,re.current||void 0,A));}catch(m){if(m instanceof Error&&m.name==="AbortError"){Ne(!1);return}throw m}finally{je.current=null,Ne(!1)}if(v(m=>m.filter($=>!$.isStreaming)),u){const m={id:(Date.now()+1).toString(),role:"assistant",content:u,timestamp:new Date,boardDraft:c||void 0,subAgentMessages:h.length>0?h:void 0};v($=>[...$,m])}const W=!!P;if(c&&Te.current&&!W&&le(!0),x.length>0){const m=x.map(te=>typeof te=="string"?{question:te,type:"free_text"}:te),k={id:(Date.now()+2).toString(),role:"assistant",content:"I have a few questions to help me design the best workflow for you:",timestamp:new Date,clarifyingQuestions:m};v(te=>[...te,k]),De(_t(m))}},[N,oe,G,K,d?.runFailureContext,P]),bt=n.useCallback(async(t,r)=>{const o=new AbortController;je.current=o;try{let p=f;if(p||(p=(await rt.createSession()).id,_(p),U(p)),r?.length){for(const b of r)await rt.uploadFile(p,b);const g=r.map(b=>`/files/${b.name}`).join(", ");t=`${t}
85
86[Uploaded files available at: ${g}]`}const u=[];let c="",x=null;const h=[],F=(g,b)=>{const A=`stream-v3-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;h.push(A),v(W=>[...W,{id:A,role:"assistant",content:g,timestamp:new Date,isStreaming:!0,agentName:b}]),b&&u.push({agent:b,content:g})};for await(const g of rt.streamMessage(p,t,o.signal)){if(!Te.current)break;switch(g.type){case"start":Z("starting");break;case"step":{const b=g;b.step&&(Z(b.step),F(`⚡ ${b.step}`,b.agent||"Agent"));break}case"token":g.content&&(c+=g.content,z(c),v(b=>{const A=b.map(W=>W.isStreaming).lastIndexOf(!0);if(A>=0){const W=[...b];return W[A]={...W[A],content:c,agentName:g.agent},W}else{const W=`stream-v3-token-${Date.now()}`;return h.push(W),[...b,{id:W,role:"assistant",content:c,timestamp:new Date,isStreaming:!0,agentName:g.agent}]}}));break;case"message":{const b=g.agent;g.content&&(c=g.content,b&&u.push({agent:b,content:g.content}),h.length===0&&(F(g.content,b||"Agent"),z(g.content)));break}case"interrupt":if(g.payload?.gaps){const A=g.payload.gaps.map(W=>W.question);F(A.map(W=>`• ${W}`).join(`
87`),"Orchestrator")}else g.payload&&F(typeof g.payload=="string"?g.payload:JSON.stringify(g.payload),"Orchestrator");break;case"plan_ready":if(g.plan){const b=g.plan;F(`📋 Here's the plan:
88
89**${b.description}**
90
91**Tools:** ${b.tools.join(", ")}
92**Inputs:** ${b.inputs.join(", ")}
93**Outputs:** ${b.outputs.join(", ")}
94
95Does this look right?`,"Plan Agent"),c=`Plan ready: ${b.description}`}break;case"board_ready":if(g.board_draft){x=g.board_draft,R(x),le(!0);const b=x.swimlanes?.length??0,A=x.swimlanes?.reduce((W,m)=>W+(m.tasks?.length??0),0)??0;F(`✅ Board ready: "${x.name}" (${b} phases, ${A} tasks)`,"Edit Agent")}break;case"done":Z(null);break;case"error":throw new Error(g.error??"Unknown error from V2 agent")}}Te.current&&(v(g=>{const b=g.filter(A=>!h.includes(A.id));return(c||x)&&b.push({id:`final-v3-${Date.now()}`,role:"assistant",content:c||"✅ Board generated successfully.",timestamp:new Date,boardDraft:x??void 0,subAgentMessages:u.length?u:void 0}),b}),x&&!Ge&&le(!0))}catch(p){if(p.name==="AbortError")return;throw p}finally{je.current=null,Ne(!1)}},[f,M,Ge,Te]),zs=n.useCallback(async(t,r)=>{if(!t.trim()||M)return;const o={id:Date.now().toString(),role:"user",content:t.trim(),timestamp:new Date,attachedFiles:r&&r.length>0?r.map(p=>p.name):void 0};v(p=>[...p,o]),V(""),D([]),xt(""),Ze(null),E(!0),Z(null),z("");try{ye.FACTORY_V2_ENABLED||(C==="v2"?await qe(o.content,r?.length?r:void 0):await Le(o.content,r?.length?r:void 0))}catch(p){console.error("Failed to generate board:",p),a({title:"Generation failed",description:p instanceof Error?p.message:"An error occurred while generating the board",variant:"destructive"})}finally{Te.current&&E(!1)}},[M,C,Le,qe,bt,a]),jt=n.useCallback(async()=>{if(!J.trim()||M)return;const t={id:Date.now().toString(),role:"user",content:J.trim(),timestamp:new Date,attachedFiles:S.length>0?S.map(o=>o.name):void 0};v(o=>[...o,t]),V(""),E(!0),Z(null),z("");const r=S.length>0?[...S]:void 0;D([]);try{ye.FACTORY_V2_ENABLED||(C==="v2"?await qe(t.content,r):await Le(t.content,r))}catch(o){console.error("Failed to generate board:",o),a({title:"Generation failed",description:o instanceof Error?o.message:"An error occurred",variant:"destructive"})}finally{E(!1),Z(null)}},[J,M,S,C,Le,qe,bt,a]),st=n.useCallback(async t=>{if(!t.trim()||M)return;const r={id:Date.now().toString(),role:"user",content:t.trim(),timestamp:new Date};v(o=>[...o,r]),V(""),E(!0),Z(null),z("");try{ye.FACTORY_V2_ENABLED||(C==="v2"?await qe(r.content):await Le(r.content))}catch(o){console.error("Failed to send answers:",o),a({title:"Failed to send",description:o instanceof Error?o.message:"An error occurred",variant:"destructive"})}finally{E(!1),Z(null)}},[M,C,Le,qe,bt,a]),Vs=n.useCallback(t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),jt())},[jt]),at=n.useCallback(t=>{const r=Array.from(t),o=[],p=[],u=ze-S.length;if(u<=0){a({title:"File limit reached",description:`You can attach up to ${ze} files per message.`,variant:"destructive"});return}for(const c of r){if(o.length>=u){p.push(`${c.name}: Exceeds ${ze}-file limit`);continue}const x=yn(c);x?p.push(`${c.name}: ${x}`):o.push(c)}p.length>0&&a({title:"Files rejected",description:p.join(`
96`),variant:"destructive"}),o.length>0&&D(c=>[...c,...o])},[a,S.length]),Us=n.useCallback(t=>{t.target.files&&t.target.files.length>0&&(at(t.target.files),t.target.value="")},[at]),Gs=n.useCallback(t=>{t.preventDefault(),t.stopPropagation(),mt(!0)},[]),Ws=n.useCallback(t=>{t.preventDefault(),t.stopPropagation(),mt(!1)},[]),Qs=n.useCallback(t=>{t.preventDefault(),t.stopPropagation(),mt(!1),t.dataTransfer.files&&t.dataTransfer.files.length>0&&at(t.dataTransfer.files)},[at]),Hs=n.useCallback(t=>{D(r=>r.filter((o,p)=>p!==t))},[]),nt=n.useCallback(async()=>{if(N)try{C==="v2"?await se.clearConversationV2(N):await se.clearConversation(N)}catch(t){console.error("Failed to clear conversation:",t)}f&&(rt.deleteSession(f).catch(()=>{}),_(null)),sessionStorage.removeItem(pe),v([]),U(null),q(null),R(null),V(""),D([]),Z(null),z(""),de([]),le(!1),l("/factory",{replace:!0}),Be(!0),Pe(null),We.current=null,ee&&Y.deleteBoard(ee).catch(()=>{}),be(null),_e(null),ke(null),ue(null),he(null),Se(!1),j(null)},[N,C,ee,f]),Ys=n.useCallback(()=>{sessionStorage.removeItem(pe),v([]),U(null),q(null),R(null),V(""),D([]),Z(null),z(""),de([]),le(!1),l("/factory",{replace:!0}),Be(!0),Pe(null),We.current=null,ee&&Y.deleteBoard(ee).catch(()=>{}),be(null),_e(null),ke(null),ue(null),he(null),Se(!1),j(null)},[ee,l]);n.useCallback(()=>{T.length!==0&&nt()},[T.length,nt]);const Xt=n.useCallback(()=>{T.length!==0&&ft(!0)},[T.length]),Js=n.useCallback(()=>{ft(!1),nt()},[nt]),Zt=n.useCallback(()=>{je.current&&(je.current.abort(),je.current=null),Ne(!1),E(!1),Z(null),z(""),v(t=>t.filter(r=>!r.isStreaming))},[]),He=T.find((t,r)=>t.role==="assistant"&&t.clarifyingQuestions?.length&&!T.slice(r+1).some(o=>o.role==="user")),Ce=He?.clarifyingQuestions;n.useEffect(()=>{Ce?.length?(De(_t(Ce)),V("")):De([])},[He?.id,Ce?.length]);const Ks=n.useCallback(()=>
96{if(!Ce||!Ma(Xe))return;const t=Oa(Ce,Xe);st(t),De([])},[Ce,Xe,st]),Xs=n.useCallback(()=>{He&&(v(t=>t.map(r=>r.id===He.id?{...r,clarifyingQuestions:void 0}:r)),De([]))},[He]),es=n.useCallback(async()=>{if(!(!P||Ue)&&!(!N&&!G?.boardId)){Ft(!0);try{if(ee){try{await Y.deleteBoard(ee)}catch{}be(null),_e(null),ke(null),ue(null),he(null)}ct(null);let t;N?t=(await se.applyBoardV2(N,P)).board_id:t=(await se.create(P)).board_id;const r=await Y.getBoard(t);if(r.success&&r.board){if(be(t),_e(r.board),Object.keys(ge).length>0&&P.configurations?.fields)try{const o=P.configurations.fields.filter(p=>p.enabled&&ge[p.key]!==void 0).map(p=>({key:p.key,value:ge[p.key],targets:p.targets}));o.length>0&&await Y.createConfigFromValues(t,o)}catch(o){console.warn("Failed to save config values, proceeding with defaults:",o)}Se(!0)}else throw new Error("Failed to load test board")}catch(t){console.error("Failed to prepare test run:",t),a({title:"Test run preparation failed",description:t instanceof Error?t.message:"An error occurred",variant:"destructive"})}finally{Ft(!1)}}},[P,N,G,Ue,ee,ge,a]),Zs=n.useCallback(t=>{ke(t),ue(null),he(null),Se(!1)},[]),ea=n.useCallback(async()=>{if(!(!ee||dt)){Ot(!0),ct(null);try{const t=await Y.generateTestData(ee,P,N);t.success&&t.data?ct(t.data):a({title:"Could not generate test data",description:t.error||"Generation failed. You can still enter data manually.",variant:"destructive"})}catch(t){a({title:"Could not generate test data",description:t instanceof Error?t.message:"An error occurred. You can still enter data manually.",variant:"destructive"})}finally{Ot(!1)}}},[ee,P,N,dt,a]),ta=n.useCallback(async t=>{if(P?.configurations?.fields){const r=P.configurations.fields.map(o=>{const p=t.find(u=>u.key===o.key);return p&&p.value!==void 0?{...o,default:p.value}:o});R({...P,configurations:{...P.configurations,fields:r}})}if(ee){Pt(!0);try{await Y.createConfigFromValues(ee,t)}catch(r){console.warn("Failed to save to test board:",r)}finally{Pt(!1)}}a({title:"Configuration saved",description:"Values will be used when you create the agent."})},[P,R,ee,a]),sa=n.useCallback(t=>{st(t)},[st]);n.useEffect(()=>{if(!ve)return;const t=xe?.compiler_version==="v3";let r=!1,o;const p=async()=>{try{if(t){const u=await Y.getRunGraphState(ve,"status");if(r||!u.success)return;const c=["completed","failed","cancelled"].includes(u.run_status),x=c?"output":"status",h=c?await Y.getRunGraphState(ve,x):u;c&&clearInterval(o),ue(F=>({...F??{},run_id:ve,status:h.run_status,error_message:h.error_message,started_at:h.started_at??F?.started_at??"",task_executions:bn(h.task_statuses,h.task_map,h.task_completed_at,h.task_outputs,ve,h.run_status,h.error_message)})),c&&u.run_status==="completed"&&h.run_state&&he(h.run_state)}else{const u=await Y.getRunStatus(ve,{lite:!0});if(!r&&u.success&&u.run)if(["completed","failed","cancelled"].includes(u.run.status)){clearInterval(o);const x=await Y.getRunStatus(ve,{lite:!1});!r&&x.success&&x.run&&(ue(x.run),u.run.status==="completed"&&(Et(!0),Y.getRunOutput(ve).then(h=>{h.success&&h.output&&he(h.output)}).finally(()=>Et(!1))))}else ue(u.run)}}catch(u){console.error("Failed to poll test run status:",u)}};return p(),o=setInterval(p,2e3),()=>{r=!0,clearInterval(o)}},[ve,xe]),n.useCallback(async t=>{try{const r=await se.getConversationV2(t);w("v2");const o=r.messages.filter(p=>p.role==="user"||p.role==="assistant").map(p=>{const u={id:p.id,role:p.role,content:p.content,timestamp:new Date(p.created_at)},c=p.metadata?.clarifying_questions;return c&&c.length>0&&(u.clarifyingQuestions=c.map(x=>typeof x=="string"?{question:x,type:"free_text"}:x)),u});v(o),U(r.id),q(r.title||null),B(r.mode||"new"),R(r.state?.board_draft||null),Z(null),z(""),de([]),V(""),D([]),sessionStorage.setItem(pe,r.id),be(null),_e(null),ke(null),ue(null),he(null),Se(!1),Ie({})}catch(r){console.error("Failed to restore conversation:",r)}},[]);const aa=n.useCallback(async()=>{if(!P||fe)return;const t=oe==="improve"&&!!P.source_board_id;ne(!0);try{let r;ee&&(Y.deleteBoard(ee).catch(()=>{}),be(null),_e(null),ke(null),ue(null),he(null));let o;if(ye.FACTORY_V2_ENABLED&&f||(C==="v2"&&N?o=await se.applyBoardV2(N,P):o=await se.create(P)),r=o.board_id,Object.keys(ge).length>0&&P.configurations?.fields)try{const p=P.configurations.fields.filter(u=>u.enabled&&ge[u.key]!==void 0).map(u=>({key:u.key,value:ge[u.key],targets:u.targets}));p.length>0&&await Y.createConfigFromValues(r,p)}catch(p){console.warn("Failed to save config values to board:",p)}if(!t&&ye.SIMPLIFIED_BOARD_UX)try{await Y.publishBoard(r)}catch(p){console.warn("Auto-publish failed, board created in draft:",p)}a({title:t?"Board updated":"Board created",description:`"${P.name}" has been ${t?"updated":"created"} successfully.`}),le(!1),l(ye.SIMPLIFIED_BOARD_UX?`/kanban/${r}`:`/kanban/${r}?tab=overview`)}catch(r){console.error("Failed to create/update board:",r),a({title:t?"Board update failed":"Board creation failed",description:r instanceof Error?r.message:"An error occurred",variant:"destructive"})}finally{ne(!1)}},[P,fe,C,N,ee,oe,a,l]),na=n.useCallback(async t=>{if(!fe){ne(!0);try{const r=await se.getConversationV2(t),o=r.state?.board_draft;if(!o){a({title:"No draft found",description:"This build does not have a completed agent draft.",variant:"destructive"});return}const u=(await se.applyBoardV2(t,o)).board_id,c=r.state?.config_values;if(c&&Object.keys(c).length>0&&o.configurations?.fields)try{const x=o.configurations.fields.filter(h=>h.enabled&&c[h.key]!==void 0).map(h=>({key:h.key,value:c[h.key],targets:h.targets}));x.length>0&&await Y.createConfigFromValues(u,x)}catch(x){console.warn("Failed to save config values to new board:",x)}try{await Y.publishBoard(u)}catch(x){console.warn("Auto-publish failed, board created in draft:",x)}a({title:"Agent created",description:`"${o.name}" has been created successfully.`}),l(`/kanban/${u}`)}catch(r){console.error("Failed to deploy build:",r),a({title:"Deploy failed",description:r instanceof Error?r.message:"An error occurred while creating the agent",variant:"destructive"})}finally{ne(!1)}}},[fe,a,l]),ra=T.length>0||M||X||!!s,ia=Q||"Untitled build",la=P?e.jsxs("div",{className:"py-4 flex items-center justify-end gap-2",children:[e.jsxs(L,{variant:"outline",onClick:es,disabled:Ue||fe||!N&&!G?.boardId,children:[Ue?e.jsx(Ve,{className:"animate-spin"}):e.jsx(Dt,{}),Ue?"Preparing...":"Test Run"]}
96),e.jsxs(L,{onClick:aa,disabled:fe,children:[fe?e.jsx(Ve,{className:"animate-spin"}):e.jsx(Ta,{}),fe?"Creating...":"Create Agent"]})]}):null;return e.jsxs(Ct,{open:Ge,onOpenChange:le,dimMainOnOpen:!1,children:[e.jsx(Ct.Main,{className:"flex flex-col",children:e.jsxs("div",{"data-testid":"crew-builder-page",children:[ra?e.jsxs("div",{className:"sticky top-0 z-10 bg-pc-bg pt-6",children:[X?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-16 bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse"}),e.jsx("div",{className:"h-4 w-24 bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse"})]}):e.jsx(Ua,{children:e.jsxs(Ga,{children:[e.jsx(St,{children:e.jsx(rs,{asChild:!0,children:e.jsx(ts,{to:"/factory",onClick:t=>{t.preventDefault(),Ys()},children:"Factory"})})}),e.jsx(is,{}),y==="history"&&e.jsxs(e.Fragment,{children:[e.jsx(St,{children:e.jsx(rs,{asChild:!0,children:e.jsx(ts,{to:"/factory/history",children:"Your Builds"})})}),e.jsx(is,{})]}),e.jsx(St,{children:e.jsx(Wa,{children:ia})})]})}),e.jsx("div",{className:"border-b border-pc-border mt-4"})]}):e.jsx(ua,{title:"Factory",subtitle:"Describe your workflow idea and let AI help you build a complete agent.",children:e.jsx("div",{className:"border-b border-pc-border mt-4 md:mt-6"})}),T.length===0&&oe==="create"&&!H&&Kt&&e.jsxs("div",{className:"flex-1 overflow-auto flex flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto py-10",children:e.jsxs("div",{className:"max-w-page-content mx-auto w-full",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("div",{className:"h-7 w-72 bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse mx-auto"}),e.jsx("div",{className:"h-4 w-96 bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse mx-auto mt-3"})]}),e.jsxs("div",{className:"mb-10",children:[e.jsx("div",{className:"h-4 w-24 bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse mb-3"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(t=>e.jsxs("div",{className:"bg-pc-surface border border-pc-border rounded-pc-md p-5 h-40",children:[e.jsx("div",{className:"h-4 w-20 bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse mb-3"}),e.jsx("div",{className:"h-5 w-full bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse mb-2"}),e.jsx("div",{className:"h-4 w-3/4 bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse"})]},t))})]})]})}),e.jsx("div",{className:"flex-none pb-6",children:e.jsx("div",{className:"max-w-page-content mx-auto w-full",children:e.jsx("div",{className:"bg-pc-surface border border-pc-border rounded-pc-lg h-36 animate-pulse"})})})]}),T.length===0&&oe==="create"&&!M&&!X&&!H&&!s&&!Kt?e.jsx(hn,{specs:Is,popularBoards:Ut,recentBuilds:Bs,totalBuildCount:Rs,isLoadingBuilds:As,onBuildFromSpec:(t,r)=>{sessionStorage.setItem("prd-builder-resume-spec",t),l("/prd-builder?resume=1&open_doc=1")},onFinishSpec:t=>{sessionStorage.setItem("prd-builder-resume-spec",t),l("/prd-builder?resume=1")},onViewAllSpecs:()=>{l("/prd-builder/history")},onViewBoard:t=>l(`/kanban/${t}`),onCustomizeBoard:t=>{const r=Ut.find(o=>o.board_id===t);Be(!1),v([]),U(null),R(null),V(""),We.current=t,Pe({boardId:t,boardName:r?.name||"",boardDescription:r?.description}),Y.getBoardDraft(t).then(o=>{o.board_draft&&(R(o.board_draft),le(!0))}).catch(()=>{})},totalBoardCount:Es,onViewAllBoards:()=>l("/kanban"),onResumeBuild:t=>{l(`/factory/${t}`)},onDeployBuild:t=>na(t),onScratchBuild:(t,r)=>zs(t,r),initialInputValue:Ms,initialInputTrigger:Os,attachedSpec:Ps,onRemoveAttachedSpec:()=>Ze(null)}):e.jsx("div",{className:"flex-1 flex flex-col min-h-0 max-w-page-content mx-auto w-full",children:(X||H)&&T.length===0?e.jsx("div",{className:"flex-1 px-4 py-6 space-y-4 overflow-hidden",children:[1,2,3].map(t=>e.jsxs("div",{className:`flex gap-2.5 ${t%2===0?"flex-row-reverse":""}`,children:[e.jsx("div",{className:"w-7 h-7 rounded-full bg-slate-200 dark:bg-pc-surface-2 animate-pulse flex-shrink-0"}),e.jsxs("div",{className:`flex flex-col gap-1.5 ${t%2===0?"items-end":"items-start"}`,children:[e.jsx("div",{className:"h-4 bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse",style:{width:`${120+t*40}px`}}
96),e.jsx("div",{className:"h-4 bg-slate-200 dark:bg-pc-surface-2 rounded animate-pulse",style:{width:`${80+t*30}px`}})]})]},t))}):e.jsxs("div",{className:`flex flex-col h-full min-h-0 ${Cs?"ring-2 ring-inset ring-pc-primary/40 bg-pc-primary/5":""}`,onDragOver:Gs,onDragLeave:Ws,onDrop:Qs,children:[e.jsx("div",{className:"flex-1 relative overflow-hidden",children:e.jsx("div",{ref:Lt,onScroll:Ls,className:"h-full overflow-y-auto",children:e.jsxs("div",{className:`w-full min-h-[76vh] ${T.length===0?"h-full flex flex-col":"space-y-4 pt-6"}`,children:[T.length===0?e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center py-4 sm:py-8",children:oe==="improve"?e.jsx("div",{className:"text-center",children:d?.runFailureContext?e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-xl font-semibold text-pc-text mb-2 tracking-tight",children:"Fix this agent"}),e.jsx("p",{className:"text-[14px] text-pc-text-3 max-w-md leading-relaxed",children:"Describe what went wrong or what changes you'd like to make to fix the failing task."})]}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-xl font-semibold text-pc-text mb-2 tracking-tight",children:"Edit this agent"}),e.jsx("p",{className:"text-[14px] text-pc-text-3 max-w-md leading-relaxed",children:"Describe what changes you'd like to make to this workflow."})]})}):e.jsxs("div",{className:"text-center",children:[e.jsx("h2",{className:"text-xl font-semibold text-pc-text mb-2 tracking-tight",children:"Chat to refine this agent"}),e.jsx("p",{className:"text-[14px] text-pc-text-3 max-w-md leading-relaxed",children:"Ask questions, request changes, or add details to customize this workflow for your needs."})]})}):e.jsxs(e.Fragment,{children:[T.map((t,r)=>e.jsx("div",{className:`flex min-w-0 ${t.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`${t.role==="user"?(Ge?"max-w-[90%]":"max-w-[80%]")+" items-end":"flex-1 items-start"} overflow-hidden flex flex-col gap-1`,children:[t.role==="user"?e.jsxs("div",{className:"min-w-0 px-6 py-4 bg-pc-primary-hover text-pc-text text-[14px] leading-relaxed rounded-tl-xl rounded-tr-xl rounded-bl-xl rounded-br-none",children:[t.attachedFiles&&t.attachedFiles.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 justify-end mb-2",children:t.attachedFiles.map((o,p)=>{const u=o.includes(".")?o.split(".").pop()?.toLowerCase():"",c=u==="pdf",x=["csv","xlsx","xls"].includes(u||""),h=["png","jpg","jpeg","gif","webp"].includes(u||"");return e.jsxs(we,{variant:"running",showDot:!1,className:"normal-case",children:[c?e.jsxs("svg",{className:"w-3 h-3 flex-shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.jsx("polyline",{points:"14 2 14 8 20 8"}),e.jsx("path",{d:"M9 15h6"}),e.jsx("path",{d:"M9 11h6"})]}):x?e.jsxs("svg",{className:"w-3 h-3 flex-shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),e.jsx("line",{x1:"3",y1:"9",x2:"21",y2:"9"}),e.jsx("line",{x1:"3",y1:"15",x2:"21",y2:"15"}),e.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]}):h?e.jsxs("svg",{className:"w-3 h-3 flex-shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),e.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),e.jsx("polyline",{points:"21 15 16 10 5 21"})]}):e.jsx(it,{className:"w-3 h-3 flex-shrink-0"}),e.jsx("span",{className:"max-w-[140px] truncate",children:o})]},p)})}),e.jsx("span",{className:"whitespace-pre-wrap [overflow-wrap:anywhere]",children:wn(t.content)})]}):e.jsxs("div",{className:"min-w-0 text-pc-text",children:[t.isStreaming&&t.agentName&&e.jsx("div",{className:"mb-1",children:e.jsxs(we,{...ks(t.agentName),showDot:!1,children:[e.jsx(Bt,{className:"h-3 w-3"}),t.agentName]})}),t.isStreaming&&!t.agentName&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-pc-primary mb-1",children:[e.jsx(Ve,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Processing..."})]}),e.jsx("div",{className:"break-words overflow-hidden",children:e.jsx(pa,{content:t.content})}),t.boardDraft&&e.jsxs(we,{variant:"neutral",showDot:!1,className:"mt-2",children:[e.jsx(as,{strokeWidth:2.5}),"Board preview updated"]}),t.subAgentMessages&&t.subAgentMessages.length>0&&e.jsx(Nn,{messages:t.subAgentMessages})]}),t.timestamp&&e.jsx("div",{className:`text-[11px] text-slate-400 dark:text-pc-text-4 px-1 ${t.role==="user"?"text-right":"text-left"}`,children:vn(t.timestamp)})]})},t.id)),M&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"w-full max-w-[85%]",children:C==="v2"&&me?e.jsxs("div",{className:"bg-white dark:bg-pc-surface border border-pc-border rounded-tl-xl rounded-tr-xl rounded-br-xl rounded-bl-none p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-pc-primary font-medium",children:[e.jsx(Ve,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:us[me]||me})]}),I&&e.jsx("div",{className:"text-sm text-pc-text-2 border-t border-pc-border pt-2",children:I}),ae.length>0&&e.jsxs("div",{className:"border-t border-pc-border pt-2",children:[e.jsx("div",{className:"text-xs font-medium text-pc-text-3 mb-1",children:"Discovered Tools:"}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[ae.slice(0,5).map((t,r)=>e.jsx(we,{variant:"neutral",children:t.name},r)),ae.length>5&&e.jsxs(we,{variant:"neutral",children:["+",ae.length-5," more"]})]})]})]}):e.jsx(Za,{startTime:_s||void 0})})})]}),e.jsx("div",{ref:ut})]})})}),e.jsx("div",{className:"sticky bottom-0 bg-pc-bg pb-6 flex-shrink-0",children:e.jsxs("div",{className:"max-w-page-content mx-auto w-full relative",children:[P&&!Ge&&e.jsxs("div",{className:"mb-3 flex items-center justify-between bg-white dark:bg-pc-surface border border-pc-border rounded-pc-md px-4 py-3 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-pc-primary/10 flex items-center justify-center",children:e.jsx(as,{className:"w-4 h-4 text-pc-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[13px] font-medium text-pc-text",children:"Agent Ready"}),e.jsx("p",{className:"text-[11px] text-pc-text-3",children:"Your workflow agent has been generated"})]})]}),e.jsxs(L,{variant:"ghost",size:"sm",onClick:()=>le(!0),children:["Agent Preview",e.jsx($e,{})]})]}),$s&&e.jsxs("div",{className:"mb-3 flex items-center gap-3 bg-white dark:bg-pc-surface border border-pc-border rounded-pc-md px-4 py-3 text-[13px] shadow-sm",children:[e.jsx("span",{className:"text-pc-text-2 flex-1",children:"Start a new conversation?"}),e.jsx(L,{variant:"outline",onClick:()=>ft(!1),children:"Cancel"}),e.jsx(L,{onClick:Js,children:"New agent"})]}),e.jsx(bs,{ref:Vt,multiple:!0,accept:".csv,.xlsx,.xls,.json,.txt,.md,.pdf,.doc,.docx,.html,.png,.jpg,.jpeg,.gif,.webp",onChange:Us,"aria-label":"Upload files"}),Ce?.length?e.jsx(Pa,{questions:Ce,answers:Xe,onAnswersChange:De,onSubmit:Ks,onReset:Xt,onStop:Zt,onSkip:Xs,disabled:M,isLoading:M}):e.jsxs("div",{className:`
97              relative bg-white dark:bg-pc-surface rounded-pc-md border border-pc-border
98              shadow-sm
99              transition-all duration-200 ease-out
100              focus-within:border-pc-primary focus-within:shadow-md
101              ${M?"opacity-75":""}
102            `,children:[S.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 px-4 pt-3 pb-1",children:S.map((t,r)=>e.jsxs(we,{variant:"running",showDot:!1,className:"normal-case",onRemove:()=>Hs(r),children:[e.jsx(it,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"max-w-[140px] truncate",title:t.name,children:t.name})]},r))}),e.jsx("textarea",{ref:Ss,value:J,onChange:t=>V(t.target.value),onKeyDown:Vs,placeholder:ht?"Loading board...":"Describe what you want your workflow to do...",disabled:M||ht,rows:1,className:`
103                  w-full resize-none bg-transparent text-[14px] text-pc-text
104                  placeholder:text-pc-text-4 outline-none
105                  px-4 py-3.5
106                  min-h-[52px] max-h-[200px]
107                  ${S.length>0?"pt-2":""}
108                `,style:{fieldSizing:"content"}}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-3",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(L,{variant:"ghost",size:"icon",onClick:()=>Vt.current?.click(),disabled:M||S.length>=ze,"aria-label":"Attach files",title:S.length>=ze?`Max ${ze} files`:"Attach file",children:e.jsx(hs,{})}),e.jsx(L,{variant:"ghost",size:"icon",onClick:Xt,disabled:T.length===0||M,"aria-label":"Reset conversation",title:"Reset",children:e.jsx(Da,{})})]}),e.jsx("div",{className:"flex items-center gap-2",children:M?e.jsxs(L,{variant:"danger-outline",onClick:Zt,children:["Stop",e.jsx(Ba,{})]}):e.jsxs(L,{onClick:jt,disabled:!J.trim()||ht,children:["Send",e.jsx(gs,{})]})})]})]}),pt&&e.jsx(L,{variant:"outline",size:"icon",onClick:qs,className:"absolute -top-12 right-0 z-10 rounded-full shadow-md","aria-label":"Scroll to bottom",title:"Scroll to bottom",children:e.jsx(Je,{})})]})})]})})]})}
108),e.jsx(Ct.Panel,{title:"Agent Preview",footer:la,children:P?e.jsxs("div",{className:"space-y-4 py-6",children:[e.jsx(ln,{boardDraft:P,configValues:ge,onConfigValuesChange:Ie,onSaveConfig:ta,isSavingConfig:Ns}),Ke&&xe&&e.jsxs(e.Fragment,{children:[e.jsx(dn,{run:Ke,board:xe,onFixWithAI:sa,onRunAgain:es,onDismiss:()=>{ke(null),ue(null),he(null)}}),Ke.status==="completed"&&(Rt||At)&&e.jsx(Va,{run:Ke,board:xe,lazyOutput:Rt,outputLoading:At,className:"agent-preview-output"})]})]}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-pc-text-3 text-sm py-20",children:"No board generated yet"})}),xe&&e.jsx(La,{open:ys,onOpenChange:Se,board:xe,onRunStarted:Zs,testRun:!0,testDataSets:Mt?[Mt]:[],onGenerateTestData:ea,isGeneratingTestData:dt})]})}export{dr as CrewBuilderPage,yn as validateFile};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.