crewly 1.20.372 → 1.20.374

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/backend/backend/src/constants.d.ts +2 -0
  2. package/dist/backend/backend/src/constants.d.ts.map +1 -1
  3. package/dist/backend/backend/src/constants.js +2 -0
  4. package/dist/backend/backend/src/constants.js.map +1 -1
  5. package/dist/backend/backend/src/services/cloud/cloud-client.service.d.ts +23 -0
  6. package/dist/backend/backend/src/services/cloud/cloud-client.service.d.ts.map +1 -1
  7. package/dist/backend/backend/src/services/cloud/cloud-client.service.js +57 -3
  8. package/dist/backend/backend/src/services/cloud/cloud-client.service.js.map +1 -1
  9. package/dist/backend/backend/src/services/cloud/cloud-initializer.d.ts.map +1 -1
  10. package/dist/backend/backend/src/services/cloud/cloud-initializer.js +5 -1
  11. package/dist/backend/backend/src/services/cloud/cloud-initializer.js.map +1 -1
  12. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-retro.js +1 -1
  13. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-retro.js.map +1 -1
  14. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-stats.d.ts +2 -0
  15. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-stats.d.ts.map +1 -1
  16. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-stats.js +12 -1
  17. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-stats.js.map +1 -1
  18. package/dist/backend/backend/src/services/trace/trace-context.service.d.ts +1 -1
  19. package/dist/backend/backend/src/services/trace/trace-context.service.d.ts.map +1 -1
  20. package/dist/backend/backend/src/services/trace/trace-context.service.js +7 -5
  21. package/dist/backend/backend/src/services/trace/trace-context.service.js.map +1 -1
  22. package/dist/backend/backend/src/services/trace/trace-markers.d.ts +17 -0
  23. package/dist/backend/backend/src/services/trace/trace-markers.d.ts.map +1 -1
  24. package/dist/backend/backend/src/services/trace/trace-markers.js +25 -0
  25. package/dist/backend/backend/src/services/trace/trace-markers.js.map +1 -1
  26. package/dist/backend/backend/src/services/trace/trace-metrics.d.ts +19 -1
  27. package/dist/backend/backend/src/services/trace/trace-metrics.d.ts.map +1 -1
  28. package/dist/backend/backend/src/services/trace/trace-metrics.js +36 -6
  29. package/dist/backend/backend/src/services/trace/trace-metrics.js.map +1 -1
  30. package/dist/backend/backend/src/services/trace/trace-summary.js +1 -1
  31. package/dist/backend/backend/src/services/trace/trace-summary.js.map +1 -1
  32. package/dist/backend/backend/src/services/trace/trace-timeline.d.ts.map +1 -1
  33. package/dist/backend/backend/src/services/trace/trace-timeline.js +1 -0
  34. package/dist/backend/backend/src/services/trace/trace-timeline.js.map +1 -1
  35. package/dist/backend/build-info.json +2 -2
  36. package/dist/cli/backend/src/constants.d.ts +2 -0
  37. package/dist/cli/backend/src/constants.d.ts.map +1 -1
  38. package/dist/cli/backend/src/constants.js +2 -0
  39. package/dist/cli/backend/src/constants.js.map +1 -1
  40. package/dist/cli/backend/src/services/cloud/cloud-client.service.d.ts +23 -0
  41. package/dist/cli/backend/src/services/cloud/cloud-client.service.d.ts.map +1 -1
  42. package/dist/cli/backend/src/services/cloud/cloud-client.service.js +57 -3
  43. package/dist/cli/backend/src/services/cloud/cloud-client.service.js.map +1 -1
  44. package/dist/cli/backend/src/services/trace/trace-context.service.d.ts +1 -1
  45. package/dist/cli/backend/src/services/trace/trace-context.service.d.ts.map +1 -1
  46. package/dist/cli/backend/src/services/trace/trace-context.service.js +7 -5
  47. package/dist/cli/backend/src/services/trace/trace-context.service.js.map +1 -1
  48. package/dist/cli/backend/src/services/trace/trace-markers.d.ts +17 -0
  49. package/dist/cli/backend/src/services/trace/trace-markers.d.ts.map +1 -1
  50. package/dist/cli/backend/src/services/trace/trace-markers.js +25 -0
  51. package/dist/cli/backend/src/services/trace/trace-markers.js.map +1 -1
  52. package/frontend/dist/assets/{index-b1fc60ea.js → index-b4db6abe.js} +2 -2
  53. package/frontend/dist/index.html +1 -1
  54. package/package.json +1 -1
@@ -4949,7 +4949,7 @@ Describe the ${v.toLowerCase()}…`,rows:16,className:"font-mono text-xs","data-
4949
4949
  Deployed to staging
4950
4950
  95% code coverage`})]}),A&&i.jsx("div",{"data-testid":"create-mission-error",children:i.jsx(Ye,{variant:"error",children:A})})]})}),i.jsxs(Jo,{children:[i.jsx(de,{variant:"ghost",size:"sm",onClick:e,disabled:k,children:"Cancel"}),i.jsx(de,{variant:"primary",size:"sm",onClick:z,loading:k,"data-testid":"create-mission-submit",children:k?"Creating...":"Create goal"})]})]}):null},wX={number:"count",percentage:"%",boolean:"done",currency:"$"},Vz={number:"Number",percentage:"Percentage",boolean:"Yes / No",currency:"Currency"},Kz={title:"",metricType:"number",baseline:"0",target:"",unit:wX.number,measurementSource:"manual"};function NBe(t){if(!t)return"never";try{return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return t}}function cx(t){if(t.trim()==="")return null;const e=Number(t);return Number.isFinite(e)?e:null}const MBe=({missionId:t,onChanged:e})=>{const[n,s]=_.useState([]),[r,a]=_.useState(!0),[o,l]=_.useState(null),[c,d]=_.useState(null),[u,h]=_.useState(!1),[f,p]=_.useState(!1),[x,v]=_.useState(Kz),[m,g]=_.useState(null),[y,b]=_.useState(""),[S,E]=_.useState(""),[k,T]=_.useState(null),[A,M]=_.useState(null),[N,L]=_.useState(null),I=_.useCallback(async()=>{l(null);try{const R=await lt.getKeyResults(t);s(R)}catch(R){l(R instanceof Error?R.message:"Failed to load key results")}finally{a(!1)}},[t]);_.useEffect(()=>{a(!0),I()},[I]);const D=_.useCallback(async R=>{h(!0),d(null);try{return await R(),await I(),e==null||e(),!0}catch(F){return d(F instanceof Error?F.message:"Request failed"),!1}finally{h(!1)}},[I,e]),z=async()=>{const R=cx(x.baseline),F=cx(x.target);if(!x.title.trim()){d("Title is required");return}if(R===null||F===null){d("Baseline and target must be numbers");return}if(R===F){d("Baseline and target must be different");return}if(!x.unit.trim()){d("Unit is required");return}const q={title:x.title.trim(),metricType:x.metricType,baseline:R,target:F,unit:x.unit.trim(),measurementSource:x.measurementSource};await D(async()=>{await lt.createKeyResult(t,q)})&&(v(Kz),p(!1))},U=R=>{d(null),T(null),g(R.id),b(String(R.current)),E("")},G=async R=>{const F=cx(y);if(F===null){d("Measurement value must be a number");return}await D(async()=>{await lt.measureKeyResult(t,R,{value:F,source:"user",...S.trim()?{note:S.trim()}:{}})})&&g(null)},K=R=>{d(null),g(null),T(R.id),M({target:String(R.target),current:String(R.current),measurementSource:R.measurementSource})},P=async R=>{if(!A)return;const F=cx(A.target),q=cx(A.current);if(F===null||q===null){d("Target and current must be numbers");return}if(F===R.baseline){d("Target must differ from the baseline");return}await D(async()=>{await lt.updateKeyResult(t,R.id,{...F!==R.target?{target:F}:{},...q!==R.current?{current:q}:{},...A.measurementSource!==R.measurementSource?{measurementSource:A.measurementSource}:{}})})&&(T(null),M(null))},B=async()=>{if(!N)return;const R=N;await D(async()=>{await lt.deleteKeyResult(t,R)})&&L(null)};return i.jsxs(tn,{variant:"default",padding:"md",className:"border border-border-dark","data-testid":"key-results-section",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 gap-2",children:[i.jsxs("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wide flex items-center gap-1.5",children:[i.jsx(DH,{className:"h-4 w-4"}),"Key Results (",n.length,")"]}),i.jsx(de,{variant:"ghost",size:"sm",icon:f?ys:qn,onClick:()=>{p(R=>!R),d(null)},"data-testid":"kr-add-toggle",children:f?"Cancel":"Add KR"})]}),c&&i.jsx("div",{className:"mb-3","data-testid":"kr-action-error",children:i.jsx(Ye,{variant:"error",onClose:()=>d(null),children:c})}),f&&i.jsxs("div",{className:"mb-4 rounded-lg border border-border-dark bg-background-dark/60 p-3 space-y-2","data-testid":"kr-add-form",children:[i.jsx(ss,{"aria-label":"KR title",placeholder:"e.g. Reach $5k MRR",value:x.title,onChange:R=>v(F=>({...F,title:R.target.value})),fullWidth:!0,"data-testid":"kr-new-title"}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[i.jsx(xn,{"aria-label":"Metric type",value:x.metricType,onChange:R=>{const F=R.target.value;v(q=>({...q,metricType:F,unit:wX[F]}))},"data-testid":"kr-new-metric",children:mue.map(R=>i.jsx("option",{value:R,children:Vz[R]},R))}),i.jsx(ss,{"aria-label":"Baseline",type:"number",placeholder:"Baseline",value:x.baseline,onChange:R=>v(F=>({...F,baseline:R.target.value})),"data-testid":"kr-new-baseline"}),i.jsx(ss,{"aria-label":"Target",type:"number",placeholder:"Target",value:x.target,onChange:R=>v(F=>({...F,target:R.target.value})),"data-testid":"kr-new-target"}),i.jsx(ss,{"aria-label":"Unit",placeholder:"Unit",value:x.unit,onChange:R=>v(F=>({...F,unit:R.target.value})),"data-testid":"kr-new-unit"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(xn,{"aria-label":"Measurement source",value:x.measurementSource,onChange:R=>v(F=>({...F,measurementSource:R.target.value})),"data-testid":"kr-new-source",children:LB.map(R=>i.jsx("option",{value:R,children:rA[R]},R))}),i.jsx(de,{variant:"primary",size:"sm",onClick:z,disabled:u,"data-testid":"kr-new-submit",children:u?"Saving…":"Create KR"})]})]}),r?i.jsx("p",{className:"text-sm text-text-secondary-dark","data-testid":"kr-loading",children:"Loading key results…"}):o?i.jsx("div",{"data-testid":"kr-error",children:i.jsxs(Ye,{variant:"error",children:[o,i.jsx(de,{variant:"ghost",size:"sm",onClick:()=>{a(!0),I()},className:"mt-2",children:"Retry"})]})}):n.length===0?i.jsx("p",{className:"text-sm text-text-secondary-dark","data-testid":"kr-empty",children:"No key results yet. Add one to make this mission measurable."}):i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full text-sm","data-testid":"kr-table",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"text-left text-[11px] uppercase tracking-wide text-text-secondary-dark border-b border-border-dark",children:[i.jsx("th",{className:"py-2 pr-3 font-medium",children:"Key result"}),i.jsx("th",{className:"py-2 pr-3 font-medium",children:"Type"}),i.jsx("th",{className:"py-2 pr-3 font-medium whitespace-nowrap",children:"Baseline → Current → Target"}),i.jsx("th",{className:"py-2 pr-3 font-medium min-w-[140px]",children:"Progress"}),i.jsx("th",{className:"py-2 pr-3 font-medium",children:"Status"}),i.jsx("th",{className:"py-2 pr-3 font-medium",children:"Source"}),i.jsx("th",{className:"py-2 pr-3 font-medium whitespace-nowrap",children:"Last measured"}),i.jsx("th",{className:"py-2 font-medium text-right",children:"Actions"})]})}),i.jsx("tbody",{children:n.map(R=>{var ne;const F=X$(R),q=(ne=R.measurements)==null?void 0:ne[0],$=m===R.id,re=k===R.id&&A!==null;return i.jsxs(an.Fragment,{children:[i.jsxs("tr",{className:"border-b border-border-dark/60 align-top","data-testid":`kr-row-${R.id}`,children:[i.jsx("td",{className:"py-2 pr-3 text-text-primary-dark font-medium",children:R.title}),i.jsx("td",{className:"py-2 pr-3 text-text-secondary-dark",children:Vz[R.metricType]}),i.jsxs("td",{className:"py-2 pr-3 font-mono text-xs text-text-primary-dark whitespace-nowrap","data-testid":`kr-values-${R.id}`,children:[iA(R.baseline,R.metricType,R.unit),i.jsx("span",{className:"text-text-secondary-dark",children:" → "}),i.jsx("span",{className:"font-semibold",children:iA(R.current,R.metricType,R.unit)}),i.jsx("span",{className:"text-text-secondary-dark",children:" → "}),iA(R.target,R.metricType,R.unit)]}),i.jsx("td",{className:"py-2 pr-3",children:i.jsx(dw,{percent:F,status:R.status,"data-testid":`kr-progress-${R.id}`})}),i.jsx("td",{className:"py-2 pr-3",children:i.jsx(mn,{variant:gue[R.status],size:"sm","data-testid":`kr-status-${R.id}`,children:n2[R.status]})}),i.jsx("td",{className:"py-2 pr-3 text-xs text-text-secondary-dark",children:rA[R.measurementSource]??R.measurementSource}),i.jsx("td",{className:"py-2 pr-3 text-xs text-text-secondary-dark whitespace-nowrap","data-testid":`kr-last-${R.id}`,children:NBe(q==null?void 0:q.measuredAt)}),i.jsx("td",{className:"py-2 text-right whitespace-nowrap",children:i.jsxs("div",{className:"inline-flex items-center gap-1",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:Oee,onClick:()=>U(R),disabled:u,"data-testid":`kr-measure-${R.id}`,"aria-label":"Record measurement",children:"Measure"}),i.jsx(de,{variant:"ghost",size:"icon",className:"h-8 w-8",icon:Lh,onClick:()=>K(R),disabled:u,"data-testid":`kr-edit-${R.id}`,"aria-label":"Edit key result"}),i.jsx(de,{variant:"danger-ghost",size:"icon",className:"h-8 w-8",icon:Qs,onClick:()=>L(R.id),disabled:u,"data-testid":`kr-delete-${R.id}`,"aria-label":"Delete key result"})]})})]}),$&&i.jsx("tr",{className:"border-b border-border-dark/60 bg-background-dark/40","data-testid":`kr-measure-form-${R.id}`,children:i.jsx("td",{colSpan:8,className:"py-2 px-2",children:i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx("span",{className:"text-xs text-text-secondary-dark",children:"Record measurement:"}),i.jsx(ss,{"aria-label":"Measurement value",type:"number",value:y,onChange:J=>b(J.target.value),className:"w-32","data-testid":`kr-measure-value-${R.id}`}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:R.unit}),i.jsx(ss,{"aria-label":"Measurement note",placeholder:"Note (optional)",value:S,onChange:J=>E(J.target.value),className:"flex-1 min-w-[160px]","data-testid":`kr-measure-note-${R.id}`}),i.jsx(de,{variant:"primary",size:"sm",icon:Xd,onClick:()=>G(R.id),disabled:u,"data-testid":`kr-measure-submit-${R.id}`,children:u?"Saving…":"Save"}),i.jsx(de,{variant:"ghost",size:"sm",onClick:()=>g(null),disabled:u,children:"Cancel"})]})})}),re&&A&&i.jsx("tr",{className:"border-b border-border-dark/60 bg-background-dark/40","data-testid":`kr-edit-form-${R.id}`,children:i.jsx("td",{colSpan:8,className:"py-2 px-2",children:i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx("span",{className:"text-xs text-text-secondary-dark",children:"Edit:"}),i.jsx("label",{className:"text-xs text-text-secondary-dark",children:"Target"}),i.jsx(ss,{"aria-label":"Edit target",type:"number",value:A.target,onChange:J=>M(H=>H&&{...H,target:J.target.value}),className:"w-28","data-testid":`kr-edit-target-${R.id}`}),i.jsx("label",{className:"text-xs text-text-secondary-dark",children:"Current"}),i.jsx(ss,{"aria-label":"Edit current",type:"number",value:A.current,onChange:J=>M(H=>H&&{...H,current:J.target.value}),className:"w-28","data-testid":`kr-edit-current-${R.id}`}),i.jsx(xn,{"aria-label":"Edit measurement source",value:A.measurementSource,onChange:J=>M(H=>H&&{...H,measurementSource:J.target.value}),"data-testid":`kr-edit-source-${R.id}`,children:LB.map(J=>i.jsx("option",{value:J,children:rA[J]},J))}),i.jsx(de,{variant:"primary",size:"sm",icon:Xd,onClick:()=>P(R),disabled:u,"data-testid":`kr-edit-submit-${R.id}`,children:u?"Saving…":"Save"}),i.jsx(de,{variant:"ghost",size:"sm",onClick:()=>{T(null),M(null)},disabled:u,children:"Cancel"})]})})})]},R.id)})})]})}),i.jsx(G0,{isOpen:N!==null,title:"Delete key result",message:"This removes the key result and its measurement history. This cannot be undone.",confirmLabel:"Delete",confirmVariant:"danger",loading:u,onCancel:()=>L(null),onConfirm:B})]})},jBe={continue:"Continue",adjust_strategy:"Adjust strategy",replan:"Replan",escalate:"Escalate"};function qz(t,e){return e.get(t)??t.slice(0,8)}const RBe=({missionId:t,level:e,parentMissionId:n,missionNames:s,refreshKey:r=0})=>{const a=cs(),[o,l]=_.useState(null),[c,d]=_.useState(!0),[u,h]=_.useState(null),f=_.useCallback(async()=>{d(!0),h(null);try{l(await lt.getCascadeSummary(t))}catch(p){h(p instanceof Error?p.message:"Failed to load cascade")}finally{d(!1)}},[t]);return _.useEffect(()=>{f()},[f,r]),i.jsxs(tn,{variant:"default",padding:"md",className:"border border-border-dark","data-testid":"cascade-section",children:[i.jsxs("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wide mb-3 flex items-center gap-1.5",children:[i.jsx(S0,{className:"h-4 w-4"}),"Cascade"]}),i.jsxs("div",{className:"mb-3",children:[i.jsx("span",{className:"text-text-secondary-dark text-xs uppercase tracking-wide block mb-1",children:"Parent"}),n?i.jsx(de,{type:"button",variant:"link",icon:U1,onClick:()=>a(qt.goal(n)),className:"text-left","data-testid":"cascade-parent-link",children:qz(n,s)}):i.jsxs("span",{className:"text-sm text-text-secondary-dark","data-testid":"cascade-parent-none",children:["None — this is a ",e," root."]})]}),c?i.jsx("p",{className:"text-sm text-text-secondary-dark","data-testid":"cascade-loading",children:"Loading roll-up…"}):u?i.jsx("div",{"data-testid":"cascade-error",children:i.jsx(Ye,{variant:"error",children:u})}):o?i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{"data-testid":"cascade-rollup",children:[i.jsxs("div",{className:"flex items-center justify-between mb-1",children:[i.jsx("span",{className:"text-text-secondary-dark text-xs uppercase tracking-wide",children:"Rolled-up progress"}),i.jsx("span",{className:"text-[11px] text-text-secondary-dark","data-testid":"cascade-recommendation",children:jBe[o.recommendation]??o.recommendation})]}),i.jsx(dw,{percent:o.rolledUpProgress,"data-testid":"cascade-rollup-bar"}),i.jsxs("div",{className:"mt-1 flex items-center justify-between gap-2 flex-wrap",children:[i.jsxs("span",{className:"text-[11px] text-text-secondary-dark",children:["Own progress ",Math.round(o.overallProgress),"% · ",o.totalKRs," KR",o.totalKRs===1?"":"s"]}),i.jsx(Q$,{counts:J$(o)})]})]}),i.jsxs("div",{children:[i.jsxs("span",{className:"text-text-secondary-dark text-xs uppercase tracking-wide block mb-1",children:["Children (",o.childMissionCount,")"]}),o.children.length===0?i.jsx("p",{className:"text-sm text-text-secondary-dark","data-testid":"cascade-children-empty",children:"No approved child missions."}):i.jsx("ul",{className:"space-y-2","data-testid":"cascade-children",children:o.children.map(p=>i.jsx("li",{"data-testid":`cascade-child-${p.missionId}`,children:i.jsxs("button",{type:"button",onClick:()=>a(qt.goal(p.missionId)),className:"w-full text-left rounded-lg border border-border-dark px-3 py-2 hover:border-primary/30 transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(cI,{level:p.level}),i.jsx("span",{className:"text-sm text-text-primary-dark truncate",children:qz(p.missionId,s)}),p.childMissionCount>0&&i.jsxs("span",{className:"text-[11px] text-text-secondary-dark ml-auto flex-shrink-0",children:[p.childMissionCount," child",p.childMissionCount===1?"":"ren"]})]}),i.jsx(dw,{percent:p.rolledUpProgress,"data-testid":`cascade-child-progress-${p.missionId}`})]})},p.missionId))})]})]}):null]})},IBe=({parentMissionId:t,onDecided:e})=>{const n=cs(),[s,r]=_.useState([]),[a,o]=_.useState(!1),l=_.useCallback(async()=>{try{r(await lt.getProposals(t))}catch{r([])}finally{o(!0)}},[t]);_.useEffect(()=>{l()},[l]);const c=d=>{r(u=>u.filter(h=>h.id!==d.id)),e==null||e(d)};return!a||s.length===0?null:i.jsxs(tn,{variant:"default",padding:"md",className:"border border-yellow-500/40","data-testid":"proposals-section",children:[i.jsxs("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wide mb-3 flex items-center gap-1.5",children:[i.jsx(VS,{className:"h-4 w-4 text-yellow-400"}),"Proposals awaiting approval (",s.length,")"]}),i.jsx("ul",{className:"space-y-2",children:s.map(d=>{var u,h,f,p,x;return i.jsx("li",{className:"rounded-lg border border-border-dark px-3 py-2","data-testid":`proposal-${d.id}`,children:i.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[d.level&&i.jsx(cI,{level:d.level}),i.jsx("button",{type:"button",onClick:()=>n(qt.goal(d.id)),className:"text-sm font-medium text-text-primary-dark hover:text-primary text-left","data-testid":`proposal-link-${d.id}`,children:d.objective})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap text-[11px] text-text-secondary-dark",children:[i.jsxs(mn,{variant:"default",size:"sm",children:["Team: ",d.ownerTeamId.slice(0,16)]}),((u=d.approval)==null?void 0:u.proposedBy)&&i.jsxs("span",{children:["Proposed by ",d.approval.proposedBy]}),(((h=d.keyResults)==null?void 0:h.length)??0)>0&&i.jsxs("span",{children:[(f=d.keyResults)==null?void 0:f.length," KR",((p=d.keyResults)==null?void 0:p.length)===1?"":"s"]})]}),((x=d.successCriteria)==null?void 0:x.length)>0&&i.jsx("ul",{className:"mt-1 text-xs text-text-secondary-dark list-disc pl-4",children:d.successCriteria.slice(0,3).map((v,m)=>i.jsx("li",{children:v},m))})]}),i.jsx(iP,{missionId:d.id,onDecided:c})]})},d.id)})})]})},LBe=[{key:"completedTasks",label:"Done",dot:"bg-emerald-500"},{key:"runningTasks",label:"Running",dot:"bg-blue-500"},{key:"queuedTasks",label:"Queued",dot:"bg-border-dark"},{key:"blockedTasks",label:"Blocked",dot:"bg-amber-500"},{key:"failedTasks",label:"Failed",dot:"bg-rose-500"}],PBe=({missionId:t,refreshKey:e=0})=>{const[n,s]=_.useState(null),[r,a]=_.useState(!0),[o,l]=_.useState(null),c=_.useCallback(async()=>{a(!0),l(null);try{s(await lt.getMissionProgress(t))}catch(d){l(d instanceof Error?d.message:"Failed to load progress")}finally{a(!1)}},[t]);return _.useEffect(()=>{c()},[c,e]),i.jsxs(tn,{variant:"default",padding:"md",className:"border border-border-dark","data-testid":"mission-progress-section",children:[i.jsxs("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wide mb-3 flex items-center gap-1.5",children:[i.jsx(du,{className:"h-4 w-4"}),"Execution Progress"]}),r?i.jsx("p",{className:"text-sm text-text-secondary-dark","data-testid":"mission-progress-loading",children:"Loading progress…"}):o?i.jsx("div",{"data-testid":"mission-progress-error",children:i.jsx(Ye,{variant:"error",children:o})}):n?i.jsxs("div",{className:"space-y-3 text-sm",children:[i.jsx(dw,{percent:n.progressPercent,label:`${n.completedTasks}/${n.totalTasks} tasks`,"data-testid":"mission-progress-bar"}),n.totalTasks===0?i.jsx("p",{className:"text-xs text-text-secondary-dark","data-testid":"mission-progress-empty",children:"No work items under this mission yet."}):i.jsx("ul",{className:"space-y-1.5","data-testid":"mission-progress-rows",children:LBe.map(d=>i.jsxs("li",{className:"flex items-center justify-between","data-testid":`mission-progress-${d.key}`,children:[i.jsxs("span",{className:"flex items-center gap-2 text-text-secondary-dark",children:[i.jsx("span",{className:`inline-block h-2 w-2 rounded-full ${d.dot}`}),d.label]}),i.jsx("span",{className:"text-text-primary-dark font-mono text-xs",children:n[d.key]})]},d.key))}),i.jsxs("div",{className:"flex items-center justify-between border-t border-border-dark pt-2",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Phase"}),i.jsx("span",{className:"text-text-primary-dark font-mono text-xs",children:n.phase})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Cost"}),i.jsxs("span",{className:"text-text-primary-dark font-mono text-xs","data-testid":"mission-progress-cost",children:["$",n.totalCost.toFixed(2)]})]})]}):null]})};function ep(t){try{return new Date(t).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return t}}function DBe(t){var e,n,s,r;return{objective:t.objective,status:t.status,priority:t.priority??"medium",ownerTeamId:t.ownerTeamId,currentStrategy:t.currentStrategy??"",cadence:t.cadence??"",successCriteriaText:(t.successCriteria??[]).join(`
4951
4951
  `),periodLabel:((e=t.period)==null?void 0:e.label)??"",periodType:((n=t.period)==null?void 0:n.type)??"",periodStart:(s=t.period)!=null&&s.startDate?t.period.startDate.slice(0,10):"",periodEnd:(r=t.period)!=null&&r.endDate?t.period.endDate.slice(0,10):"",parentMissionId:t.parentMissionId??""}}function OBe(t){const e={objective:t.objective.trim(),status:t.status,priority:t.priority,ownerTeamId:t.ownerTeamId.trim(),currentStrategy:t.currentStrategy,cadence:t.cadence.trim(),successCriteria:t.successCriteriaText.split(`
4952
- `).map(n=>n.trim()).filter(Boolean),parentMissionId:t.parentMissionId||""};return t.periodType&&t.periodStart&&t.periodEnd?e.period={type:t.periodType,startDate:new Date(t.periodStart).toISOString(),endDate:new Date(t.periodEnd).toISOString(),...t.periodLabel?{label:t.periodLabel}:{}}:!t.periodType&&!t.periodStart&&!t.periodEnd&&(e.period=null),e}const EX=()=>{var re,ne,J,H,X;const{id:t}=Lc(),e=cs(),[n,s]=_.useState(null),[r,a]=_.useState(!0),[o,l]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[f,p]=_.useState(null),[x,v]=_.useState(!1),[m,g]=_.useState(null),[y,b]=_.useState(new Map),[S,E]=_.useState(new Map),[k,T]=_.useState(new Map),[A,M]=_.useState(0),N=_.useCallback(async(Z=!0)=>{if(t){Z?a(!0):d(!0),l(null);try{const oe=await lt.getMission(t);s(oe)}catch(oe){const ye=oe instanceof Error?oe.message:"Failed to load goal";l(ye)}finally{a(!1),d(!1)}}},[t]);_.useEffect(()=>{N()},[N]),_.useEffect(()=>{let Z=!1;return(async()=>{try{const oe=await lt.getMissions();if(Z)return;b(new Map(oe.map(ye=>[ye.id,ye.objective]))),E(new Map(oe.map(ye=>[ye.id,{level:ye.level,parentMissionId:ye.parentMissionId}])))}catch{}})(),()=>{Z=!0}},[t]),_.useEffect(()=>{let Z=!1;return(async()=>{try{const oe=await lt.getTeams();!Z&&Array.isArray(oe)&&T(new Map(oe.map(ye=>[ye.id,ye.name])))}catch{}})(),()=>{Z=!0}},[]);const L=_.useCallback(()=>{M(Z=>Z+1),N(!1)},[N]),I=_.useCallback(Z=>{s(oe=>oe&&oe.id===Z.id?{...oe,...Z}:oe),L()},[L]),D=_.useCallback(()=>{n&&(p(DBe(n)),g(null),h(!0))},[n]),z=_.useCallback(()=>{h(!1),p(null),g(null)},[]),U=_.useCallback(async()=>{if(!(!t||!f)){if(!f.objective.trim()){g("Objective cannot be empty.");return}if(!f.ownerTeamId.trim()){g("Owner team cannot be empty.");return}v(!0),g(null);try{const Z=await lt.updateMission(t,OBe(f));s(Z),h(!1),p(null)}catch(Z){const oe=Z instanceof Error?Z.message:"Failed to save goal";g(oe)}finally{v(!1)}}},[t,f]),G=_.useMemo(()=>(Z,oe)=>{p(ye=>ye&&{...ye,[Z]:oe})},[]);if(r)return i.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:i.jsx(zt,{size:"xl",text:"Loading goal..."})});if(o)return i.jsxs("div",{className:"p-6 max-w-[1000px] mx-auto","data-testid":"mission-detail-error",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:Fa,onClick:()=>e(qt.goals()),className:"mb-6",children:"Back to Goals"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsxs("div",{className:"flex flex-col items-center text-center py-8",children:[i.jsx("p",{className:"text-red-400 mb-2",children:o}),i.jsx(de,{variant:"secondary",size:"sm",icon:$t,onClick:()=>N(),children:"Retry"})]})})]});if(!n)return i.jsxs("div",{className:"p-6 max-w-[1000px] mx-auto",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:Fa,onClick:()=>e(qt.goals()),className:"mb-6",children:"Back to Goals"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsx(is,{icon:ay,title:"Goal not found.",compact:!0})})]});const K=lI(n,S),P=(re=n.approval)==null?void 0:re.state,B=bX(n),R=vX(n.ownerTeamId,k),F=u&&!!f,q=(Z,oe,ye)=>i.jsxs("div",{className:"flex items-baseline justify-between gap-4 border-t border-border-soft py-2 text-sm first:border-t-0","data-testid":ye,children:[i.jsx("dt",{className:"shrink-0 text-text-2",children:Z}),i.jsx("dd",{className:"min-w-0 text-right text-text",children:oe})]}),$="mb-2 text-[13px] font-semibold text-text-2";return i.jsxs("div",{className:"p-6 max-w-5xl mx-auto","data-testid":"mission-detail-page",children:[i.jsx(_r,{eyebrow:i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:Yt.teams,className:"text-text-2 hover:text-text",children:"Teams"}),i.jsx(cr,{className:"h-3.5 w-3.5 text-text-3","aria-hidden":"true"}),i.jsx(hs,{to:qt.goals(),className:"text-text-2 hover:text-text","data-testid":"mission-detail-back",children:"Goals"})]}),title:F?"Edit goal":n.objective,subtitle:i.jsxs("span",{className:"inline-flex flex-wrap items-center gap-x-1.5",children:[i.jsx("span",{"data-testid":`level-badge-${K}`,children:dc[K]}),i.jsx("span",{className:"text-text-3",children:"·"}),i.jsx(sn,{tone:B.tone,children:B.label}),n.priority&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-3",children:"·"}),i.jsxs("span",{children:[QM[n.priority]," priority"]})]}),((ne=n.period)==null?void 0:ne.label)&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-3",children:"·"}),i.jsx("span",{children:n.period.label})]}),i.jsx("span",{className:"text-text-3",children:"·"}),i.jsx("span",{title:k.has(n.ownerTeamId)?void 0:`Team id ${n.ownerTeamId}`,children:R})]}),actions:F?i.jsxs(i.Fragment,{children:[i.jsx(de,{variant:"primary",size:"sm",icon:Xd,onClick:U,disabled:x,"data-testid":"mission-save",children:x?"Saving…":"Save"}),i.jsx(de,{variant:"ghost",size:"sm",icon:ys,onClick:z,disabled:x,"data-testid":"mission-cancel",children:"Cancel"})]}):i.jsxs(i.Fragment,{children:[i.jsx(de,{variant:"primary",size:"sm",icon:Lh,onClick:D,"data-testid":"mission-edit",children:"Edit"}),i.jsx(Co,{icon:pa,label:"More goal actions",buttonClassName:"inline-flex h-9 w-9 items-center justify-center rounded-2xl border border-border-soft text-text-2 transition-colors hover:bg-surface-hover hover:text-text",items:[{label:c?"Refreshing…":"Refresh",icon:$t,onClick:()=>N(!1),disabled:c}]})]})}),P&&P!=="pending_approval"&&((J=n.approval)==null?void 0:J.decidedAt)&&!F&&i.jsx("div",{className:"mb-4",children:i.jsx(s2,{state:P})}),P==="pending_approval"&&!F&&i.jsxs("div",{className:"mb-6 flex flex-wrap items-center gap-3","data-testid":"mission-pending-banner",children:[i.jsx(s2,{state:P}),i.jsxs("span",{className:"text-[13px] text-attention",children:["Proposed",(H=n.approval)!=null&&H.proposedBy?` by ${n.approval.proposedBy}`:"",". Waiting for your decision."]}),i.jsx(iP,{missionId:n.id,onDecided:I})]}),P==="rejected"&&((X=n.approval)==null?void 0:X.rejectionReason)&&i.jsxs("p",{className:"mb-4 text-[13px] text-danger","data-testid":"mission-rejection-reason",children:["Rejected: ",n.approval.rejectionReason]}),m&&i.jsx("div",{"data-testid":"mission-save-error",className:"mb-4",children:i.jsx(Ye,{variant:"error",onClose:()=>g(null),children:m})}),F&&f?i.jsxs("div",{className:"flex flex-col gap-4 rounded-2xl border border-border-soft p-5","data-testid":"mission-edit-form",children:[i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Objective",i.jsx(ss,{"aria-label":"Objective",value:f.objective,onChange:Z=>G("objective",Z.target.value),fullWidth:!0,"data-testid":"edit-objective"})]}),i.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Status",i.jsxs(xn,{value:f.status,onChange:Z=>G("status",Z.target.value),"data-testid":"edit-status",children:[i.jsx("option",{value:"active",children:"Active"}),i.jsx("option",{value:"paused",children:"Paused"}),i.jsx("option",{value:"completed",children:"Completed"}),i.jsx("option",{value:"cancelled",children:"Cancelled"})]})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Priority",i.jsxs(xn,{value:f.priority,onChange:Z=>G("priority",Z.target.value),"data-testid":"edit-priority",children:[i.jsx("option",{value:"critical",children:"Critical"}),i.jsx("option",{value:"high",children:"High"}),i.jsx("option",{value:"medium",children:"Medium"}),i.jsx("option",{value:"low",children:"Low"})]})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Owner team",i.jsx(ss,{"aria-label":"Owner Team",value:f.ownerTeamId,onChange:Z=>G("ownerTeamId",Z.target.value),fullWidth:!0,"data-testid":"edit-owner-team"})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Parent goal",i.jsx(ss,{"aria-label":"Parent Mission ID",placeholder:"(none)",value:f.parentMissionId,onChange:Z=>G("parentMissionId",Z.target.value),fullWidth:!0,"data-testid":"edit-parent"})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Review cadence (cron)",i.jsx(ss,{"aria-label":"Cadence",value:f.cadence,onChange:Z=>G("cadence",Z.target.value),fullWidth:!0,"data-testid":"edit-cadence"})]})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Current strategy",i.jsx(er,{"aria-label":"Current Strategy",rows:4,value:f.currentStrategy,onChange:Z=>G("currentStrategy",Z.target.value),"data-testid":"edit-strategy"})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Success criteria (one per line)",i.jsx(er,{"aria-label":"Success Criteria (one per line)",rows:5,placeholder:"One criterion per line",value:f.successCriteriaText,onChange:Z=>G("successCriteriaText",Z.target.value),"data-testid":"edit-success-criteria"})]}),i.jsxs("fieldset",{className:"flex flex-col gap-2",children:[i.jsx("legend",{className:"mb-1 text-sm text-text-2",children:"OKR period"}),i.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-4",children:[i.jsxs(xn,{value:f.periodType,onChange:Z=>G("periodType",Z.target.value),"data-testid":"edit-period-type",children:[i.jsx("option",{value:"",children:"— No period —"}),i.jsx("option",{value:"weekly",children:"Weekly"}),i.jsx("option",{value:"biweekly",children:"Biweekly"}),i.jsx("option",{value:"monthly",children:"Monthly"}),i.jsx("option",{value:"quarterly",children:"Quarterly"}),i.jsx("option",{value:"custom",children:"Custom"})]}),i.jsx(ss,{type:"date","aria-label":"Period start",value:f.periodStart,onChange:Z=>G("periodStart",Z.target.value),fullWidth:!0,"data-testid":"edit-period-start"}),i.jsx(ss,{type:"date","aria-label":"Period end",value:f.periodEnd,onChange:Z=>G("periodEnd",Z.target.value),fullWidth:!0,"data-testid":"edit-period-end"}),i.jsx(ss,{"aria-label":"Period label",placeholder:"Label (optional)",value:f.periodLabel,onChange:Z=>G("periodLabel",Z.target.value),fullWidth:!0,"data-testid":"edit-period-label"})]})]})]}):i.jsxs("div",{className:"flex flex-col gap-8",children:[i.jsx(MBe,{missionId:n.id,onChanged:L}),i.jsx(IBe,{parentMissionId:n.id,onDecided:I}),i.jsxs("section",{"aria-labelledby":"goal-strategy-h",children:[i.jsx("h2",{id:"goal-strategy-h",className:$,children:"Current strategy"}),i.jsx("p",{className:"whitespace-pre-wrap text-[15px] leading-relaxed text-text",children:n.currentStrategy||"No strategy defined."})]}),i.jsx(ni,{title:"More",summary:"Success criteria, cascade, learnings, progress, settings, period, timestamps","data-testid":"goal-more",children:i.jsxs("div",{className:"grid grid-cols-1 gap-8 lg:grid-cols-3",children:[i.jsxs("div",{className:"flex flex-col gap-8 lg:col-span-2",children:[i.jsxs("section",{"aria-labelledby":"goal-criteria-h",children:[i.jsxs("h2",{id:"goal-criteria-h",className:$,children:["Success criteria (",n.successCriteria.length,")"]}),n.successCriteria.length===0?i.jsx("p",{className:"text-sm text-text-2",children:"No success criteria defined."}):i.jsx("ul",{className:"space-y-2",children:n.successCriteria.map((Z,oe)=>i.jsxs("li",{className:"flex items-start gap-2 text-sm text-text",children:[i.jsx(WH,{className:"mt-0.5 h-4 w-4 shrink-0 text-text-3","aria-hidden":"true"}),Z]},oe))})]}),i.jsx(RBe,{missionId:n.id,level:K,parentMissionId:n.parentMissionId,missionNames:y,refreshKey:A}),n.learnings&&n.learnings.length>0&&i.jsxs("section",{"aria-labelledby":"goal-learnings-h",children:[i.jsxs("h2",{id:"goal-learnings-h",className:$,children:["Learnings (",n.learnings.length,")"]}),i.jsx(fs,{as:"ul",limit:6,className:"space-y-2","data-testid":"goal-learnings",children:n.learnings.map((Z,oe)=>i.jsx("li",{className:"border-l-2 border-border-soft pl-4 text-sm text-text",children:Z},oe))})]})]}),i.jsxs("div",{className:"flex flex-col gap-8",children:[i.jsx(PBe,{missionId:n.id,refreshKey:A}),i.jsxs("section",{"aria-labelledby":"goal-settings-h",children:[i.jsx("h2",{id:"goal-settings-h",className:$,children:"Team & settings"}),i.jsxs("dl",{children:[q("Owner team",i.jsx("span",{title:n.ownerTeamId,children:R})),q("Status",hE(n.status)),q("Priority",QM[n.priority??"medium"]),q("Parent goal",n.parentMissionId?i.jsx(de,{type:"button",variant:"link",size:"xs",onClick:()=>e(qt.goal(n.parentMissionId)),className:"max-w-full truncate","data-testid":"mission-parent-link",children:y.get(n.parentMissionId)??n.parentMissionId}):"—"),q("Level",i.jsx("span",{"data-testid":"mission-level",children:K})),n.projectId&&q("Project",i.jsx(de,{type:"button",variant:"link",size:"xs",onClick:()=>e(qt.project(n.projectId)),"data-testid":"mission-project-link",children:"Open project"})),q("Active tasks",n.activeProjectTaskIds.length),q("Review cadence",i.jsx("span",{className:"font-mono text-xs",children:n.cadence||"N/A"})),q("Reference",i.jsx("span",{className:"font-mono text-xs",children:n.id.slice(0,12)}))]})]}),i.jsxs("section",{"aria-labelledby":"goal-period-h",children:[i.jsx("h2",{id:"goal-period-h",className:$,children:"OKR period"}),n.period?i.jsxs("dl",{children:[q("Type",n.period.type),q("Start",ep(n.period.startDate)),q("End",ep(n.period.endDate)),n.period.label&&q("Label",n.period.label)]}):i.jsx("p",{className:"text-sm text-text-2",children:"No period defined."})]}),i.jsxs("section",{"aria-labelledby":"goal-times-h",children:[i.jsx("h2",{id:"goal-times-h",className:$,children:"Timestamps"}),i.jsxs("dl",{children:[q("Created",ep(n.createdAt)),q("Updated",i.jsx("span",{title:ep(n.updatedAt),children:Ml(n.updatedAt)})),n.lastReviewAt&&q("Last review",ep(n.lastReviewAt)),n.nextReviewAt&&q("Next review",ep(n.nextReviewAt))]})]}),n.activeProjectTaskIds.length>0&&i.jsxs("section",{"aria-labelledby":"goal-task-ids-h",children:[i.jsx("h2",{id:"goal-task-ids-h",className:$,children:"Active task ids"}),i.jsx("p",{className:"flex flex-wrap gap-x-3 gap-y-1 font-mono text-xs text-text-2",children:n.activeProjectTaskIds.map(Z=>i.jsx("span",{title:Z,children:Z.slice(0,12)},Z))})]})]})]})})]})]})};EX.displayName="MissionDetail";function aP(t){return{queued:"Queued",scheduled:"Scheduled",running:"Running",blocked:"Blocked",done:"Completed",failed:"Failed",cancelled:"Cancelled"}[t]??t}function oP(t){return{delegate:"Delegate",project_task:"Project Task",check:"Check",notify:"Notify",cron_run:"Cron Run",review:"Review",confirm:"Confirm",reconcile:"Reconcile",ticket_triage:"Ticket triage",autopilot_retro:"Autopilot retro",goal_replan:"Goal replan",autopilot_self_review:"Autopilot self-review"}[t]??t}function Q2(t){return{orchestrator:"Orchestrator",team_lead:"Team Lead",agent:"Agent",system:"System"}[t]??t}function oC(t){const e=Date.now(),n=new Date(t).getTime(),s=e-n,r=Math.floor(s/6e4),a=Math.floor(r/60),o=Math.floor(a/24);return r<1?"just now":r<60?`${r}m ago`:a<24?`${a}h ago`:`${o}d ago`}function Ax(t){const e=new Date(t);return isNaN(e.getTime())?t:e.toLocaleString("en-US",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0})}function CX(t){return t===0?"—":t<.01?`$${t.toFixed(4)}`:`$${t.toFixed(2)}`}function Qx(t){return t===0?"—":t<1e3?t.toString():t<1e6?`${(t/1e3).toFixed(1)}K`:`${(t/1e6).toFixed(1)}M`}function kX(t){const e=[];if(e.push({id:`${t.id}-created`,kind:"status_change",label:"QUEUED",detail:"WorkItem created and added to pool.",timestamp:t.createdAt,status:"queued"}),t.startedAt&&e.push({id:`${t.id}-started`,kind:"status_change",label:"RUNNING",detail:t.target?`Claimed by agent: ${t.target}`:"Execution started.",timestamp:t.startedAt,status:"running"}),t.error){const n=t.completedAt||t.startedAt||t.createdAt;e.push({id:`${t.id}-error`,kind:"error",label:"ERROR",detail:t.error,timestamp:n,status:"failed"})}if(t.completedAt&&t.status==="done"&&e.push({id:`${t.id}-done`,kind:"status_change",label:"COMPLETED",detail:"Execution completed successfully.",timestamp:t.completedAt,status:"done"}),t.completedAt&&t.status==="failed"&&e.push({id:`${t.id}-failed`,kind:"status_change",label:"FAILED",detail:`Execution failed after ${t.retryCount}/${t.maxRetries} retries.`,timestamp:t.completedAt,status:"failed"}),t.status==="cancelled"){const n=t.completedAt||t.createdAt,s=t.cancelReason,r=typeof s=="string"&&s.length>0?`Cancelled: ${s}`:"Cancelled (no reason recorded).";e.push({id:`${t.id}-cancelled`,kind:"status_change",label:"CANCELLED",detail:r,timestamp:n,status:"cancelled"})}if(t.status==="blocked"){const n=t.blockedReason,s=typeof n=="string"&&n.length>0?`Blocked: ${n}`:"Blocked (no reason recorded).";e.push({id:`${t.id}-blocked`,kind:"status_change",label:"BLOCKED",detail:s,timestamp:t.startedAt||t.createdAt,status:"blocked"})}if(t.result&&Object.keys(t.result).length>0){const n=t.completedAt||t.startedAt||t.createdAt;e.push({id:`${t.id}-result`,kind:"progress_update",label:"RESULT DATA",detail:JSON.stringify(t.result,null,2),timestamp:n})}return e.sort((n,s)=>new Date(s.timestamp).getTime()-new Date(n.timestamp).getTime())}function BBe(t,e){if(t==="error")return Yd;if(t==="progress_update")return DH;if(t==="agent_reasoning"||t==="tool_action")return Ia;switch(e){case"queued":return jr;case"running":return Ia;case"done":return Ua;case"failed":return Yd;case"cancelled":return dee;case"blocked":return Kd;default:return jr}}function FBe(t,e){if(t==="error")return"text-red-400";if(t==="progress_update")return"text-blue-400";switch(e){case"queued":return"text-text-secondary-dark";case"running":return"text-green-400";case"done":return"text-blue-400";case"failed":return"text-red-400";case"cancelled":return"text-text-secondary-dark";case"blocked":return"text-yellow-400";default:return"text-text-secondary-dark"}}function UBe(t,e){return t==="error"?"border-red-500/30":e==="done"?"border-blue-500/30":e==="running"?"border-green-500/30":"border-border-dark"}const lP=({events:t})=>t.length===0?i.jsx("div",{className:"flex items-center justify-center py-8 text-text-secondary-dark text-sm","data-testid":"timeline-empty",children:"No activity recorded yet."}):i.jsx("div",{className:"relative","data-testid":"workitem-timeline",children:t.map((e,n)=>{const s=BBe(e.kind,e.status),r=FBe(e.kind,e.status),a=UBe(e.kind,e.status),o=n===t.length-1;return i.jsxs("div",{className:"relative flex gap-4 pb-6","data-testid":`timeline-event-${e.id}`,children:[!o&&i.jsx("div",{className:`absolute left-[15px] top-8 bottom-0 w-px border-l ${a}`}),i.jsx("div",{className:"relative z-10 flex-shrink-0 mt-0.5",children:i.jsx("div",{className:`p-1 rounded-full bg-surface-dark ${r}`,children:i.jsx(s,{className:"h-5 w-5"})})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx("span",{className:`text-sm font-semibold ${r}`,children:e.label}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:Ax(e.timestamp)})]}),e.detail&&i.jsx("div",{className:`mt-1 text-sm ${e.kind==="error"?"bg-red-500/10 border border-red-500/20 rounded-md p-2 text-red-300":e.kind==="progress_update"?"bg-surface-dark border border-border-dark rounded-md p-2 text-text-secondary-dark font-mono text-xs whitespace-pre-wrap overflow-x-auto max-h-40 overflow-y-auto":"text-text-secondary-dark"}`,children:e.detail})]})]},e.id)})});lP.displayName="WorkItemTimeline";const io=({icon:t,label:e,value:n,valueClass:s="text-text-primary-dark"})=>i.jsxs("div",{className:"flex items-center justify-between py-2",children:[i.jsxs("div",{className:"flex items-center gap-2 text-text-secondary-dark",children:[i.jsx(t,{className:"h-4 w-4"}),i.jsx("span",{className:"text-sm",children:e})]}),i.jsx("span",{className:`text-sm font-medium ${s}`,children:n})]}),AX=({item:t})=>{const e=zBe(t);return i.jsxs("div",{className:"space-y-4","data-testid":"workitem-metrics",children:[i.jsxs(tn,{variant:"default",padding:"md",children:[i.jsx("h3",{className:"text-xs font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:"Token Usage"}),i.jsxs("div",{className:"divide-y divide-border-dark",children:[i.jsx(io,{icon:_0,label:"Input Tokens",value:Qx(t.inputTokens)}),i.jsx(io,{icon:_0,label:"Output Tokens",value:Qx(t.outputTokens)}),i.jsx(io,{icon:rR,label:"Cost",value:CX(t.cost),valueClass:t.cost>0?"text-yellow-400":"text-text-primary-dark"})]})]}),i.jsxs(tn,{variant:"default",padding:"md",children:[i.jsx("h3",{className:"text-xs font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:"Execution"}),i.jsxs("div",{className:"divide-y divide-border-dark",children:[i.jsx(io,{icon:$t,label:"Retries",value:`${t.retryCount} / ${t.maxRetries}`}),i.jsx(io,{icon:jr,label:"Duration",value:e}),i.jsx(io,{icon:oy,label:"Owner",value:Q2(t.owner)}),t.target&&i.jsx(io,{icon:ay,label:"Agent",value:t.target})]})]}),(t.requestId||t.missionId||t.projectTaskId||t.triggerId)&&i.jsxs(tn,{variant:"default",padding:"md",children:[i.jsx("h3",{className:"text-xs font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:"Linked References"}),i.jsxs("div",{className:"divide-y divide-border-dark",children:[t.requestId&&i.jsx(io,{icon:tp,label:"Request",value:dx(t.requestId)}),t.missionId&&i.jsx(io,{icon:tp,label:"Mission",value:dx(t.missionId)}),t.projectTaskId&&i.jsx(io,{icon:tp,label:"Project Task",value:dx(t.projectTaskId)}),t.triggerId&&i.jsx(io,{icon:tp,label:"Trigger",value:dx(t.triggerId)}),t.parentWorkItemId&&i.jsx(io,{icon:tp,label:"Parent Item",value:dx(t.parentWorkItemId)})]})]}),i.jsxs(tn,{variant:"default",padding:"md",children:[i.jsx("h3",{className:"text-xs font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:"Timestamps"}),i.jsxs("div",{className:"space-y-2 text-sm",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Created"}),i.jsx("span",{className:"text-text-primary-dark",children:Ax(t.createdAt)})]}),t.startedAt&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Started"}),i.jsx("span",{className:"text-text-primary-dark",children:Ax(t.startedAt)})]}),t.completedAt&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Completed"}),i.jsx("span",{className:"text-text-primary-dark",children:Ax(t.completedAt)})]}),t.scheduledAt&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Scheduled"}),i.jsx("span",{className:"text-text-primary-dark",children:Ax(t.scheduledAt)})]})]})]})]})};AX.displayName="WorkItemMetrics";function zBe(t){const e=t.startedAt?new Date(t.startedAt).getTime():null,n=t.completedAt?new Date(t.completedAt).getTime():t.startedAt?Date.now():null;if(!e||!n)return"--";const s=n-e,r=Math.floor(s/1e3)%60,a=Math.floor(s/6e4)%60,o=Math.floor(s/36e5);return o>0?`${o}h ${a}m`:a>0?`${a}m ${r}s`:`${r}s`}function dx(t){return t.length<=12?t:`${t.slice(0,8)}...`}let M_=null;function HBe(){return M_||(M_=Promise.resolve().then(()=>x$()).then(t=>Wce(t.flatMap(e=>e.tickets.map(n=>n.id)))).catch(t=>{throw M_=null,t})),M_}function TX(){const[t,e]=_.useState(()=>new Set);return _.useEffect(()=>{let n=!0;return HBe().then(s=>{n&&e(s)}).catch(()=>{}),()=>{n=!1}},[]),t}const NX=()=>{const{id:t}=Lc(),e=cs(),{names:n}=Bm(),s=TX(),[r,a]=_.useState(null),[o,l]=_.useState(!0),[c,d]=_.useState(null),[u,h]=_.useState(!1),f=_.useCallback(async(y=!0)=>{if(t){y?l(!0):h(!0),d(null);try{const b=await lt.getWorkItem(t);a(b)}catch(b){const S=b instanceof Error?b.message:"Failed to load run";d(S)}finally{l(!1),h(!1)}}},[t]);_.useEffect(()=>{f(!0)},[f]),_.useEffect(()=>{if(!r||r.status!=="running")return;const y=setInterval(()=>{f(!1)},1e4);return()=>clearInterval(y)},[r==null?void 0:r.status,f]);const p=()=>{e(qt.runs())},x=()=>{f(!1)};if(o)return i.jsx("div",{className:"flex items-center justify-center h-64","data-testid":"workitem-detail-loading",children:i.jsx(zt,{})});if(c)return i.jsxs("div",{className:"p-6","data-testid":"workitem-detail-error",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:Fa,onClick:p,className:"mb-6",children:"Back to Runs"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsxs("div",{className:"flex flex-col items-center text-center py-8",children:[i.jsx("p",{className:"text-danger text-lg font-medium mb-2",children:"Failed to load run"}),i.jsx("p",{className:"text-text-2 text-sm mb-4",children:c}),i.jsx(de,{variant:"secondary",size:"sm",icon:$t,onClick:()=>f(!0),children:"Retry"})]})})]});if(!r)return i.jsxs("div",{className:"p-6","data-testid":"workitem-detail-not-found",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:Fa,onClick:p,className:"mb-6",children:"Back to Runs"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsx(is,{icon:bee,title:"Run not found.",compact:!0})})]});const v=kX(r),m=Jd(r.target,n,!0),g=k$(r.title,s);return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-6","data-testid":"workitem-detail",children:[i.jsx(_r,{className:"mb-0",eyebrow:i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:qt.ticketsBoard(),className:"text-text-2 hover:text-text",children:"Tickets"}),i.jsx("span",{className:"text-text-3",children:"/"}),i.jsx(hs,{to:qt.runs(),className:"text-text-2 hover:text-text","data-testid":"workitem-detail-back",children:"Runs"})]}),title:r.title,subtitle:i.jsxs(i.Fragment,{children:[m?`${Q2(r.owner)} · ${m}`:Q2(r.owner),` · created ${oC(r.createdAt)} · `,i.jsxs("span",{className:"font-mono text-text-3",title:r.id,children:["run ",dN(r.id)]})]}),actions:i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:x,loading:u,"data-testid":"workitem-detail-refresh"}),"data-testid":"workitem-detail-header"}),i.jsxs("div",{className:"-mt-2 flex flex-wrap items-center gap-x-4 gap-y-2 text-[13px] text-text-2",children:[i.jsx(sn,{tone:GBe(r.status),children:aP(r.status)}),i.jsx("span",{children:oP(r.type)}),i.jsxs("span",{children:["Retry ",r.retryCount,"/",r.maxRetries]}),g&&i.jsx("span",{children:g}),r.requestId&&i.jsxs(hs,{to:qt.request(r.requestId),className:"font-semibold text-primary-text hover:underline",children:["Request ",dN(r.requestId)]}),r.missionId&&i.jsxs(hs,{to:qt.goal(r.missionId),className:"font-semibold text-primary-text hover:underline",children:["Goal ",dN(r.missionId)]})]}),r.description&&i.jsx("p",{className:"whitespace-pre-wrap text-sm leading-relaxed text-text-2",children:r.description}),i.jsxs("section",{"aria-labelledby":"workitem-timeline-heading",className:"rounded-2xl bg-surface p-4",children:[i.jsx("h2",{id:"workitem-timeline-heading",className:"mb-4 text-[15px] font-bold text-text",children:"Activity timeline"}),i.jsx(lP,{events:v})]}),i.jsx(ni,{title:"Details",summary:"Tokens, cost, retries, duration, links and timestamps",children:i.jsx(AX,{item:r})})]})};function GBe(t){return t==="cancelled"||t==="queued"||t==="scheduled"?"neutral":rE(t)}NX.displayName="WorkItemDetail";function dN(t){return t.length<=12?t:t.slice(0,8)}const ux=new Set(["open","waiting_owner","ready","overdue"]),$Be={open:{label:"Open",variant:"info"},waiting_owner:{label:"Waiting on you",variant:"warning"},ready:{label:"Ready to deliver",variant:"warning"},overdue:{label:"Overdue",variant:"error"},delivered:{label:"Delivered",variant:"success"},resolved:{label:"Answered",variant:"success"},superseded:{label:"Superseded",variant:"default"},expired:{label:"Expired",variant:"default"},cancelled:{label:"Cancelled",variant:"default"},skipped:{label:"Skipped",variant:"default"}};function Xz(t){if(!t)return"";const e=new Date(t);return Number.isNaN(e.getTime())?"":e.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}const WBe=({items:t,onSkip:e})=>{const[n,s]=an.useState(null),[r,a]=an.useState(null),o=async d=>{if(e){s(d),a(null);try{await e(d)}catch(u){a(u instanceof Error?u.message:String(u))}finally{s(null)}}},l=[...t].sort((d,u)=>Number(ux.has(u.status))-Number(ux.has(d.status))||Date.parse(u.createdAt)-Date.parse(d.createdAt)),c=l.filter(d=>ux.has(d.status)).length;return i.jsxs(tn,{variant:"default",padding:"md","data-testid":"request-open-items",children:[i.jsxs("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:["Open items ",c>0?`(${c} open)`:""]}),r&&i.jsx("p",{className:"text-xs text-red-400 mb-2",role:"alert",children:r}),i.jsx("ul",{className:"flex flex-col gap-3",children:l.map(d=>{const u=$Be[d.status]??{label:d.status,variant:"default"};return i.jsxs("li",{className:"flex flex-col gap-1","data-testid":"request-open-item",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx(mn,{variant:d.type==="commitment"?"info":"warning",size:"sm",children:d.type==="commitment"?"Promise":"Question"}),i.jsx(mn,{variant:u.variant,size:"sm",children:u.label}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:d.agent}),d.type==="commitment"&&d.due&&ux.has(d.status)&&i.jsxs("span",{className:"text-xs text-text-secondary-dark",children:["due ",Xz(d.due)]}),d.decisionId&&i.jsx("span",{className:"text-xs text-text-secondary-dark font-mono",children:d.decisionId}),e&&ux.has(d.status)&&i.jsx(de,{size:"sm",variant:"ghost",className:"ml-auto min-h-8",disabled:n===d.id,onClick:()=>void o(d.id),title:d.type==="commitment"?"Drop this promise and cancel its follow-up":"Skip this question — the agent won't ask again",children:"Skip"})]}),i.jsx("p",{className:"text-sm text-text-primary-dark break-words",children:d.text}),d.answer&&i.jsxs("p",{className:"text-xs text-text-secondary-dark",children:["Answer: ",d.answer]}),d.status==="ready"&&d.readyAt&&i.jsxs("p",{className:"text-xs text-amber-400",children:["The work was ready at ",Xz(d.readyAt),"; the agent was asked to deliver it."]})]},d.id)})})]})},VBe="/api/traces";class MX extends Error{constructor(e,n){super(e),this.status=n,this.name="TraceApiError"}}async function jX(t){const e=await fetch(`${VBe}${t}`);let n={};try{n=await e.json()}catch{n={}}if(!e.ok||n.success===!1)throw new MX(n.error||`HTTP ${e.status}`,e.status);return n.data}function KBe(t){return t?`?stallMinutes=${encodeURIComponent(String(t))}`:""}async function qBe(t,e){try{return await jX(`/by-ref?${t}=${encodeURIComponent(e)}`)}catch(n){if(n instanceof MX&&n.status===404)return null;throw n}}function XBe(t,e){return jX(`/${encodeURIComponent(t)}/timeline${KBe(e)}`)}function YBe(t){return t==="done"?"success":t==="failed"?"danger":t==="waiting_on_owner"?"attention":t==="in_progress"?"primary":"neutral"}function Yz(t,e){return e>0?`${Math.round(t/e*100)}% of the time`:void 0}function JBe(t){const e=t.time,n=t.stalls.items.some(a=>a.ongoing),s=t.ownerTouches,r=t.rework;return[{id:"wall",label:"Wall time",value:zi(e.wallMs)},{id:"active",label:"Agents working",value:zi(e.activeMs),hint:Yz(e.activeMs,e.wallMs),title:e.activeSource==="inferred"?"Estimated from agent activity":void 0},{id:"owner-wait",label:"Waiting on you",value:zi(e.waitingOwnerMs),hint:Yz(e.waitingOwnerMs,e.wallMs),attention:e.waitingOwnerMs>0},{id:"touches",label:"Your touches",value:String(s.total),title:`Answered ${s.answered}, approved ${s.approved}, sent back ${s.sentBack}, corrected ${s.corrected}`},{id:"rework",label:"Rework",value:String(r.total),title:`Send-backs ${r.sendBacks}, retries ${r.retries}, failed verifications ${r.failedVerifications}, subagent send-backs ${r.subagentSendBacks}`,attention:r.total>0},{id:"stalls",label:"Stalls",value:String(t.stalls.count),hint:t.stalls.count>0?n?"one still going":zi(t.stalls.totalMs):void 0,attention:t.stalls.count>0},{id:"cost",label:"Cost",value:Nc(t.usage.costUsd),hint:`${A0(t.usage.totalTokens)} tokens`}]}function Jz(t,e){return t.length===0?"none":t.map(n=>`${e(n.key)} ${A0(n.totalTokens)} ${Nc(n.costUsd)}`).join(" · ")}const RX=({metrics:t,nameOf:e=n=>n})=>{var o;const n=JBe(t),s=t,r=Object.entries(s.stalls.byCause).filter(([,l])=>l>0).map(([l,c])=>`${rI[l]} ${c}`).join(" · "),a=s.interventions;return i.jsxs("section",{"aria-label":"Run metrics","data-testid":"trace-metrics-strip",children:[i.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] text-text-2",children:[i.jsx(sn,{tone:YBe(s.outcome.state),"data-testid":"trace-outcome",children:yde[s.outcome.state]}),((o=s.outcome.experiment)==null?void 0:o.verdict)&&i.jsxs("span",{children:["Experiment: ",s.outcome.experiment.verdict==="didnt"?"didn't work":s.outcome.experiment.verdict]}),s.outcome.workItems.total>0&&i.jsxs("span",{children:[s.outcome.workItems.done," of ",s.outcome.workItems.total," runs done",s.outcome.workItems.failed>0?` · ${s.outcome.workItems.failed} failed`:""]})]}),i.jsx("dl",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap sm:gap-3",children:n.map(l=>i.jsxs("div",{title:l.title,className:`min-w-0 rounded-2xl px-3 py-2 sm:min-w-[7.5rem] ${l.attention?"bg-attention-soft":"bg-surface"}`,"data-testid":`trace-metric-${l.id}`,children:[i.jsx("dt",{className:"truncate text-[12px] text-text-2",children:l.label}),i.jsx("dd",{className:`text-[15px] font-bold leading-snug ${l.attention?"text-attention":"text-text"}`,children:l.value}),l.hint&&i.jsx("dd",{className:"truncate text-[12px] text-text-3",children:l.hint})]},l.id))}),i.jsx(ni,{className:"mt-2",unmountWhenClosed:!0,title:"Details",summary:"Touches, rework, interventions, cost by agent and model","data-testid":"trace-metrics-details",children:i.jsxs("dl",{className:"grid grid-cols-1 gap-x-6 gap-y-1.5 text-[13px] sm:grid-cols-[auto_1fr]",children:[i.jsx("dt",{className:"text-text-2",children:"Your touches"}),i.jsxs("dd",{className:"text-text",children:["answered ",s.ownerTouches.answered," · approved ",s.ownerTouches.approved," · sent back ",s.ownerTouches.sentBack," · corrected ",s.ownerTouches.corrected]}),i.jsx("dt",{className:"text-text-2",children:"Rework"}),i.jsxs("dd",{className:"text-text",children:["send-backs ",s.rework.sendBacks," · retries ",s.rework.retries," · failed verifications ",s.rework.failedVerifications," · subagent send-backs ",s.rework.subagentSendBacks]}),i.jsx("dt",{className:"text-text-2",children:"Crewly stepped in"}),i.jsxs("dd",{className:"text-text",children:["nudges ",a.nudges," · redeliveries ",a.redeliveries," · wakes ",a.wakes," · corrections ",a.corrections," · guard blocks ",a.guardBlocks," · misroutes ",a.misroutes]}),i.jsx("dt",{className:"text-text-2",children:"Time"}),i.jsxs("dd",{className:"text-text",children:["working ",zi(s.time.activeMs)," · waiting on you ",zi(s.time.waitingOwnerMs)," · waiting on agents ",zi(s.time.waitingAgentMs)," · idle ",zi(s.time.idleMs)]}),i.jsx("dt",{className:"text-text-2",children:"Stalls"}),i.jsx("dd",{className:"text-text",children:s.stalls.count===0?`none longer than ${s.stalls.thresholdMinutes}m`:`${r} (longer than ${s.stalls.thresholdMinutes}m)`}),i.jsx("dt",{className:"text-text-2",children:"By agent"}),i.jsx("dd",{className:"text-text",children:Jz(s.usage.byAgent,e)}),i.jsx("dt",{className:"text-text-2",children:"By model"}),i.jsx("dd",{className:"break-words text-text",children:Jz(s.usage.byModel,l=>l)})]})})]})};RX.displayName="MetricsStrip";function ZBe(t,e){if(t.kind==="stall"&&t.stall)return`Stalled ${zi(t.stall.ms)}${t.stall.ongoing?" and counting":""} — ${rI[t.stall.cause]}`;if(t.kind==="owner")return"You";if(t.kind==="system")return"Crewly";const n=t.session;if(!n)return t.title;const s=e(n);if(t.title===`${n} working`)return`${s} working`;if(t.title===`Harness → ${n}`)return`Crewly → ${s}`;const r=t.title.lastIndexOf(" → "),a=r>=0?t.title.slice(0,r):t.title;return`${a==="Owner"?"You":a} → ${s}`}function Zz(t,e){var o;const n=T0(t.start,e),s=T0(t.end,e),r=n===s?n:`${n}–${s}`;if(t.kind==="stall")return(o=t.stall)!=null&&o.ongoing?`since ${n}`:r;const a=[r,`${t.counts.events} ${t.counts.events===1?"event":"events"}`];return t.counts.skillCalls>0&&a.push(`${t.counts.skillCalls} skill ${t.counts.skillCalls===1?"call":"calls"}`),t.tokens>0&&a.push(`${A0(t.tokens)} tokens ${Nc(t.costUsd)}`),a.join(" · ")}const QBe=({event:t,nameOf:e,now:n})=>{const s=t.actor.kind==="agent"&&t.actor.session?e(t.actor.session):_de(t);return i.jsxs("li",{className:"flex min-w-0 gap-3 py-1.5 text-[13px]","data-testid":"trace-event",children:[i.jsx("span",{className:"w-12 shrink-0 font-mono text-[12px] text-text-3",children:T0(t.ts,n)}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"font-semibold text-text",children:bde(t.type)}),i.jsxs("span",{className:"text-text-3",children:[" · ",s]}),(t.outcome==="failed"||t.outcome==="blocked")&&i.jsx(sn,{className:"ml-2",size:"sm",tone:t.outcome==="failed"?"danger":"attention",children:t.outcome==="failed"?"Failed":"Blocked"}),i.jsx("span",{className:"block break-words text-text-2",children:t.summary})]})]})},IX=({group:t,nameOf:e=s=>s,now:n})=>{var h,f;const[s,r]=_.useState(!1),[a,o]=_.useState(!1),l=t.kind==="stall",c=t.events.filter(p=>MB.has(p.type)),d=a?t.events:t.events.filter(p=>!MB.has(p.type)),u=l||t.outcome==="blocked"?"bg-attention":t.outcome==="failed"?"bg-danger":t.kind==="owner"?"bg-primary":"bg-muted-dot";return i.jsxs("li",{className:`list-none border-b border-border-soft last:border-b-0 ${l?"bg-attention-soft":""}`,"data-testid":`trace-group-${t.id}`,"data-kind":t.kind,children:[i.jsx(Ts,{className:"border-b-0",primary:i.jsx("span",{className:l?"text-attention":void 0,children:ZBe(t,e)}),meta:l?`${Zz(t,n)} · ${((h=t.stall)==null?void 0:h.detail)??""}`:Zz(t,n),leading:i.jsx("span",{"aria-hidden":"true",className:`h-2.5 w-2.5 rounded-full ${u}${(f=t.stall)!=null&&f.ongoing?" animate-pulse":""}`}),trailing:t.kind!=="stall"&&(t.counts.errors>0||t.counts.blocks>0)?i.jsxs("span",{className:"text-[12px]",children:[t.counts.errors>0&&i.jsxs("span",{className:"text-danger",children:[t.counts.errors," failed"]}),t.counts.errors>0&&t.counts.blocks>0&&" · ",t.counts.blocks>0&&i.jsxs("span",{className:"text-attention",children:[t.counts.blocks," blocked"]})]}):void 0,onClick:l?void 0:()=>r(p=>!p),"data-testid":`trace-group-row-${t.id}`}),s&&!l&&i.jsxs("div",{className:"px-4 pb-3 sm:pl-12","data-testid":`trace-group-events-${t.id}`,children:[i.jsx("ul",{className:"divide-y divide-border-soft",children:d.map((p,x)=>i.jsx(QBe,{event:p,nameOf:e,now:n},`${p.ts}-${x}`))}),c.length>0&&i.jsx(de,{variant:"link",size:"xs",onClick:()=>o(p=>!p),"data-testid":`trace-group-show-all-${t.id}`,children:a?"Hide routine events":`Show all ${t.events.length} events (${c.length} routine)`})]})]})};IX.displayName="TimelineGroupRow";const eFe=3e4,tFe=5*6e4,nFe=new Set(["done","cancelled","failed"]),lC=({traceId:t,refParam:e,refId:n,nameOf:s,pollMs:r=eFe,now:a,onLoaded:o})=>{const[l,c]=_.useState({kind:"loading"}),[d,u]=_.useState(!1),h=_.useRef(t??null),f=_.useRef(null),p=_.useRef(0),x=_.useRef(o);x.current=o;const v=_.useCallback(async y=>{var b;y&&u(!0);try{let S=t??h.current;if(!S&&e&&n){const T=await qBe(e,n);S=(T==null?void 0:T.traceId)??null}if(!S){c({kind:"none"});return}h.current=S;const E=await XBe(S),k=`${E.metrics.eventCount}|${E.metrics.window.end}`;k===f.current?p.current+=1:(f.current=k,p.current=0),c({kind:"ready",data:E}),(b=x.current)==null||b.call(x,E)}catch(S){y||c({kind:"error",message:S instanceof Error?S.message:"Failed to load the timeline"})}finally{u(!1)}},[t,e,n]);_.useEffect(()=>{h.current=t??null,f.current=null,p.current=0,c({kind:"loading"}),v(!1)},[v,t]);const m=l.kind==="ready"&&nFe.has(l.data.metrics.outcome.state);if(_.useEffect(()=>{if(!r||l.kind!=="ready"||m)return;let y,b=!1;const S=()=>{if(b||document.hidden)return;const k=Math.max(r,Math.min(r*2**p.current,tFe));y=setTimeout(()=>{v(!0).then(S)},k)},E=()=>{clearTimeout(y),!document.hidden&&!b&&v(!0).then(S)};return S(),document.addEventListener("visibilitychange",E),()=>{b=!0,clearTimeout(y),document.removeEventListener("visibilitychange",E)}},[r,l.kind,m,v]),l.kind==="loading")return i.jsx("div",{className:"flex justify-center py-10","data-testid":"trace-timeline-loading",children:i.jsx(zt,{})});if(l.kind==="none")return i.jsx(is,{icon:du,title:"No timeline for this yet",description:"A timeline is recorded for work started after run traces were turned on.",compact:!0,"data-testid":"trace-timeline-none"});if(l.kind==="error")return i.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center","data-testid":"trace-timeline-error",children:[i.jsx("p",{className:"text-sm text-danger",children:l.message}),i.jsx(de,{variant:"secondary",size:"sm",icon:$t,onClick:()=>void v(!1),children:"Retry"})]});const{data:g}=l;return i.jsxs("div",{className:"flex flex-col gap-4","data-testid":"trace-timeline",children:[i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx(RX,{metrics:g.metrics,nameOf:s})}),i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh timeline",onClick:()=>void v(!0),loading:d,"data-testid":"trace-timeline-refresh"})]}),g.groups.length===0?i.jsx("p",{className:"py-6 text-[13px] text-text-3","data-testid":"trace-timeline-empty",children:"Nothing has happened in this run yet."}):i.jsx("ol",{className:"overflow-hidden rounded-2xl bg-surface","aria-label":"Run timeline","data-testid":"trace-timeline-groups",children:g.groups.map(y=>i.jsx(IX,{group:y,nameOf:s,now:a},y.id))}),g.truncated&&i.jsx("p",{className:"text-[12px] text-text-3",children:"This run hit the trace size limit; later events were not recorded."})]})};lC.displayName="TraceTimeline";const sFe={overview:"Overview",timeline:"Timeline"},Qz={open:"text-primary-text",in_progress:"text-primary-text",blocked:"text-danger",waiting_confirmation:"text-attention",awaiting_followup:"text-attention",done:"text-success",cancelled:"text-text-2"};function ej(t){return{open:"Open",in_progress:"In Progress",blocked:"Blocked",waiting_confirmation:"Waiting Confirmation",awaiting_followup:"Awaiting Follow-up",done:"Completed",cancelled:"Cancelled"}[t]??t}const e6=["open","in_progress","done"],rFe=({currentStatus:t})=>{const e=e6.indexOf(t),n=t==="cancelled"||t==="blocked";return i.jsxs("ol",{className:"flex flex-wrap items-center gap-1.5 text-[13px]","aria-label":"Progress","data-testid":"request-progress-rail",children:[e6.map((s,r)=>{const a=s===t,o=e>=0&&r<=e;return i.jsxs(an.Fragment,{children:[r>0&&i.jsx("li",{"aria-hidden":"true",className:`h-px w-6 ${o?"bg-success":"bg-border"}`}),i.jsxs("li",{"aria-current":a?"step":void 0,className:`inline-flex items-center gap-1 ${a?`font-semibold ${Qz[s]??"text-text"}`:o?"text-success":"text-text-3"}`,children:[o&&!a&&i.jsx(Ua,{className:"h-3 w-3","aria-hidden":"true"}),ej(s)]})]},s)}),n&&i.jsxs(i.Fragment,{children:[i.jsx("li",{"aria-hidden":"true",className:"h-px w-6 bg-border"}),i.jsx("li",{"aria-current":"step",className:`font-semibold ${Qz[t]??"text-text-2"}`,children:ej(t)})]})]})},iFe=({workItems:t,onItemClick:e,names:n})=>{const[s,r]=_.useState(null);return t.length===0?i.jsx("p",{className:"py-6 text-[13px] text-text-3","data-testid":"request-workitems-empty",children:"No runs for this request yet."}):i.jsx("ul",{className:"overflow-hidden rounded-2xl bg-surface","data-testid":"request-workitems-list",children:t.map(a=>{const o=s===a.id,l=Jd(a.target,n,!0);return i.jsxs("li",{className:"list-none border-b border-border-soft last:border-b-0","data-testid":`request-workitem-${a.id}`,children:[i.jsx(Ts,{className:"border-b-0",primary:a.title,meta:[oP(a.type),l,oC(a.createdAt)].filter(Boolean).join(" · "),trailing:i.jsx(sn,{tone:a.status==="cancelled"||a.status==="queued"||a.status==="scheduled"?"neutral":rE(a.status),children:aP(a.status)}),onClick:()=>r(o?null:a.id),actions:[i.jsx(de,{variant:"link",size:"xs",onClick:()=>e(a.id),"data-testid":`request-workitem-detail-link-${a.id}`,children:"Details"},"details")],"data-testid":`request-workitem-row-${a.id}`}),o&&i.jsx("div",{className:"border-t border-border-soft px-4 py-3","data-testid":`request-workitem-timeline-${a.id}`,children:i.jsx(lP,{events:kX(a)})})]},a.id)})})},LX=()=>{const{id:t}=Lc(),e=cs(),{names:n}=Bm(),[s,r]=uu(_h),a=_.useCallback(N=>Jd(N,n)??N,[n]),[o,l]=_.useState(null),[c,d]=_.useState([]),[u,h]=_.useState(!0),[f,p]=_.useState(null),[x,v]=_.useState(!1),[m,g]=_.useState(null),y=_.useCallback(async(N=!0)=>{if(t){N?h(!0):v(!0),p(null);try{const[L,I,D]=await Promise.all([lt.getRequest(t),lt.getWorkItemsByRequest(t),Promise.resolve().then(()=>lt.getRequestWhereabouts(t)).catch(()=>null)]);g(D&&!D.finished?D.summary:null),l(L),d(I.sort((z,U)=>new Date(U.createdAt).getTime()-new Date(z.createdAt).getTime()))}catch(L){const I=L instanceof Error?L.message:"Failed to load request";p(I)}finally{h(!1),v(!1)}}},[t]);_.useEffect(()=>{y(!0)},[y]),_.useEffect(()=>{if(!o||o.status==="done"||o.status==="cancelled")return;const N=setInterval(()=>{y(!1)},15e3);return()=>clearInterval(N)},[o==null?void 0:o.status,y]);const b=_.useCallback(()=>{e(qt.requests())},[e]),S=_.useCallback(N=>{e(qt.run(N))},[e]),E=_.useCallback(()=>{y(!1)},[y]),k=_.useCallback(async N=>{if(t)try{const L=N==="confirmed"?"done":"cancelled";await lt.updateRequest(t,{status:L}),y(!1)}catch(L){const I=L instanceof Error?L.message:"Failed to update request";p(I)}},[t,y]),T=_.useMemo(()=>o?o.totalInputTokens+o.totalOutputTokens:0,[o]),A=_.useMemo(()=>{if(!o)return"";const N=new Date(o.createdAt).getTime(),I=(o.completedAt?new Date(o.completedAt).getTime():Date.now())-N,D=Math.floor(I/6e4),z=Math.floor(D/60);return D<1?"< 1m":z<1?`${D}m`:`${z}h ${D%60}m`},[o]);if(u)return i.jsx("div",{className:"flex items-center justify-center h-64","data-testid":"request-detail-loading",children:i.jsx(zt,{})});if(f)return i.jsxs("div",{className:"p-6","data-testid":"request-detail-error",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:Fa,onClick:b,className:"mb-6",children:"Back to Requests"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsxs("div",{className:"flex flex-col items-center text-center py-8",children:[i.jsx("p",{className:"text-danger text-lg font-medium mb-2",children:"Failed to load Request"}),i.jsx("p",{className:"text-text-2 text-sm mb-4",children:f}),i.jsx(de,{variant:"secondary",size:"sm",icon:$t,onClick:()=>y(!0),children:"Retry"})]})})]});if(!o)return i.jsxs("div",{className:"p-6","data-testid":"request-detail-not-found",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:Fa,onClick:b,className:"mb-6",children:"Back to Requests"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsx(is,{icon:Cl,title:"Request not found.",compact:!0})})]});const M=[`Created ${oC(o.createdAt)}`,o.intentCategory?o.intentCategory.replace(/_/g," "):null,o.intentLevel?`Intent level ${o.intentLevel}`:null,o.priority&&o.priority!=="normal"?`${o.priority.charAt(0).toUpperCase()}${o.priority.slice(1)} priority`:null].filter(Boolean);return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-6","data-testid":"request-detail",children:[i.jsx(_r,{className:"mb-0",eyebrow:i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:qt.ticketsBoard(),className:"text-text-2 hover:text-text",children:"Tickets"}),i.jsx("span",{className:"text-text-3",children:"/"}),i.jsx(hs,{to:qt.requests(),className:"text-text-2 hover:text-text","data-testid":"request-detail-back",children:"Requests"})]}),title:o.title,subtitle:i.jsx(i.Fragment,{children:M.map((N,L)=>i.jsxs(an.Fragment,{children:[L>0&&" · ",N]},L))}),actions:i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:E,loading:x,"data-testid":"request-detail-refresh"}),tabs:i.jsx(Oc,{"aria-label":"Request views",idPrefix:"request",value:s,onChange:N=>r(N),tabs:_h.map(N=>({value:N,label:sFe[N]}))}),"data-testid":"request-detail-header"}),s==="timeline"?i.jsx("div",{role:"tabpanel",id:"request-panel-timeline","aria-labelledby":"request-tab-timeline","data-testid":"request-panel-timeline",children:i.jsx(lC,{traceId:o.traceId,refParam:"requestId",refId:o.id,nameOf:a})}):i.jsxs("div",{role:"tabpanel",id:"request-panel-overview","aria-labelledby":"request-tab-overview",className:"flex flex-col gap-6","data-testid":"request-panel-overview",children:[i.jsxs("div",{className:"-mt-2 flex flex-wrap items-center gap-x-4 gap-y-2 text-[13px] text-text-2",children:[i.jsx(sn,{tone:aFe(o.status),children:ej(o.status)}),o.requiresConfirmation&&i.jsx("span",{className:"font-semibold text-attention",children:"Requires confirmation"}),typeof o.ticketNumber=="number"&&i.jsxs("span",{children:["TKT-",String(o.ticketNumber).padStart(3,"0")]}),i.jsx(rFe,{currentStatus:o.status})]}),m&&i.jsxs("p",{className:"-mt-3 text-[13px] text-text-2","data-testid":"request-now-with",children:[i.jsx("span",{className:"font-semibold text-text",children:"Now: "}),m]}),o.requiresConfirmation&&o.status==="waiting_confirmation"&&i.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-2xl bg-attention-soft px-4 py-3","data-testid":"request-action-area",children:[i.jsx("span",{className:"mr-auto text-sm text-text",children:"This request needs your confirmation before it completes"}),i.jsx(de,{variant:"secondary",size:"sm",onClick:()=>k("rejected"),children:"Reject"}),i.jsx(de,{variant:"primary",size:"sm",onClick:()=>k("confirmed"),children:"Approve"})]}),o.openItems&&o.openItems.length>0&&i.jsx(WBe,{items:o.openItems,onSkip:async N=>{await _re(o.id,N),await y(!1)}}),i.jsxs("section",{"aria-labelledby":"request-message-heading",children:[i.jsx("h2",{id:"request-message-heading",className:"mb-2 text-[15px] font-bold text-text",children:"Original message"}),o.description?i.jsx("p",{className:"whitespace-pre-wrap text-sm leading-relaxed text-text",children:o.description}):i.jsx("p",{className:"text-sm italic text-text-3",children:"No description provided."}),(o.sourceConversationItemId||o.tags.length>0)&&i.jsxs("p",{className:"mt-3 flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] text-text-3",children:[o.sourceConversationItemId&&i.jsxs("span",{children:["Source: ",i.jsx("span",{className:"font-mono",children:o.sourceConversationItemId})]}),o.tags.map(N=>i.jsx("span",{className:"rounded-full bg-surface-2 px-2 py-0.5 text-text-2",children:N},N))]})]}),i.jsxs("section",{"data-testid":"request-detail-workitems","aria-labelledby":"request-runs-heading",children:[i.jsxs("h2",{id:"request-runs-heading",className:"mb-2 text-[15px] font-bold text-text",children:["Runs ",i.jsx("span",{className:"text-[13px] font-normal text-text-2",children:c.length})]}),i.jsx(iFe,{workItems:c,onItemClick:S,names:n})]}),i.jsx(ni,{title:"Statistics",summary:"Tokens, cost, elapsed time, runs",children:i.jsxs("dl",{className:"grid max-w-md grid-cols-[1fr_auto] gap-x-6 gap-y-2 text-sm","data-testid":"request-detail-stats",children:[i.jsxs("dt",{className:"flex items-center gap-1.5 text-text-2",children:[i.jsx(_0,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Total tokens"]}),i.jsx("dd",{className:"text-right font-semibold text-text",children:Qx(T)}),i.jsx("dt",{className:"pl-5 text-text-3",children:"Input"}),i.jsx("dd",{className:"text-right text-text-2",children:Qx(o.totalInputTokens)}),i.jsx("dt",{className:"pl-5 text-text-3",children:"Output"}),i.jsx("dd",{className:"text-right text-text-2",children:Qx(o.totalOutputTokens)}),i.jsxs("dt",{className:"flex items-center gap-1.5 text-text-2",children:[i.jsx(rR,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Total cost"]}),i.jsx("dd",{className:"text-right font-semibold text-text",children:CX(o.totalCost)}),i.jsxs("dt",{className:"flex items-center gap-1.5 text-text-2",children:[i.jsx(jr,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Elapsed time"]}),i.jsx("dd",{className:"text-right font-semibold text-text",children:A}),i.jsxs("dt",{className:"flex items-center gap-1.5 text-text-2",children:[i.jsx(fM,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Runs"]}),i.jsx("dd",{className:"text-right font-semibold text-text",children:c.length})]})})]})]})};function aFe(t){return t==="open"||t==="in_progress"||t==="awaiting_followup"?"primary":t==="cancelled"?"neutral":rE(t)}LX.displayName="RequestDetail";const oFe="/api/experiments";class PX extends Error{constructor(e,n){super(e),this.status=n,this.name="ExperimentsApiError"}}async function DX(t){const e=await fetch(`${oFe}${t}`);let n={};try{n=await e.json()}catch{n={}}if(!e.ok||n.success===!1)throw new PX(n.error||`HTTP ${e.status}`,e.status);return n.data}function lFe(){return DX("")}function cFe(t){return DX(`/${encodeURIComponent(t)}`)}function OX(t){return t.status==="done"?t.verdict==="worked"?{label:"Worked",tone:"success"}:t.verdict==="didnt"?{label:"Didn't work",tone:"danger"}:{label:"Inconclusive",tone:"attention"}:t.status==="running"?{label:"Measuring",tone:"primary"}:t.status==="cancelled"?{label:"Cancelled",tone:"neutral"}:{label:"Not shipped",tone:"neutral"}}function BX(t){if(t.metric.label)return t.metric.label;const e=t.metric.page??t.metric.query??t.metric.event;return`${t.metric.source.toUpperCase()} ${t.metric.measure}${e?` · ${e}`:""}`}const dFe=()=>{const t=cs(),[e,n]=_.useState(null),[s,r]=_.useState(null),[a,o]=_.useState(!1),l=_.useCallback(async()=>{r(null),o(!1);try{const c=await lFe();n([...c].sort((d,u)=>u.updatedAt.localeCompare(d.updatedAt)))}catch(c){c instanceof PX&&c.status===503?o(!0):r(c instanceof Error?c.message:"Failed to load experiments")}},[]);return _.useEffect(()=>{l()},[l]),a?i.jsx(is,{icon:tm,title:"Experiments are not running",description:"Experiment cards are switched off on this machine, or Crewly is still starting. Nothing to show yet.",action:i.jsx(de,{variant:"secondary",size:"sm",icon:$t,onClick:()=>void l(),children:"Check again"}),"data-testid":"experiments-off"}):s?i.jsxs("div",{className:"flex flex-col items-center gap-3 py-10 text-center","data-testid":"experiments-error",children:[i.jsx("p",{className:"text-sm text-danger",children:s}),i.jsx(de,{variant:"secondary",size:"sm",icon:$t,onClick:()=>void l(),children:"Retry"})]}):e?e.length===0?i.jsx(is,{icon:tm,title:"No experiments yet",description:"An agent attaches an experiment to a ticket that should move a number; it is measured automatically after the change ships.","data-testid":"experiments-empty"}):i.jsx("ul",{className:"overflow-hidden rounded-2xl bg-surface","data-testid":"experiments-list",children:e.map(c=>{const d=OX(c),u=[c.id,BX(c),c.ticket?c.ticket.id:null,`${c.windowDays}-day window`].filter(Boolean).join(" · ");return i.jsx("li",{className:"list-none",children:i.jsx(Ts,{primary:c.title,meta:u,trailing:i.jsx(sn,{tone:d.tone,children:d.label}),onClick:()=>t(qt.experiment(c.id)),"data-testid":`experiment-row-${c.id}`})},c.id)})}):i.jsx("div",{className:"flex justify-center py-10","data-testid":"experiments-loading",children:i.jsx(zt,{})})},uFe={overview:"Overview",timeline:"Timeline"};function v1(t){return!t||t.total===null?"—":`${Number.isInteger(t.total)?t.total.toLocaleString():t.total.toFixed(3)} (${t.start} – ${t.end})`}function t6(t){return t?[`${t.ticketsShipped} shipped (${t.ticketsStarted} started)`,t.ownerTouchesPerTicket===null?`${t.ownerTouches} owner touches`:`${t.ownerTouchesPerTicket} owner touches per ticket`,`stalls ${t.stalls===0?"none":zi(t.stallMs)}`,t.costPerShippedTicket===null?`${Nc(t.costUsd)} spent`:`${Nc(t.costPerShippedTicket)} per shipped ticket`].join(" · "):"Not measured yet"}const hFe=({scope:t})=>{var e;return i.jsxs("section",{"aria-labelledby":"experiment-autopilot-heading","data-testid":"experiment-autopilot",children:[i.jsxs("h2",{id:"experiment-autopilot-heading",className:"mb-2 text-[15px] font-bold text-text",children:["Autopilot: ",t.projectName,t.label?` · ${t.label}`:""]}),i.jsxs("dl",{className:"grid max-w-xl grid-cols-[auto_1fr] gap-x-6 gap-y-2 text-sm",children:[t.processBaseline&&!t.processBaseline.noData&&i.jsxs(i.Fragment,{children:[i.jsx("dt",{className:"text-text-2",children:"Before"}),i.jsx("dd",{className:"text-text",children:t6(t.processBaseline)})]}),i.jsx("dt",{className:"text-text-2",children:"During"}),i.jsx("dd",{className:"text-text",children:(e=t.processResult)!=null&&e.noData?"No autopilot work recorded":t6(t.processResult)}),t.outcomes.map((n,s)=>i.jsxs(an.Fragment,{children:[i.jsx("dt",{className:"text-text-2",children:n.metric.label??`${n.metric.source} ${n.metric.measure}${n.metric.page?` ${n.metric.page}`:""}`}),i.jsx("dd",{className:"break-words text-text",children:n.verdictReason??(n.lastError?`Fetch failed: ${n.lastError}`:`${v1(n.baseline)} → ${v1(n.result)}`)})]},s))]})]})},FX=()=>{const{id:t=""}=Lc(),[e,n]=uu(_h),[s,r]=_.useState(null),[a,o]=_.useState(null),[l,c]=_.useState(!0),d=_.useCallback(async()=>{c(!0),o(null);try{r(await cFe(t))}catch(p){o(p instanceof Error?p.message:"Failed to load the experiment")}finally{c(!1)}},[t]);_.useEffect(()=>{d()},[d]);const u=i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:qt.ticketsBoard(),className:"text-text-2 hover:text-text",children:"Tickets"}),i.jsx("span",{className:"text-text-3",children:"/"}),i.jsx(hs,{to:qt.experiments(),className:"text-text-2 hover:text-text","data-testid":"experiment-detail-back",children:"Experiments"})]});if(l&&!s)return i.jsx("div",{className:"flex h-64 items-center justify-center","data-testid":"experiment-detail-loading",children:i.jsx(zt,{})});if(a||!s)return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-4 sm:p-6","data-testid":"experiment-detail-error",children:[i.jsx(_r,{className:"mb-0",eyebrow:u,title:"Experiment"}),i.jsx(is,{icon:tm,title:"Experiment not found",description:a??void 0,action:i.jsx(de,{variant:"secondary",size:"sm",icon:$t,onClick:()=>void d(),children:"Retry"})})]});const h=OX(s),f=s.traceId.startsWith("tr-")?s.traceId:null;return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-4 sm:p-6","data-testid":"experiment-detail",children:[i.jsx(_r,{className:"mb-0",eyebrow:u,title:s.title,subtitle:`${s.id} · ${BX(s)} · ${s.windowDays}-day window · by ${s.createdBy}`,actions:i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:()=>void d(),loading:l}),tabs:i.jsx(Oc,{"aria-label":"Experiment views",idPrefix:"experiment",value:e,onChange:p=>n(p),tabs:_h.map(p=>({value:p,label:uFe[p]}))})}),e==="timeline"?i.jsx("div",{role:"tabpanel",id:"experiment-panel-timeline","aria-labelledby":"experiment-tab-timeline","data-testid":"experiment-panel-timeline",children:i.jsx(lC,{traceId:f,refParam:"experimentId",refId:s.id})}):i.jsxs("div",{role:"tabpanel",id:"experiment-panel-overview","aria-labelledby":"experiment-tab-overview",className:"flex flex-col gap-6","data-testid":"experiment-panel-overview",children:[i.jsxs("div",{className:"-mt-2 flex flex-wrap items-center gap-x-4 gap-y-2 text-[13px] text-text-2",children:[i.jsx(sn,{tone:h.tone,children:h.label}),s.ticket&&i.jsxs("span",{children:["Ticket ",s.ticket.id]}),s.dueAt&&s.status==="running"&&i.jsxs("span",{children:["Measured after ",s.dueAt.slice(0,10)]})]}),i.jsxs("section",{"aria-labelledby":"experiment-hypothesis-heading",children:[i.jsx("h2",{id:"experiment-hypothesis-heading",className:"mb-2 text-[15px] font-bold text-text",children:"Hypothesis"}),i.jsx("p",{className:"whitespace-pre-wrap text-sm leading-relaxed text-text",children:s.hypothesis})]}),i.jsxs("dl",{className:"grid max-w-xl grid-cols-[auto_1fr] gap-x-6 gap-y-2 text-sm","data-testid":"experiment-results",children:[i.jsx("dt",{className:"text-text-2",children:"Baseline"}),i.jsx("dd",{className:"text-text",children:v1(s.baseline)}),i.jsx("dt",{className:"text-text-2",children:"Result"}),i.jsx("dd",{className:"text-text",children:v1(s.result)}),i.jsx("dt",{className:"text-text-2",children:"Verdict"}),i.jsx("dd",{className:"text-text",children:s.verdict?`${h.label}${s.verdictReason?` — ${s.verdictReason}`:""}`:"Not measured yet"}),s.lastError&&i.jsxs(i.Fragment,{children:[i.jsx("dt",{className:"text-text-2",children:"Last error"}),i.jsx("dd",{className:"break-words text-danger",children:s.lastError})]})]}),s.autopilot&&i.jsx(hFe,{scope:s.autopilot}),i.jsxs("section",{"aria-labelledby":"experiment-log-heading",children:[i.jsx("h2",{id:"experiment-log-heading",className:"mb-2 text-[15px] font-bold text-text",children:"Card log"}),i.jsx("ol",{className:"flex flex-col gap-1.5 text-[13px]","data-testid":"experiment-card-log",children:[...s.timeline].reverse().map((p,x)=>i.jsxs("li",{className:"flex gap-3",children:[i.jsx("span",{className:"w-28 shrink-0 text-text-3",children:T0(p.at)}),i.jsxs("span",{className:"min-w-0 break-words text-text",children:[i.jsx("span",{className:"font-semibold",children:p.event.replace(/_/g," ")}),p.detail?i.jsxs("span",{className:"text-text-2",children:[" — ",p.detail]}):null]})]},`${p.at}-${x}`))})]})]})]})};FX.displayName="ExperimentDetail";const fFe={request:"Request",goal:"Goal",experiment:"Experiment",owner_message:"Your message",autopilot:"Autopilot run",ticket:"Ticket",triage:"Autopilot triage"},UX=()=>{const{traceId:t=""}=Lc(),{names:e}=Bm(),[n,s]=_.useState(null),r=_.useCallback(o=>Jd(o,e)??o,[e]),a=_.useCallback(o=>s(o.root),[]);return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-4 sm:p-6","data-testid":"trace-detail",children:[i.jsx(_r,{className:"mb-0",eyebrow:i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:qt.ticketsBoard(),className:"text-text-2 hover:text-text",children:"Tickets"}),i.jsx("span",{className:"text-text-3",children:"/"}),i.jsx("span",{className:"text-text-2",children:"Run timeline"})]}),title:(n==null?void 0:n.summary)??"Run timeline",subtitle:n?`${fFe[n.kind]} · started ${T0(n.createdAt)}`:void 0}),i.jsx(lC,{traceId:t,nameOf:r,onLoaded:a})]})};UX.displayName="TraceDetail";const pFe=t=>i.jsx(T$,{...t});function mFe(t){return{active:"Active",blocked:"Blocked",waiting_confirmation:"Waiting Confirmation",done:"Done"}[t]??t}function n6(t){return t.charAt(0).toUpperCase()+t.slice(1)}function gFe(t){const e=Date.now(),n=new Date(t).getTime(),s=e-n,r=Math.floor(s/6e4),a=Math.floor(r/60),o=Math.floor(a/24);return r<1?"just now":r<60?`${r}m ago`:a<24?`${a}h ago`:`${o}d ago`}function xFe(t){return t===0?"$0.00":t<.01?`$${t.toFixed(4)}`:`$${t.toFixed(2)}`}function yFe(t){return{total:t.length,active:t.filter(e=>e.status==="active").length,blocked:t.filter(e=>e.status==="blocked").length,waitingConfirmation:t.filter(e=>e.status==="waiting_confirmation").length,done:t.filter(e=>e.status==="done").length,totalCost:t.reduce((e,n)=>e+(n.totalCost||0),0)}}function vFe(t){switch(t){case"open":case"ready":case"running":case"awaiting_followup":return"active";case"blocked":return"blocked";case"waiting_confirmation":return"waiting_confirmation";case"done":case"cancelled":return"done";default:return typeof console<"u"&&t&&console.warn("[RequestList] Unknown backend Request status:",t),"active"}}function bFe(t){switch(t){case"high":return"high";case"low":return"low";default:return"medium"}}const _Fe=new Set(["open","waiting_owner","ready","overdue"]);function SFe(t){return Array.isArray(t)?t.filter(e=>e&&typeof e=="object"&&_Fe.has(String(e.status))).length:0}function wFe(t){return t.map(e=>{const n=Array.isArray(e.workItemIds)?e.workItemIds:[],s=e.intentCategory;return{id:e.id||"",title:e.title||"Untitled Request",status:vFe(e.status||""),priority:bFe(e.priority||""),source:(e.tags||[]).includes("slack")?"slack":"api",requester:"user",category:s&&s.length>0?s:void 0,workItemCount:n.length,updatedAt:e.updatedAt||e.createdAt||new Date().toISOString(),missionLink:e.missionId?`Mission: ${e.missionId.slice(0,8)}`:void 0,totalInputTokens:e.totalInputTokens||0,totalOutputTokens:e.totalOutputTokens||0,totalCost:e.totalCost||0,ownerAgent:e.ownerAgent||void 0,openItemCount:SFe(e.openItems)}}).sort((e,n)=>new Date(n.updatedAt).getTime()-new Date(e.updatedAt).getTime())}const EFe=25,CFe=300,kFe={slack:kc,email:KH,chat:qH,api:lR,manual:JH},AFe={active:"primary",blocked:"danger",waiting_confirmation:"attention",done:"success"},hx={active:"Active",blocked:"Blocked",waiting_confirmation:"Waiting",done:"Done"},TFe={status:["active"],only:[]},NFe=()=>{const t=cs(),{names:e}=Bm(),[n,s]=_.useState([]),[r,a]=_.useState(!0),[o,l]=_.useState(null),[c,d]=_.useState(TFe),[u,h]=_.useState(""),[f,p]=_.useState("");_.useEffect(()=>{const y=setTimeout(()=>p(u),CFe);return()=>clearTimeout(y)},[u]);const x=_.useCallback(async()=>{a(!0),l(null);try{const y=await lt.getRequests();s(Array.isArray(y)?wFe(y):[])}catch(y){l(y instanceof Error?y.message:"Failed to load requests"),s([])}finally{a(!1)}},[]);_.useEffect(()=>{x()},[x]);const v=_.useMemo(()=>yFe(n),[n]),m=_.useMemo(()=>[{id:"status",label:"Status",single:!0,options:[{value:"active",label:hx.active,count:v.active},{value:"blocked",label:hx.blocked,count:v.blocked},{value:"waiting_confirmation",label:hx.waiting_confirmation,count:v.waitingConfirmation},{value:"done",label:hx.done,count:v.done}]},{id:"only",label:"Only",options:[{value:"assigned_to_me",label:"Assigned to me"},{value:"urgent",label:"Urgent"}]}],[v]),g=_.useMemo(()=>{var E;const y=(E=c.status)==null?void 0:E[0],b=c.only??[],S=f.trim().toLowerCase();return n.filter(k=>!(y&&k.status!==y||b.includes("urgent")&&k.priority!=="critical"&&k.priority!=="high"||b.includes("assigned_to_me")&&k.requester!=="user"||S&&!(k.title.toLowerCase().includes(S)||k.requester.toLowerCase().includes(S)||(k.missionLink??"").toLowerCase().includes(S))))},[n,c,f]);return i.jsxs("div",{className:"flex min-w-0 flex-col gap-4","data-testid":"requests-page",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(Zo,{groups:m,value:c,onChange:d}),i.jsx(tI,{value:u,onChange:h,placeholder:"Search requests…","data-testid":"request-search-input"}),i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:()=>void x(),className:"ml-auto"})]}),r?i.jsx("div",{"data-testid":"request-list-loading",children:i.jsx(sE,{count:4})}):o?i.jsxs("div",{className:"flex flex-col items-center gap-3 py-16 text-text-2","data-testid":"request-list-error",children:[i.jsx("span",{className:"text-sm text-danger",children:o}),i.jsx(de,{variant:"link",onClick:()=>void x(),children:"Retry"})]}):g.length===0?i.jsxs("div",{className:"flex flex-col items-center gap-3 py-16 text-text-2","data-testid":"request-list-empty",children:[i.jsx(VS,{className:"h-10 w-10 opacity-40","aria-hidden":"true"}),i.jsx("span",{className:"text-sm",children:n.length===0?"No requests yet. They appear here when you ask for something in Slack or chat.":"No requests match the current filters."})]}):i.jsx("div",{className:"overflow-hidden rounded-2xl bg-surface","data-testid":"request-list",children:i.jsx(fs,{limit:EFe,as:"ul","data-testid":"request-list-rows",children:g.map(y=>{const b=kFe[y.source]??VS,S=Jd(y.ownerAgent,e),E=[y.category?y.category.replace(/_/g," "):null,S?`via ${S}`:null,y.priority==="high"||y.priority==="critical"?"Urgent":null,y.workItemCount>0?`${y.workItemCount} run${y.workItemCount===1?"":"s"}`:null,y.missionLink?y.missionLink.replace(/^Mission:/,"Goal:"):null,gFe(y.updatedAt)].filter(Boolean),k=y.openItemCount??0;return i.jsx("li",{className:"list-none border-b border-border-soft last:border-b-0","data-testid":`request-row-${y.id}`,children:i.jsx(Ts,{leading:i.jsx("span",{title:n6(y.source),children:i.jsx(b,{className:"h-4 w-4 text-text-3","aria-label":n6(y.source)})}),primary:i.jsx("span",{title:y.title,children:eI(y.title)}),meta:i.jsxs(i.Fragment,{children:[k>0&&i.jsxs("span",{className:"font-semibold text-attention",title:"Promises or questions the agent still owes you",children:[k," open item",k===1?"":"s",E.length>0?" · ":""]}),E.join(" · ")]}),trailing:i.jsx(sn,{tone:AFe[y.status],title:mFe(y.status),children:hx[y.status]}),onClick:()=>t(qt.request(y.id)),className:"border-b-0","data-testid":`request-row-${y.id}-row`})},y.id)})})}),!r&&!o&&n.length>0&&i.jsxs("p",{className:"text-[13px] text-text-3","data-testid":"requests-total",children:[v.total," request",v.total===1?"":"s"," · total cost ",xFe(v.totalCost)]})]})},MFe=25,jFe=300,RFe=[{value:"running",label:"Running"},{value:"queued",label:"Queued"},{value:"done",label:"Completed"},{value:"failed",label:"Failed"},{value:"blocked",label:"Blocked"},{value:"cancelled",label:"Cancelled"}],s6={running:0,blocked:1,failed:2,done:3,completed:3,cancelled:4,queued:5,scheduled:5},zX=()=>{const t=cs(),{names:e}=Bm(),n=TX(),[s,r]=_.useState([]),[a,o]=_.useState(!0),[l,c]=_.useState(null),[d,u]=_.useState({status:[]}),[h,f]=_.useState(""),[p,x]=_.useState(""),v=_.useRef(),m=_.useCallback(E=>{f(E),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>x(E),jFe)},[]);_.useEffect(()=>()=>{v.current&&clearTimeout(v.current)},[]);const g=_.useCallback(async()=>{o(!0),c(null);try{const E=await lt.getWorkItems();r(Array.isArray(E)?E:[])}catch(E){c(E instanceof Error?E.message:"Failed to load runs")}finally{o(!1)}},[]);_.useEffect(()=>{g()},[g]);const y=_.useMemo(()=>{const E={};for(const k of s){const T=k.status==="scheduled"?"queued":k.status;E[T]=(E[T]||0)+1}return E},[s]),b=_.useMemo(()=>[{id:"status",label:"Status",single:!0,options:RFe.map(E=>({...E,count:y[E.value]??0}))}],[y]),S=_.useMemo(()=>{var T;const E=(T=d.status)==null?void 0:T[0],k=p.trim().toLowerCase();return s.filter(A=>!(E&&A.status!==E&&!(E==="queued"&&A.status==="scheduled")||k&&!(A.title.toLowerCase().includes(k)||A.id.toLowerCase().includes(k)||(A.target??"").toLowerCase().includes(k)||(Jd(A.target,e)??"").toLowerCase().includes(k)||A.type.toLowerCase().includes(k)))).sort((A,M)=>{const N=s6[A.status]??5,L=s6[M.status]??5;return N!==L?N-L:new Date(M.createdAt).getTime()-new Date(A.createdAt).getTime()})},[s,d,p,e]);return i.jsxs("div",{className:"flex min-w-0 flex-col gap-4","data-testid":"workitems-page",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(Zo,{groups:b,value:d,onChange:u}),i.jsx(tI,{value:h,onChange:m,placeholder:"Search by title, ID, agent…","data-testid":"workitems-search"}),i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:()=>void g(),className:"ml-auto","data-testid":"workitems-refresh"})]}),a&&i.jsx("div",{"data-testid":"workitems-loading",children:i.jsx(sE,{count:4})}),l&&!a&&i.jsxs(Ye,{variant:"error",title:"Failed to load runs",onClose:()=>c(null),"data-testid":"workitems-error",children:[l,i.jsx(de,{variant:"ghost",size:"sm",onClick:()=>void g(),className:"mt-2",children:"Retry"})]}),!a&&!l&&S.length===0&&i.jsxs("div",{className:"flex flex-col items-center gap-3 py-16 text-text-2","data-testid":"workitems-empty",children:[i.jsx(VS,{className:"h-10 w-10 opacity-40","aria-hidden":"true"}),i.jsx("span",{className:"text-sm",children:s.length===0?"No runs yet.":"No runs match the current filters."})]}),!a&&!l&&S.length>0&&i.jsx("div",{className:"overflow-hidden rounded-2xl bg-surface","data-testid":"workitems-list",children:i.jsx(fs,{limit:MFe,as:"ul",children:S.map(E=>{const k=k$(E.title,n),T=Jd(E.target,e,!0),A=[oP(E.type),T,k,oC(E.createdAt)].filter(Boolean).join(" · ");return i.jsx("li",{className:"list-none border-b border-border-soft last:border-b-0",children:i.jsx(Ts,{primary:i.jsx("span",{title:`${E.title} (${E.id.slice(0,8)})`,children:E.title}),meta:A,trailing:i.jsx(sn,{tone:rE(E.status==="cancelled"||E.status==="queued"||E.status==="scheduled"?"neutral":E.status),children:aP(E.status)}),onClick:()=>t(qt.run(E.id)),className:"border-b-0","data-testid":`workitem-row-${E.id}`})},E.id)})})}),!a&&!l&&s.length>0&&i.jsxs("p",{className:"text-[13px] text-text-3","data-testid":"workitems-total",children:[s.length," run",s.length===1?"":"s"," in the pool"]})]})};zX.displayName="WorkItems";const IFe=({onCreated:t})=>{const[e,n]=_.useState(!1),[s,r]=_.useState([]),[a,o]=_.useState([]),l=()=>{n(!0),Promise.resolve().then(()=>lt.getProjects()).then(c=>r((c??[]).map(d=>({id:d.id,name:d.name})))).catch(()=>r([])),Promise.resolve().then(()=>lt.getTeams()).then(c=>o(c??[])).catch(()=>o([]))};return i.jsxs(i.Fragment,{children:[i.jsx(de,{size:"sm",icon:qn,onClick:l,"data-testid":"tickets-new-ticket",children:hi.NEW_TICKET}),i.jsx(A$,{open:e,ticket:null,projects:s,teams:a,onClose:()=>n(!1),onSaved:t})]})},LFe={board:"Board",requests:"Requests",runs:"Runs",experiments:"Experiments"},PFe={board:"Everything your crew is working on",requests:"Everything you asked for, from every channel",runs:"What the agents actually ran",experiments:"Changes that should move a number, and whether they did"},DFe=()=>{const[t,e]=uu(MO),[n,s]=_.useState(0),[r,a]=_.useState(null),o=_.useCallback(l=>a(l.toReview),[]);return i.jsxs("div",{children:[i.jsx(_r,{title:"Tickets",subtitle:PFe[t],actions:i.jsx(IFe,{onCreated:()=>s(l=>l+1)}),tabs:i.jsx(Oc,{"aria-label":"Tickets views",idPrefix:"tickets",value:t,onChange:l=>e(l),tabs:MO.map(l=>({value:l,label:LFe[l],...l==="board"&&r?{count:r,attention:!0}:{}}))})}),i.jsxs("div",{role:"tabpanel",id:`tickets-panel-${t}`,"aria-labelledby":`tickets-tab-${t}`,"data-testid":`tickets-panel-${t}`,children:[t==="board"&&i.jsx(pFe,{showNewTicket:!1,refreshKey:n,onCountsChange:o}),t==="requests"&&i.jsx(NFe,{}),t==="runs"&&i.jsx(zX,{}),t==="experiments"&&i.jsx(dFe,{})]})]})},OFe=({member:t,teamId:e,onClose:n})=>{const[s,r]=_.useState(null),[a,o]=_.useState(!1),[l,c]=_.useState(null),[d,u]=_.useState(!1),[h,f]=_.useState(null),[p,x]=_.useState(!1),[v,m]=_.useState("prompt"),g=_.useRef(null);_.useEffect(()=>(y(),()=>{S()}),[t.id,e]);const y=async()=>{if(!t.sessionName){c("No active session for this team member");return}try{o(!0),c(null),jt.isConnected()||await jt.connect(),b(),jt.subscribeToSession(t.sessionName),await E()}catch(L){console.error("Error initializing terminal:",L),c("Failed to connect to terminal"),x(!1)}finally{o(!1)}},b=()=>{if(!t.sessionName)return;const L=G=>{G.sessionName===t.sessionName&&(r(K=>({...K,memberId:t.id,memberName:t.name,sessionName:t.sessionName,output:G.content,timestamp:G.timestamp})),setTimeout(()=>{g.current&&(g.current.scrollTop=g.current.scrollHeight)},10))},I=G=>{G.sessionName===t.sessionName&&(r({memberId:t.id,memberName:t.name,sessionName:t.sessionName,output:G.content,timestamp:G.timestamp}),x(!0),c(null))},D=G=>{G.sessionName===t.sessionName&&(console.log("Successfully subscribed to session:",G.sessionName),x(!0),c(null))},z=G=>{G.sessionName===t.sessionName&&(console.error("WebSocket error for session:",G),c(G.error||"WebSocket error occurred"),x(!1))},U=()=>{x(!0)};return jt.on("terminal_output",L),jt.on("initial_terminal_state",I),jt.on("subscription_confirmed",D),jt.on("error",z),jt.on("connected",U),()=>{jt.off("terminal_output",L),jt.off("initial_terminal_state",I),jt.off("subscription_confirmed",D),jt.off("error",z),jt.off("connected",U)}},S=()=>{h&&clearInterval(h),t.sessionName&&jt.isConnected()&&jt.unsubscribeFromSession(t.sessionName)};_.useEffect(()=>{if(d){const L=setInterval(()=>{E()},15e3);f(L)}else h&&(clearInterval(h),f(null));return()=>{h&&clearInterval(h)}},[d]);const E=async()=>{if(!t.sessionName){c("No active session for this team member");return}o(!0),c(null);try{const L=await fetch(`/api/teams/${e}/members/${t.id}/session?lines=100`);if(L.ok){const I=await L.json();I.success?r(I.data):c(I.error||"Failed to fetch session data")}else{const I=await L.json();c(I.error||"Failed to fetch session data")}}catch(L){c("Network error while fetching session data"),console.error("Error fetching session data:",L)}finally{o(!1)}},k=L=>({orchestrator:"text-primary",pm:"text-blue-400",developer:"text-emerald-400",qa:"text-amber-400",tester:"text-red-400",designer:"text-pink-400"})[L]||"text-text-secondary-dark",T=L=>({activating:"warning",active:"success"})[L]||"default",A=L=>L==="in_progress"?"success":"default",M=L=>new Date(L).toLocaleString(),N=i.jsxs("span",{className:"flex flex-col gap-2",children:[i.jsx("span",{children:t.name}),i.jsxs("span",{className:"flex flex-wrap items-center gap-1.5",children:[i.jsx(mn,{className:k(t.role),children:t.role}),i.jsxs(mn,{variant:T(t.agentStatus),children:["Agent: ",t.agentStatus]}),i.jsxs(mn,{variant:A(t.workingStatus),children:["Work: ",t.workingStatus]})]})]});return i.jsx(Pr,{isOpen:!0,onClose:n,title:N,size:"xxl",children:i.jsxs(eE,{value:v,onValueChange:L=>m(L),children:[i.jsxs(tE,{"aria-label":"Member details",children:[i.jsx(Bh,{value:"prompt",children:"System Prompt"}),i.jsx(Bh,{value:"terminal",children:"Terminal Output"})]}),i.jsx(C0,{value:"prompt",children:i.jsx("pre",{className:"max-h-[55vh] overflow-auto whitespace-pre-wrap rounded-2xl border border-border-dark bg-background-dark p-4 text-xs font-mono text-text-primary-dark",children:t.systemPrompt})}),i.jsxs(C0,{value:"terminal",className:"space-y-3",children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[i.jsx("div",{className:"text-xs text-text-secondary-dark",children:t.sessionName&&i.jsxs("span",{children:["Session: ",t.sessionName]})}),i.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[i.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-text-secondary-dark",children:[i.jsx(NR,{status:p?"online":"offline",size:"sm"}),p?"Live":"Offline"]}),i.jsx(vi,{size:"sm",label:"Auto-refresh (fallback)",checked:d,onChange:L=>u(L.target.checked),disabled:p}),i.jsx(de,{onClick:E,disabled:p,loading:a,variant:"secondary",size:"sm",children:a?"Loading...":"Manual Refresh"})]})]}),a&&!s&&i.jsx(zt,{size:"md",text:"Loading session data...",className:"py-8"}),l&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs(Ye,{variant:"error",children:["Error: ",l]}),i.jsx(de,{onClick:E,variant:"outline",size:"sm",children:"Retry"})]}),s&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs("p",{className:"text-xs text-text-secondary-dark",children:["Last updated: ",M(s.timestamp)]}),i.jsx("pre",{className:"max-h-[50vh] overflow-auto whitespace-pre-wrap rounded-2xl border border-border-dark bg-background-dark p-4 text-xs font-mono text-text-primary-dark",ref:g,children:s.output||"No output available"})]}),!a&&!l&&!s&&i.jsx(is,{compact:!0,title:"No session data available"})]})]})})},BFe={xs:"w-6 h-6 text-xs",sm:"w-8 h-8 text-sm",md:"w-10 h-10 text-base",lg:"w-12 h-12 text-lg",xl:"w-16 h-16 text-xl"},FFe={active:"bg-green-500",inactive:"bg-text-secondary-dark",activating:"bg-yellow-500"},UFe=({name:t,avatar:e,size:n="md",className:s="",showStatus:r=!1,status:a,ringClass:o=""})=>{const l=BFe[n],c=()=>{if(e&&(e.startsWith("http")||e.startsWith("data:")))return i.jsx("img",{src:e,alt:`${t}'s avatar`,title:t,className:`${l} rounded-full object-cover ${o} ${s}`});if(e)return i.jsx("div",{className:`${l} rounded-full bg-background-dark border border-border-dark flex items-center justify-center ${o} ${s}`,title:t,children:i.jsx("span",{children:e})});const d=t?t.charAt(0).toUpperCase():"";return i.jsx("div",{className:`${l} rounded-full bg-background-dark border border-border-dark flex items-center justify-center ${o} ${s}`,title:t,children:d})};return i.jsxs("div",{className:"relative inline-block",children:[c(),r&&a&&i.jsx("span",{className:`absolute bottom-0 right-0 w-3 h-3 ${FFe[a]} rounded-full border-2 border-surface-dark`,title:a})]})};function zFe(t){const e=new Map;for(const n of t)if(n.parentTeamId){const s=e.get(n.parentTeamId)||[];s.push(n),e.set(n.parentTeamId,s)}return e}const HX=({team:t,depth:e,childrenMap:n,projectMap:s,onTeamClick:r})=>{var f;const a=n.get(t.id)||[],[o,l]=_.useState(!0),c=a.length>0,d=t.members||[],u=d.some(p=>p.agentStatus==="active"),h=(f=t.projectIds)!=null&&f[0]?s[t.projectIds[0]]:void 0;return i.jsxs("div",{"data-testid":`tree-node-${t.id}`,children:[i.jsxs("div",{className:"flex items-center gap-2 py-2 px-3 rounded-lg hover:bg-background-dark cursor-pointer transition-colors group",style:{paddingLeft:`${e*24+12}px`},onClick:()=>r(t.id),children:[c?i.jsx("button",{onClick:p=>{p.stopPropagation(),l(!o)},className:"p-0.5 text-text-secondary-dark hover:text-text-primary-dark","data-testid":`toggle-${t.id}`,"aria-label":o?"Collapse":"Expand","aria-expanded":o,children:o?i.jsx(Eo,{className:"w-4 h-4"}):i.jsx(cr,{className:"w-4 h-4"})}):i.jsx("span",{className:"w-5"}),i.jsx("span",{className:"font-medium text-sm truncate",children:t.name}),u&&i.jsx("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] font-medium rounded-full bg-green-500/10 text-green-400",children:"Active"}),i.jsxs("span",{className:"text-xs text-text-secondary-dark ml-auto flex items-center gap-1",children:[i.jsx(vr,{className:"w-3 h-3"}),d.length]}),h&&i.jsxs("span",{className:"text-xs text-text-secondary-dark flex items-center gap-1 ml-2",children:[i.jsx(Xo,{className:"w-3 h-3"}),h]}),i.jsx("div",{className:"flex items-center ml-2",children:d.slice(0,3).map((p,x)=>i.jsx("div",{style:{marginLeft:x===0?0:-4},children:i.jsx(UFe,{name:p.name,avatar:p.avatar,size:"xs",ringClass:"ring-1 ring-surface-dark"})},p.id))})]}),c&&o&&i.jsx("div",{"data-testid":`children-${t.id}`,children:a.map(p=>i.jsx(HX,{team:p,depth:e+1,childrenMap:n,projectMap:s,onTeamClick:r},p.id))})]})},HFe=({teams:t,projectMap:e,onTeamClick:n})=>{const s=_.useMemo(()=>zFe(t),[t]),r=_.useMemo(()=>t.filter(a=>!a.parentTeamId),[t]);return r.length===0?i.jsx("div",{className:"text-center py-8 text-text-secondary-dark text-sm",children:"No teams to display"}):i.jsx("div",{className:"bg-surface-dark border border-border-dark rounded-xl p-2","data-testid":"teams-tree-view",children:r.map(a=>i.jsx(HX,{team:a,depth:0,childrenMap:s,projectMap:e,onTeamClick:n},a.id))})};function GFe(t){return(t.members??[]).reduce((e,n)=>{const s=n.readyAt||n.updatedAt;return s?e?new Date(s)>new Date(e)?s:e:s:e},null)}function $Fe(t,e,n){var a;const s=t.members??[];return(((a=t.projectIds)==null?void 0:a.length)??0)>0?{label:e??"Project",needsProject:!1}:s.some(o=>o.role==="orchestrator"||o.role==="auditor")?{label:"System team",needsProject:!1}:t.parentTeamId||(n??0)>0?{label:"Parent team",needsProject:!1}:{label:"No project yet",needsProject:!0}}const WFe=({team:t,projectName:e,subTeamCount:n,onOpen:s,onEdit:r,onStart:a,onStop:o,onOpenChat:l,onOpenWiki:c,onDelete:d,isPinned:u=!1,onTogglePin:h,onPause:f,onResume:p})=>{const[x,v]=_.useState(null),m=t.members??[],g=m.some(N=>N.agentStatus==="active"),y=m.filter(N=>N.loginRequired),b=$Fe(t,e,n),S=D$(t),E=GFe(t),k=(n??0)>0?`${n} sub-team${n===1?"":"s"} · ${m.length} member${m.length===1?"":"s"}`:m.length===0?"No members":m.map(N=>N.name).join(", "),T=i.jsxs(i.Fragment,{children:[i.jsx("span",{className:b.needsProject?"text-attention":void 0,"data-testid":b.needsProject?"assign-project-cta":void 0,children:b.label}),i.jsx("span",{className:"text-text-3",children:" · "}),i.jsx("span",{children:k}),E&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-3",children:" · "}),i.jsx("span",{title:`Last activity: ${new Date(E).toLocaleString()}`,children:Ml(E)})]})]}),A=[{label:"View team",onClick:()=>s(t.id)},...r?[{label:"Edit team",onClick:()=>r(t.id)}]:[],...l?[{label:"Open chat",onClick:()=>l(t.id)}]:[],...c?[{label:"Open wiki",onClick:()=>c(t.id)}]:[],...h?[{label:u?"Unpin from favorites":"Pin to favorites",onClick:h}]:[],...!S&&f?[{label:"Pause team…",onClick:()=>f(t.id)}]:[],...S&&p?[{label:"Resume team",onClick:()=>p(t.id)}]:[],...d?[{label:"Delete team",danger:!0,separator:!0,onClick:()=>v("delete")}]:[]],M=S&&p?i.jsx(de,{variant:"secondary",size:"xs",onClick:()=>p(t.id),"data-testid":`resume-btn-${t.id}`,children:"Resume"},"resume"):g?o&&i.jsx(de,{variant:"secondary",size:"xs",onClick:()=>v("stop"),"data-testid":`stop-btn-${t.id}`,children:"Stop"},"stop"):a&&i.jsx(de,{variant:"secondary",size:"xs",onClick:()=>a(t.id),"data-testid":`start-btn-${t.id}`,children:"Start"},"start");return i.jsxs(i.Fragment,{children:[i.jsx(Ts,{"data-testid":`team-row-${t.id}`,onClick:()=>s(t.id),primary:i.jsxs("span",{className:"inline-flex min-w-0 items-center gap-2",children:[i.jsx("span",{className:"truncate",children:t.name}),u&&i.jsx(iy,{className:"h-3.5 w-3.5 shrink-0 text-text-3","aria-label":"Pinned"})]}),meta:T,trailing:i.jsxs("span",{className:"flex items-center gap-2",children:[y.length>0&&i.jsx("span",{className:"flex items-center gap-1","data-testid":"team-sign-in-needed",children:y.map(N=>i.jsx(zR,{loginRequired:N.loginRequired,agentLabel:N.name,runtimeType:N.runtimeType},N.id))}),S?i.jsx("span",{title:O$(t),"data-testid":`team-paused-${t.id}`,children:i.jsx(sn,{tone:"attention",children:"Paused"})}):i.jsx(sn,{tone:g?"success":"neutral",children:g?"Active":"Idle"})]}),actions:M?[M]:void 0,overflow:A,overflowLabel:`More actions for ${t.name}`}),i.jsx(G0,{isOpen:x==="stop",onCancel:()=>v(null),onConfirm:()=>{v(null),o==null||o(t.id)},title:"Stop Team",message:`Are you sure you want to stop all agents in "${t.name}"? Active work will be interrupted.`,confirmLabel:"Stop Team",confirmVariant:"danger"}),i.jsx(G0,{isOpen:x==="delete",onCancel:()=>v(null),onConfirm:()=>{v(null),d==null||d(t.id)},title:"Delete Team",message:`Delete team "${t.name}"? Its members and terminal sessions are removed. This cannot be undone.`,confirmLabel:"Delete",confirmVariant:"danger"})]})},r6=3e4,VFe=3e5,KFe=2;function qFe(t,e,n,s){const[r,a]=_.useState([]),[o,l]=_.useState(!1),[c,d]=_.useState(null),u=_.useRef(null),h=_.useRef(!0),f=_.useRef(0),p=_.useRef(null),x=_.useRef(!1),v=_.useRef(t),m=_.useRef(n),g=_.useRef(s),y=_.useRef(e);v.current=t,m.current=n,g.current=s,y.current=e;const b=_.useCallback(()=>f.current===0?r6:Math.min(r6*Math.pow(KFe,f.current),VFe),[]),S=_.useCallback(()=>{if(!h.current||!y.current)return;u.current&&clearTimeout(u.current);const A=b();u.current=setTimeout(()=>{k()},A)},[b]),E=_.useCallback(async()=>{var A;if(!x.current){x.current=!0;try{const N=await(await fetch("/api/cloud/device-id")).json();N.success&&((A=N.data)!=null&&A.deviceId)&&(p.current=N.data.deviceId)}catch{}}},[]),k=_.useCallback(async()=>{const A=v.current;if(!A||!h.current)return;await E();const M={"Content-Type":"application/json",Authorization:`Bearer ${A}`};try{const N={deviceName:g.current,teams:m.current};p.current&&(N.deviceId=p.current),await fetch(`${GM}/devices/heartbeat`,{method:"POST",headers:M,body:JSON.stringify(N)});const I=await(await fetch(`${GM}/devices`,{headers:M})).json();h.current&&I.success&&(a(I.data||[]),d(null),f.current=0)}catch(N){h.current&&(f.current=Math.min(f.current+1,10),d(N instanceof Error?N.message:"Heartbeat failed"))}S()},[S,E]),T=_.useCallback(async()=>{l(!0),f.current=0,await k(),h.current&&l(!1)},[k]);return _.useEffect(()=>{if(h.current=!0,!e||!t){a([]),f.current=0;return}return l(!0),k().finally(()=>{h.current&&l(!1)}),()=>{h.current=!1,u.current&&(clearTimeout(u.current),u.current=null)}},[e,t,k]),{devices:r,isLoading:o,error:c,refresh:T}}function XFe(){const[t,e]=_.useState(null),[n,s]=_.useState(!0),[r,a]=_.useState(!1),[o,l]=_.useState(null),c=_.useRef(!0),d=_.useCallback(async()=>{try{const p=await lt.getCloudStatus();c.current&&(e(p),l(null))}catch{c.current&&e({connected:!1,tier:null,cloudUrl:null,status:"disconnected"})}},[]);_.useEffect(()=>(c.current=!0,(async()=>{await d(),c.current&&s(!1)})(),()=>{c.current=!1}),[d]);const u=_.useCallback(async(p,x)=>{a(!0),l(null);try{const v=await lt.connectToCloud(p,x);return c.current&&e({connected:v.connected,tier:v.tier,cloudUrl:v.cloudUrl,status:"connected"}),!0}catch(v){return c.current&&l(v instanceof Error?v.message:"Connection failed"),!1}finally{c.current&&a(!1)}},[]),h=_.useCallback(async()=>{a(!0),l(null);try{return await lt.disconnectFromCloud(),c.current&&e({connected:!1,tier:null,cloudUrl:null,status:"disconnected"}),!0}catch(p){return c.current&&l(p instanceof Error?p.message:"Disconnect failed"),!1}finally{c.current&&a(!1)}},[]),f=_.useCallback(async()=>{await d()},[d]);return{isConnected:(t==null?void 0:t.connected)??!1,tier:(t==null?void 0:t.tier)??null,isLoading:n,isActioning:r,error:o,connect:u,disconnect:h,refresh:f}}const YFe=6,i6=t=>{var e;return((e=t.members)==null?void 0:e.some(n=>n.agentStatus==="active"))??!1},JFe=({createOpen:t,onCreateOpenChange:e,onCount:n})=>{var Te,se;const s=cs(),{isPinned:r,togglePin:a}=Z1(),[o,l]=_.useState([]),[c,d]=_.useState(""),[u,h]=_.useState({status:[],project:[]}),f=((Te=u.status)==null?void 0:Te[0])??"all",p=((se=u.project)==null?void 0:se[0])??"all",[x,v]=_.useState(!1),m=t??x,g=_.useCallback(W=>{e?e(W):v(W)},[e]),[y,b]=_.useState(null),[S,E]=_.useState(""),[k,T]=_.useState(!0),[A,M]=_.useState("list"),[N,L]=_.useState([]),{showError:I,AlertComponent:D}=Jh(),z=Object.fromEntries(N.map(W=>[W.id,W.name])),{isConnected:U,tier:G}=XFe(),{getAccessToken:K}=jm(),P=U&&G==="pro"?K():null,B=_.useMemo(()=>o.map(W=>({id:W.id,name:W.name,memberCount:W.members.length})),[o]),R=U&&G==="pro",{devices:F,isLoading:q,refresh:$}=qFe(P,R,B,typeof window<"u"&&window.location.hostname||"My Device"),re=_.useMemo(()=>{let W=o;return c&&(W=W.filter(ae=>{var ee;return ae.name.toLowerCase().includes(c.toLowerCase())||ae.description&&ae.description.toLowerCase().includes(c.toLowerCase())||((ee=ae.projectIds)==null?void 0:ee.length)>0&&ae.projectIds.some(le=>le.toLowerCase().includes(c.toLowerCase()))||ae.members.some(le=>le.name.toLowerCase().includes(c.toLowerCase())||le.role.toLowerCase().includes(c.toLowerCase()))})),f!=="all"&&(W=W.filter(ae=>f==="active"?ae.members.some(ee=>ee.agentStatus==="active"):f==="inactive"?!ae.members.some(ee=>ee.agentStatus==="active"):!0)),p!=="all"&&(W=W.filter(ae=>{var ee;return(ee=ae.projectIds)==null?void 0:ee.includes(p)})),W=W.filter(ae=>!ae.parentTeamId),W},[o,c,f,p]),ne=_.useMemo(()=>{const W=new Map;for(const ae of o)ae.parentTeamId&&W.set(ae.parentTeamId,(W.get(ae.parentTeamId)||0)+1);return W},[o]),J=_.useCallback(W=>{l(ae=>ae.map(ee=>ee.id===W.teamId?{...ee,members:ee.members.map(le=>le.id===W.memberId||le.sessionName===W.sessionName?{...le,agentStatus:W.agentStatus}:le)}:ee))},[]);_.useEffect(()=>{X(),H()},[]),_.useEffect(()=>(jt.on("team_member_status_changed",J),()=>{jt.off("team_member_status_changed",J)}),[J]);const H=async()=>{try{const W=await lt.getProjects();L(W.map(ae=>({id:ae.id,name:ae.name})))}catch(W){Na(W,{context:"Loading projects for filter"})}},X=async()=>{try{const ae=(await lt.getTeams()).map(ee=>({...ee,members:qR(ee.members)}));l(ae)}catch(W){Na(W,{context:"fetchTeams"}),l([])}finally{T(!1)}},Z=async W=>{try{const ae=await lt.createTeam(W);l(ee=>[...ee,ae]),g(!1)}catch(ae){Na(ae,{context:"handleCreateTeam"}),I("Error creating team: "+(ae instanceof Error?ae.message:"Unknown error"))}},oe=async W=>{try{await lt.startTeam(W)}catch(ae){Na(ae,{context:"handleStartTeam"}),I("Failed to start team: "+(ae instanceof Error?ae.message:"Unknown error"))}},ye=async W=>{try{await lt.stopTeam(W)}catch(ae){Na(ae,{context:"handleStopTeam"}),I("Failed to stop team: "+(ae instanceof Error?ae.message:"Unknown error"))}},[Q,Ce]=_.useState(null),[ie,ge]=_.useState(!1),he=async W=>{if(Q){ge(!0);try{await lt.pauseTeam(Q.id,W),Ce(null),await X()}catch(ae){I("Failed to pause team: "+(ae instanceof Error?ae.message:"Unknown error"))}finally{ge(!1)}}},ke=async W=>{try{await lt.resumeTeam(W),await X()}catch(ae){I("Failed to resume team: "+(ae instanceof Error?ae.message:"Unknown error"))}},Y=async W=>{try{await lt.deleteTeam(W),l(ae=>ae.filter(ee=>ee.id!==W))}catch(ae){I("Failed to delete team: "+(ae instanceof Error?ae.message:"Unknown error"))}},Ae=_.useMemo(()=>o.filter(W=>!W.parentTeamId),[o]);_.useEffect(()=>{k||n==null||n(Ae.length)},[k,Ae.length,n]);const Ee=()=>{b(null),E("")};if(k)return i.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:i.jsx(zt,{size:"xl",text:"Loading teams..."})});const _e=!!c||f!=="all"||p!=="all";return i.jsxs("div",{"data-testid":"teams-list-page",children:[i.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2","data-testid":"teams-toolbar",children:[i.jsx(Zo,{value:u,onChange:h,groups:[{id:"status",label:"Status",single:!0,options:[{value:"active",label:"Active",count:Ae.filter(i6).length},{value:"inactive",label:"Idle",count:Ae.filter(W=>!i6(W)).length}]},...N.length>0?[{id:"project",label:"Project",single:!0,options:N.map(W=>({value:W.id,label:W.name}))}]:[]]}),i.jsx(YR,{label:"Search teams",value:c,onChange:d}),i.jsxs("div",{className:"ml-auto flex items-center gap-1",role:"group","aria-label":"View",children:[i.jsx(Zt,{icon:Cee,size:"xs","aria-label":"List view",title:"List view","aria-pressed":A==="list",className:A==="list"?"text-primary-text bg-primary-soft":"text-text-2",onClick:()=>M("list")}),i.jsx(Zt,{icon:S0,size:"xs","aria-label":"Tree view",title:"Tree view (parent and sub-teams)","aria-pressed":A==="tree",className:A==="tree"?"text-primary-text bg-primary-soft":"text-text-2",onClick:()=>M("tree")})]})]}),A==="tree"?o.length>0&&i.jsx(HFe,{teams:o,projectMap:z,onTeamClick:W=>s(qt.team(W))}):re.length>0?i.jsx("div",{className:"rounded-2xl border border-border-soft","data-testid":"teams-list",children:i.jsx(fs,{limit:YFe,"data-testid":"teams-show-all",children:re.map(W=>{var ae;return i.jsx(WFe,{team:W,projectName:((ae=W.projectIds)==null?void 0:ae.length)>0?z[W.projectIds[0]]:void 0,subTeamCount:ne.get(W.id),onOpen:ee=>s(qt.team(ee)),onEdit:ee=>s(`${qt.team(ee)}?edit=true`),onStart:oe,onStop:ye,onOpenChat:ee=>s(`${Yt.chat}?${Gd}=${ee}`),onOpenWiki:ee=>s(`${Yt.wiki}?${Gd}=${ee}`),onDelete:Y,isPinned:r(W.id),onTogglePin:()=>a({id:W.id,name:W.name,type:"team"}),onPause:()=>Ce(W),onResume:ke},W.id)})})}):i.jsx(is,{icon:vr,title:"No teams found",description:_e?"Try adjusting your search or filters":"Create your first team to get started",action:_e?void 0:i.jsx(de,{variant:"primary",icon:qn,onClick:()=>g(!0),children:"Create Team"}),className:"py-16"}),R&&i.jsxs(ni,{title:`Online devices (${F.length})`,summary:"Other machines on your account and their teams",className:"mt-8","data-testid":"online-devices",children:[i.jsx("div",{className:"mb-3 flex justify-end",children:i.jsx(Zt,{icon:$t,size:"xs",onClick:$,title:"Refresh devices","aria-label":"Refresh devices"})}),q?i.jsx(zt,{size:"sm",text:"Discovering devices..."}):F.length===0?i.jsx(is,{compact:!0,icon:Tm,title:"No other devices online",description:"Other Pro users will appear here when they are online"}):i.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:F.map(W=>i.jsxs(tn,{padding:"md",children:[i.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[i.jsx(NR,{status:"online",size:"sm",pulse:!0}),i.jsx("span",{className:"truncate text-sm font-semibold text-text",children:W.deviceName})]}),i.jsx("p",{className:"mb-3 truncate text-xs text-text-2",children:W.email}),W.teams.length>0&&i.jsx("ul",{className:"space-y-1 text-[13px]",children:W.teams.map(ae=>i.jsxs("li",{className:"flex items-center justify-between gap-2",children:[i.jsx("span",{className:"truncate text-text",children:ae.name}),i.jsxs("span",{className:"shrink-0 text-text-2",children:[ae.memberCount," member",ae.memberCount!==1?"s":""]})]},ae.id))})]},W.deviceId))})]}),i.jsx(V$,{isOpen:m,onClose:()=>g(!1),onSubmit:Z}),y&&S&&i.jsx(OFe,{member:y,teamId:S,onClose:Ee}),i.jsx(B$,{isOpen:!!Q,teamName:(Q==null?void 0:Q.name)??"",issueRepo:Q==null?void 0:Q.issueRepo,busy:ie,onCancel:()=>Ce(null),onConfirm:he}),i.jsx(D,{})]})},ZFe={teams:"Teams",goals:"Goals"},QFe={teams:"Your crews and the goals they work toward",goals:"Company → team → project goals and their key results"},e4e=()=>{const[t,e]=uu(jO),[n,s]=Pc(),[r,a]=_.useState(!1),[o,l]=_.useState(!1),[c,d]=_.useState(0),[u,h]=_.useState(null),[f,p]=_.useState(null);_.useEffect(()=>{if(n.get("create")!=="true")return;t==="goals"?l(!0):a(!0);const g=new URLSearchParams(n);g.delete("create"),s(g,{replace:!0})},[n,s,t]);const x=_.useCallback(g=>h(g),[]),v=_.useCallback(g=>p(g),[]),m=t==="teams"?i.jsx(de,{variant:"primary",icon:qn,onClick:()=>a(!0),"data-testid":"teams-new",children:"New team"}):i.jsxs(i.Fragment,{children:[i.jsx(de,{variant:"primary",icon:qn,onClick:()=>l(!0),"data-testid":"missions-new",children:"New goal"}),i.jsx(Co,{icon:pa,label:"More goal actions",buttonClassName:"inline-flex h-10 w-10 items-center justify-center rounded-2xl border border-border-soft text-text-2 transition-colors hover:bg-surface-hover hover:text-text",items:[{label:"Refresh",onClick:()=>d(g=>g+1)}]})]});return i.jsxs("div",{className:"p-6 max-w-5xl mx-auto",children:[i.jsx(_r,{title:"Teams",subtitle:QFe[t],actions:m,tabs:i.jsx(Oc,{"aria-label":"Teams views",idPrefix:"teams",value:t,onChange:g=>e(g),tabs:jO.map(g=>({value:g,label:ZFe[g],count:g==="teams"?u:f?f.pending>0?f.pending:f.total:null,attention:g==="goals"&&((f==null?void 0:f.pending)??0)>0}))})}),i.jsxs("div",{role:"tabpanel",id:`teams-panel-${t}`,"aria-labelledby":`teams-tab-${t}`,"data-testid":`teams-panel-${t}`,children:[t==="teams"&&i.jsx(JFe,{createOpen:r,onCreateOpenChange:a,onCount:x}),t==="goals"&&i.jsx(SX,{createOpen:o,onCreateOpenChange:l,refreshKey:c,onCounts:v})]})]})},tj="connector",t4e=[{label:"Skills",value:"skill"},{label:"3D Models",value:"model"},{label:"Roles",value:"role"},{label:"MCP Tools",value:"mcp_tool"},{label:"Connectors",value:tj}],n4e=[{label:"Popular",value:"popular"},{label:"Highest Rated",value:"rating"},{label:"Newest",value:"newest"}],GX=5;function a6({view:t="browse",onPendingCount:e}={}){const{toasts:n,addToast:s,dismissToast:r}=AK();return i.jsxs(i.Fragment,{children:[t==="browse"?i.jsx(s4e,{addToast:s}):i.jsx(o4e,{addToast:s,onPendingCount:e}),i.jsx(TK,{toasts:n,onDismiss:r})]})}function s4e({addToast:t}){var A,M;const e=cs(),[n,s]=_.useState([]),[r,a]=_.useState(!0),[o,l]=_.useState(null),[c,d]=_.useState({}),[u,h]=_.useState(""),[f,p]=_.useState(null),x=((A=c.type)==null?void 0:A[0])??"all",v=((M=c.sort)==null?void 0:M[0])??"popular",m=_.useCallback(async()=>{try{a(!0),l(null);const N=await ZNe({type:x==="all"||x===tj?void 0:x,search:u||void 0,sort:v});s(N)}catch{l("Failed to load marketplace items")}finally{a(!1)}},[x,u,v]);_.useEffect(()=>{m()},[m]);const g=async(N,L,I,D)=>{p(N);try{const z=await L(N);t(z.message||`${I} ${N}`,z.success?"success":"error"),await m()}catch(z){t(z instanceof Error?z.message:D,"error")}p(null)},y=N=>g(N,wK,"Installed","Install failed"),b=N=>g(N,EK,"Uninstalled","Uninstall failed"),S=N=>g(N,eMe,"Updated","Update failed"),E=async()=>{try{await CK(),t("Registry refreshed","success"),await m()}catch{t("Failed to refresh registry","error")}},k=N=>e(`${Yt.marketplace}/${encodeURIComponent(N)}`),T=N=>RL.filter(L=>L.group===N).filter(L=>!u.trim()||`${L.name} ${L.description}`.toLowerCase().includes(u.trim().toLowerCase()));return i.jsxs("div",{className:"space-y-5","data-testid":"marketplace-browse",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx("label",{htmlFor:"marketplace-search",className:"sr-only",children:"Search marketplace"}),i.jsxs("div",{className:"relative min-w-0 flex-1 basis-56",children:[i.jsx(Tl,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-3","aria-hidden":"true"}),i.jsx("input",{id:"marketplace-search",type:"text",placeholder:"Search...",value:u,onChange:N=>h(N.target.value),className:"h-9 w-full rounded-2xl border border-border bg-surface pl-9 pr-3 text-sm text-text placeholder:text-text-3 focus:border-primary focus:outline-none"})]}),i.jsx(Zo,{value:c,onChange:d,groups:[{id:"type",label:"Type",single:!0,options:t4e},{id:"sort",label:"Sort",single:!0,options:n4e}]}),i.jsx(Zt,{icon:$t,variant:"outline",onClick:()=>void E(),"aria-label":"Refresh marketplace",title:"Refresh marketplace"})]}),x===tj?i.jsxs("div",{className:"space-y-6","data-testid":"marketplace-connectors",children:[i.jsxs("p",{className:"text-[13px] text-text-2",children:["Connectors are not installed — you authorise them against your own account, and can revoke them at any time. Manage them on"," ",i.jsx(hs,{to:Yt.connections,className:"font-semibold text-primary-text hover:underline",children:"Connections"}),"."]}),bK.map(N=>{const L=T(N.id);return L.length===0?null:i.jsxs("section",{"aria-label":N.title,className:"space-y-2",children:[i.jsx("h2",{className:"px-1 text-[15px] font-semibold text-text",children:N.title}),i.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-soft bg-surface",children:L.map(I=>i.jsx(Ts,{"data-testid":`marketplace-connector-${I.id}`,leading:i.jsx(lR,{className:"h-4 w-4 text-text-3","aria-hidden":"true"}),primary:I.name,meta:I.description,actions:[i.jsx(hs,{to:`${Yt.connections}?platform=${I.id}`,className:"inline-flex h-8 items-center rounded-2xl bg-primary-soft px-3 text-sm font-semibold text-primary-text transition-colors hover:bg-primary/20",children:"Connect →"},"connect")]},I.id))})]},N.id)})]}):r?i.jsx(zt,{size:"md",text:"Loading marketplace...",className:"py-16"}):o?i.jsx(Ye,{variant:"error",children:o}):n.length===0?i.jsx(is,{icon:oR,title:"No items found."}):i.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-soft bg-surface",children:i.jsx(fs,{limit:GX,children:n.map(N=>i.jsx(r4e,{item:N,busy:f===N.id,onOpen:()=>k(N.id),onInstall:()=>void y(N.id),onUninstall:()=>void b(N.id),onUpdate:()=>void S(N.id)},N.id))})})]})}function r4e({item:t,busy:e,onOpen:n,onInstall:s,onUninstall:r,onUpdate:a}){const o=[{label:"View details",icon:YH,onClick:n}];let l,c=null;return t.installStatus==="not_installed"?l=[i.jsx(de,{variant:"primary",size:"sm",icon:oR,onClick:s,loading:e,children:e?"Installing...":"Install"},"install")]:t.installStatus==="installed"?(c=i.jsx(sn,{tone:"success",size:"sm",children:"Installed"}),l=[i.jsx(de,{variant:"outline",size:"sm",onClick:r,loading:e,children:e?"Removing...":"Uninstall"},"uninstall")]):t.installStatus==="update_available"&&(c=i.jsx(sn,{tone:"attention",size:"sm",children:"Update available"}),l=[i.jsx(de,{variant:"primary",size:"sm",icon:U1,onClick:a,loading:e,children:e?"Updating...":"Update"},"update"),i.jsx(de,{variant:"outline",size:"sm",onClick:r,disabled:e,children:"Remove"},"remove")]),i.jsx(Ts,{"data-testid":`marketplace-item-${t.id}`,primary:t.name,meta:i.jsxs(i.Fragment,{children:[i.jsx("span",{children:NK[t.type]??t.type}),i.jsx("span",{"aria-hidden":"true",children:" · "}),i.jsxs("span",{children:["by ",t.author]}),t.description&&i.jsxs(i.Fragment,{children:[i.jsx("span",{"aria-hidden":"true",children:" · "}),i.jsx("span",{title:t.description,children:t.description})]})]}),onClick:n,trailing:c,actions:l,overflow:o,overflowLabel:`More actions for ${t.name}`})}const i4e={pending:"attention",approved:"success",rejected:"danger"},a4e={pending:"Pending review",approved:"Approved",rejected:"Rejected"};function o4e({addToast:t,onPendingCount:e}){const[n,s]=_.useState([]),[r,a]=_.useState(!0),[o,l]=_.useState(null),[c,d]=_.useState(null),[u,h]=_.useState(null),f=_.useCallback(async()=>{try{a(!0),l(null);const x=await kK();s(x),e==null||e(x.filter(v=>v.status==="pending").length)}catch{l("Failed to load submissions")}finally{a(!1)}},[e]);_.useEffect(()=>{f()},[f]);const p=async(x,v)=>{d(x);try{const m=await tMe(x,v);t(m.message||`${v==="approve"?"Approved":"Rejected"}`,m.success?"success":"error"),await f(),v==="approve"&&await CK()}catch(m){t(m instanceof Error?m.message:"Review failed","error")}d(null)};return i.jsxs("div",{className:"space-y-5","data-testid":"marketplace-submissions",children:[i.jsxs("p",{className:"text-[13px] text-text-2",children:["Submit skills via CLI:"," ",i.jsx("code",{className:"rounded bg-surface-2 px-2 py-0.5 font-mono text-xs text-text",children:"crewly publish path/to/skill --submit"})]}),r?i.jsx(zt,{size:"md",text:"Loading submissions...",className:"py-16"}):o?i.jsx(Ye,{variant:"error",children:o}):n.length===0?i.jsx(is,{icon:lG,title:"No submissions yet."}):i.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-soft bg-surface",children:i.jsx(fs,{limit:GX,children:n.map(x=>{const v=c===x.id,m=u===x.id;return i.jsxs("div",{className:"border-b border-border-soft last:border-b-0","data-testid":`submission-${x.id}`,children:[i.jsx(Ts,{className:"border-b-0",primary:x.name,meta:`by ${x.author} · ${x.category} · ${uw(x.submittedAt)||new Date(x.submittedAt).toLocaleDateString()}`,onClick:()=>h(m?null:x.id),selected:m,trailing:i.jsx(sn,{tone:i4e[x.status]??"danger",size:"sm",children:a4e[x.status]??x.status}),actions:x.status==="pending"?[i.jsx(de,{variant:"success",size:"sm",onClick:()=>void p(x.id,"approve"),loading:v,children:v?"...":"Approve"},"approve"),i.jsx(de,{variant:"outline",size:"sm",onClick:()=>void p(x.id,"reject"),disabled:v,children:"Reject"},"reject")]:void 0}),m&&i.jsxs("div",{className:"space-y-2 px-4 pb-4 text-sm","data-testid":`submission-detail-${x.id}`,children:[i.jsx("p",{className:"text-text-2",children:x.description}),i.jsxs("p",{className:"text-[13px] text-text-3",children:["Version ",x.version," · submitted ",new Date(x.submittedAt).toLocaleString()]}),x.reviewNotes&&i.jsxs("p",{className:"text-[13px] italic text-text-2",children:["Review: ",x.reviewNotes]})]})]},x.id)})})})]})}const $X=[{value:"",label:"All Categories"},...Qde.map(t=>({value:t,label:H$(t)}))],l4e=5,c4e=({skill:t,onSave:e,onClose:n})=>{const s=(t==null?void 0:t.isBuiltin)??!1,[r,a]=_.useState({name:(t==null?void 0:t.name)||"",displayName:(t==null?void 0:t.name)||"",description:(t==null?void 0:t.description)||"",category:(t==null?void 0:t.category)||"development",promptContent:(t==null?void 0:t.promptContent)||"",triggers:[],tags:[]}),[o,l]=_.useState(!1),[c,d]=_.useState(null),u=async f=>{if(f.preventDefault(),d(null),!r.displayName.trim()){d("Display Name is required");return}if(!r.name.trim()){d("ID is required");return}if(!r.description.trim()){d("Description is required");return}l(!0);try{await e(r)}catch(p){d(p instanceof Error?p.message:"Failed to save skill")}finally{l(!1)}},h=i.jsxs(i.Fragment,{children:[i.jsx(de,{variant:"secondary",onClick:n,type:"button",children:"Cancel"}),i.jsx(de,{type:"submit",onClick:u,disabled:o,loading:o,children:o?"Saving...":"Save Skill"})]});return i.jsx(Xi,{isOpen:!0,onClose:n,title:t?"Edit Skill":"Create Skill",subtitle:t?"Modify skill configuration":"Configure a new skill for your agents",size:"lg",footer:h,children:i.jsxs("div",{className:"-m-6 max-h-[65vh] overflow-y-auto",children:[s&&t&&i.jsxs(Ye,{variant:"info",className:"mx-6 mt-4",children:[i.jsx("strong",{children:"Built-in Skill:"})," Changes will be saved as a user override. You can reset to defaults anytime."]}),c&&i.jsx("div",{className:"mx-6 mt-4",children:i.jsx(Ye,{variant:"error",children:c})}),i.jsxs("form",{onSubmit:u,className:"p-6 space-y-4",children:[i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-display-name",required:!0,children:"Display Name"}),i.jsx(Dt,{id:"skill-display-name",type:"text",value:r.displayName,onChange:f=>a({...r,displayName:f.target.value}),placeholder:"Code Review",required:!0})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-name",required:!0,children:"ID"}),i.jsx(Dt,{id:"skill-name",type:"text",value:r.name,onChange:f=>a({...r,name:f.target.value}),placeholder:"code-review",required:!0,disabled:!!t}),i.jsx("p",{className:"text-xs text-text-2 mt-1",children:"Lowercase letters, numbers, and hyphens only"})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-description",required:!0,children:"Description"}),i.jsx(er,{id:"skill-description",value:r.description,onChange:f=>a({...r,description:f.target.value}),placeholder:"Describe what this skill does...",rows:3,required:!0})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-category",children:"Category"}),i.jsx(xn,{id:"skill-category",value:r.category,onChange:f=>a({...r,category:f.target.value}),children:$X.filter(f=>f.value).map(f=>i.jsx("option",{value:f.value,children:f.label},f.value))})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-prompt",children:"Instructions (Markdown)"}),i.jsx(er,{id:"skill-prompt",value:r.promptContent,onChange:f=>a({...r,promptContent:f.target.value}),placeholder:`# Skill Instructions
4952
+ `).map(n=>n.trim()).filter(Boolean),parentMissionId:t.parentMissionId||""};return t.periodType&&t.periodStart&&t.periodEnd?e.period={type:t.periodType,startDate:new Date(t.periodStart).toISOString(),endDate:new Date(t.periodEnd).toISOString(),...t.periodLabel?{label:t.periodLabel}:{}}:!t.periodType&&!t.periodStart&&!t.periodEnd&&(e.period=null),e}const EX=()=>{var re,ne,J,H,X;const{id:t}=Lc(),e=cs(),[n,s]=_.useState(null),[r,a]=_.useState(!0),[o,l]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[f,p]=_.useState(null),[x,v]=_.useState(!1),[m,g]=_.useState(null),[y,b]=_.useState(new Map),[S,E]=_.useState(new Map),[k,T]=_.useState(new Map),[A,M]=_.useState(0),N=_.useCallback(async(Z=!0)=>{if(t){Z?a(!0):d(!0),l(null);try{const oe=await lt.getMission(t);s(oe)}catch(oe){const ye=oe instanceof Error?oe.message:"Failed to load goal";l(ye)}finally{a(!1),d(!1)}}},[t]);_.useEffect(()=>{N()},[N]),_.useEffect(()=>{let Z=!1;return(async()=>{try{const oe=await lt.getMissions();if(Z)return;b(new Map(oe.map(ye=>[ye.id,ye.objective]))),E(new Map(oe.map(ye=>[ye.id,{level:ye.level,parentMissionId:ye.parentMissionId}])))}catch{}})(),()=>{Z=!0}},[t]),_.useEffect(()=>{let Z=!1;return(async()=>{try{const oe=await lt.getTeams();!Z&&Array.isArray(oe)&&T(new Map(oe.map(ye=>[ye.id,ye.name])))}catch{}})(),()=>{Z=!0}},[]);const L=_.useCallback(()=>{M(Z=>Z+1),N(!1)},[N]),I=_.useCallback(Z=>{s(oe=>oe&&oe.id===Z.id?{...oe,...Z}:oe),L()},[L]),D=_.useCallback(()=>{n&&(p(DBe(n)),g(null),h(!0))},[n]),z=_.useCallback(()=>{h(!1),p(null),g(null)},[]),U=_.useCallback(async()=>{if(!(!t||!f)){if(!f.objective.trim()){g("Objective cannot be empty.");return}if(!f.ownerTeamId.trim()){g("Owner team cannot be empty.");return}v(!0),g(null);try{const Z=await lt.updateMission(t,OBe(f));s(Z),h(!1),p(null)}catch(Z){const oe=Z instanceof Error?Z.message:"Failed to save goal";g(oe)}finally{v(!1)}}},[t,f]),G=_.useMemo(()=>(Z,oe)=>{p(ye=>ye&&{...ye,[Z]:oe})},[]);if(r)return i.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:i.jsx(zt,{size:"xl",text:"Loading goal..."})});if(o)return i.jsxs("div",{className:"p-6 max-w-[1000px] mx-auto","data-testid":"mission-detail-error",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:Fa,onClick:()=>e(qt.goals()),className:"mb-6",children:"Back to Goals"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsxs("div",{className:"flex flex-col items-center text-center py-8",children:[i.jsx("p",{className:"text-red-400 mb-2",children:o}),i.jsx(de,{variant:"secondary",size:"sm",icon:$t,onClick:()=>N(),children:"Retry"})]})})]});if(!n)return i.jsxs("div",{className:"p-6 max-w-[1000px] mx-auto",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:Fa,onClick:()=>e(qt.goals()),className:"mb-6",children:"Back to Goals"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsx(is,{icon:ay,title:"Goal not found.",compact:!0})})]});const K=lI(n,S),P=(re=n.approval)==null?void 0:re.state,B=bX(n),R=vX(n.ownerTeamId,k),F=u&&!!f,q=(Z,oe,ye)=>i.jsxs("div",{className:"flex items-baseline justify-between gap-4 border-t border-border-soft py-2 text-sm first:border-t-0","data-testid":ye,children:[i.jsx("dt",{className:"shrink-0 text-text-2",children:Z}),i.jsx("dd",{className:"min-w-0 text-right text-text",children:oe})]}),$="mb-2 text-[13px] font-semibold text-text-2";return i.jsxs("div",{className:"p-6 max-w-5xl mx-auto","data-testid":"mission-detail-page",children:[i.jsx(_r,{eyebrow:i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:Yt.teams,className:"text-text-2 hover:text-text",children:"Teams"}),i.jsx(cr,{className:"h-3.5 w-3.5 text-text-3","aria-hidden":"true"}),i.jsx(hs,{to:qt.goals(),className:"text-text-2 hover:text-text","data-testid":"mission-detail-back",children:"Goals"})]}),title:F?"Edit goal":n.objective,subtitle:i.jsxs("span",{className:"inline-flex flex-wrap items-center gap-x-1.5",children:[i.jsx("span",{"data-testid":`level-badge-${K}`,children:dc[K]}),i.jsx("span",{className:"text-text-3",children:"·"}),i.jsx(sn,{tone:B.tone,children:B.label}),n.priority&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-3",children:"·"}),i.jsxs("span",{children:[QM[n.priority]," priority"]})]}),((ne=n.period)==null?void 0:ne.label)&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-3",children:"·"}),i.jsx("span",{children:n.period.label})]}),i.jsx("span",{className:"text-text-3",children:"·"}),i.jsx("span",{title:k.has(n.ownerTeamId)?void 0:`Team id ${n.ownerTeamId}`,children:R})]}),actions:F?i.jsxs(i.Fragment,{children:[i.jsx(de,{variant:"primary",size:"sm",icon:Xd,onClick:U,disabled:x,"data-testid":"mission-save",children:x?"Saving…":"Save"}),i.jsx(de,{variant:"ghost",size:"sm",icon:ys,onClick:z,disabled:x,"data-testid":"mission-cancel",children:"Cancel"})]}):i.jsxs(i.Fragment,{children:[i.jsx(de,{variant:"primary",size:"sm",icon:Lh,onClick:D,"data-testid":"mission-edit",children:"Edit"}),i.jsx(Co,{icon:pa,label:"More goal actions",buttonClassName:"inline-flex h-9 w-9 items-center justify-center rounded-2xl border border-border-soft text-text-2 transition-colors hover:bg-surface-hover hover:text-text",items:[{label:c?"Refreshing…":"Refresh",icon:$t,onClick:()=>N(!1),disabled:c}]})]})}),P&&P!=="pending_approval"&&((J=n.approval)==null?void 0:J.decidedAt)&&!F&&i.jsx("div",{className:"mb-4",children:i.jsx(s2,{state:P})}),P==="pending_approval"&&!F&&i.jsxs("div",{className:"mb-6 flex flex-wrap items-center gap-3","data-testid":"mission-pending-banner",children:[i.jsx(s2,{state:P}),i.jsxs("span",{className:"text-[13px] text-attention",children:["Proposed",(H=n.approval)!=null&&H.proposedBy?` by ${n.approval.proposedBy}`:"",". Waiting for your decision."]}),i.jsx(iP,{missionId:n.id,onDecided:I})]}),P==="rejected"&&((X=n.approval)==null?void 0:X.rejectionReason)&&i.jsxs("p",{className:"mb-4 text-[13px] text-danger","data-testid":"mission-rejection-reason",children:["Rejected: ",n.approval.rejectionReason]}),m&&i.jsx("div",{"data-testid":"mission-save-error",className:"mb-4",children:i.jsx(Ye,{variant:"error",onClose:()=>g(null),children:m})}),F&&f?i.jsxs("div",{className:"flex flex-col gap-4 rounded-2xl border border-border-soft p-5","data-testid":"mission-edit-form",children:[i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Objective",i.jsx(ss,{"aria-label":"Objective",value:f.objective,onChange:Z=>G("objective",Z.target.value),fullWidth:!0,"data-testid":"edit-objective"})]}),i.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Status",i.jsxs(xn,{value:f.status,onChange:Z=>G("status",Z.target.value),"data-testid":"edit-status",children:[i.jsx("option",{value:"active",children:"Active"}),i.jsx("option",{value:"paused",children:"Paused"}),i.jsx("option",{value:"completed",children:"Completed"}),i.jsx("option",{value:"cancelled",children:"Cancelled"})]})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Priority",i.jsxs(xn,{value:f.priority,onChange:Z=>G("priority",Z.target.value),"data-testid":"edit-priority",children:[i.jsx("option",{value:"critical",children:"Critical"}),i.jsx("option",{value:"high",children:"High"}),i.jsx("option",{value:"medium",children:"Medium"}),i.jsx("option",{value:"low",children:"Low"})]})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Owner team",i.jsx(ss,{"aria-label":"Owner Team",value:f.ownerTeamId,onChange:Z=>G("ownerTeamId",Z.target.value),fullWidth:!0,"data-testid":"edit-owner-team"})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Parent goal",i.jsx(ss,{"aria-label":"Parent Mission ID",placeholder:"(none)",value:f.parentMissionId,onChange:Z=>G("parentMissionId",Z.target.value),fullWidth:!0,"data-testid":"edit-parent"})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Review cadence (cron)",i.jsx(ss,{"aria-label":"Cadence",value:f.cadence,onChange:Z=>G("cadence",Z.target.value),fullWidth:!0,"data-testid":"edit-cadence"})]})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Current strategy",i.jsx(er,{"aria-label":"Current Strategy",rows:4,value:f.currentStrategy,onChange:Z=>G("currentStrategy",Z.target.value),"data-testid":"edit-strategy"})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Success criteria (one per line)",i.jsx(er,{"aria-label":"Success Criteria (one per line)",rows:5,placeholder:"One criterion per line",value:f.successCriteriaText,onChange:Z=>G("successCriteriaText",Z.target.value),"data-testid":"edit-success-criteria"})]}),i.jsxs("fieldset",{className:"flex flex-col gap-2",children:[i.jsx("legend",{className:"mb-1 text-sm text-text-2",children:"OKR period"}),i.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-4",children:[i.jsxs(xn,{value:f.periodType,onChange:Z=>G("periodType",Z.target.value),"data-testid":"edit-period-type",children:[i.jsx("option",{value:"",children:"— No period —"}),i.jsx("option",{value:"weekly",children:"Weekly"}),i.jsx("option",{value:"biweekly",children:"Biweekly"}),i.jsx("option",{value:"monthly",children:"Monthly"}),i.jsx("option",{value:"quarterly",children:"Quarterly"}),i.jsx("option",{value:"custom",children:"Custom"})]}),i.jsx(ss,{type:"date","aria-label":"Period start",value:f.periodStart,onChange:Z=>G("periodStart",Z.target.value),fullWidth:!0,"data-testid":"edit-period-start"}),i.jsx(ss,{type:"date","aria-label":"Period end",value:f.periodEnd,onChange:Z=>G("periodEnd",Z.target.value),fullWidth:!0,"data-testid":"edit-period-end"}),i.jsx(ss,{"aria-label":"Period label",placeholder:"Label (optional)",value:f.periodLabel,onChange:Z=>G("periodLabel",Z.target.value),fullWidth:!0,"data-testid":"edit-period-label"})]})]})]}):i.jsxs("div",{className:"flex flex-col gap-8",children:[i.jsx(MBe,{missionId:n.id,onChanged:L}),i.jsx(IBe,{parentMissionId:n.id,onDecided:I}),i.jsxs("section",{"aria-labelledby":"goal-strategy-h",children:[i.jsx("h2",{id:"goal-strategy-h",className:$,children:"Current strategy"}),i.jsx("p",{className:"whitespace-pre-wrap text-[15px] leading-relaxed text-text",children:n.currentStrategy||"No strategy defined."})]}),i.jsx(ni,{title:"More",summary:"Success criteria, cascade, learnings, progress, settings, period, timestamps","data-testid":"goal-more",children:i.jsxs("div",{className:"grid grid-cols-1 gap-8 lg:grid-cols-3",children:[i.jsxs("div",{className:"flex flex-col gap-8 lg:col-span-2",children:[i.jsxs("section",{"aria-labelledby":"goal-criteria-h",children:[i.jsxs("h2",{id:"goal-criteria-h",className:$,children:["Success criteria (",n.successCriteria.length,")"]}),n.successCriteria.length===0?i.jsx("p",{className:"text-sm text-text-2",children:"No success criteria defined."}):i.jsx("ul",{className:"space-y-2",children:n.successCriteria.map((Z,oe)=>i.jsxs("li",{className:"flex items-start gap-2 text-sm text-text",children:[i.jsx(WH,{className:"mt-0.5 h-4 w-4 shrink-0 text-text-3","aria-hidden":"true"}),Z]},oe))})]}),i.jsx(RBe,{missionId:n.id,level:K,parentMissionId:n.parentMissionId,missionNames:y,refreshKey:A}),n.learnings&&n.learnings.length>0&&i.jsxs("section",{"aria-labelledby":"goal-learnings-h",children:[i.jsxs("h2",{id:"goal-learnings-h",className:$,children:["Learnings (",n.learnings.length,")"]}),i.jsx(fs,{as:"ul",limit:6,className:"space-y-2","data-testid":"goal-learnings",children:n.learnings.map((Z,oe)=>i.jsx("li",{className:"border-l-2 border-border-soft pl-4 text-sm text-text",children:Z},oe))})]})]}),i.jsxs("div",{className:"flex flex-col gap-8",children:[i.jsx(PBe,{missionId:n.id,refreshKey:A}),i.jsxs("section",{"aria-labelledby":"goal-settings-h",children:[i.jsx("h2",{id:"goal-settings-h",className:$,children:"Team & settings"}),i.jsxs("dl",{children:[q("Owner team",i.jsx("span",{title:n.ownerTeamId,children:R})),q("Status",hE(n.status)),q("Priority",QM[n.priority??"medium"]),q("Parent goal",n.parentMissionId?i.jsx(de,{type:"button",variant:"link",size:"xs",onClick:()=>e(qt.goal(n.parentMissionId)),className:"max-w-full truncate","data-testid":"mission-parent-link",children:y.get(n.parentMissionId)??n.parentMissionId}):"—"),q("Level",i.jsx("span",{"data-testid":"mission-level",children:K})),n.projectId&&q("Project",i.jsx(de,{type:"button",variant:"link",size:"xs",onClick:()=>e(qt.project(n.projectId)),"data-testid":"mission-project-link",children:"Open project"})),q("Active tasks",n.activeProjectTaskIds.length),q("Review cadence",i.jsx("span",{className:"font-mono text-xs",children:n.cadence||"N/A"})),q("Reference",i.jsx("span",{className:"font-mono text-xs",children:n.id.slice(0,12)}))]})]}),i.jsxs("section",{"aria-labelledby":"goal-period-h",children:[i.jsx("h2",{id:"goal-period-h",className:$,children:"OKR period"}),n.period?i.jsxs("dl",{children:[q("Type",n.period.type),q("Start",ep(n.period.startDate)),q("End",ep(n.period.endDate)),n.period.label&&q("Label",n.period.label)]}):i.jsx("p",{className:"text-sm text-text-2",children:"No period defined."})]}),i.jsxs("section",{"aria-labelledby":"goal-times-h",children:[i.jsx("h2",{id:"goal-times-h",className:$,children:"Timestamps"}),i.jsxs("dl",{children:[q("Created",ep(n.createdAt)),q("Updated",i.jsx("span",{title:ep(n.updatedAt),children:Ml(n.updatedAt)})),n.lastReviewAt&&q("Last review",ep(n.lastReviewAt)),n.nextReviewAt&&q("Next review",ep(n.nextReviewAt))]})]}),n.activeProjectTaskIds.length>0&&i.jsxs("section",{"aria-labelledby":"goal-task-ids-h",children:[i.jsx("h2",{id:"goal-task-ids-h",className:$,children:"Active task ids"}),i.jsx("p",{className:"flex flex-wrap gap-x-3 gap-y-1 font-mono text-xs text-text-2",children:n.activeProjectTaskIds.map(Z=>i.jsx("span",{title:Z,children:Z.slice(0,12)},Z))})]})]})]})})]})]})};EX.displayName="MissionDetail";function aP(t){return{queued:"Queued",scheduled:"Scheduled",running:"Running",blocked:"Blocked",done:"Completed",failed:"Failed",cancelled:"Cancelled"}[t]??t}function oP(t){return{delegate:"Delegate",project_task:"Project Task",check:"Check",notify:"Notify",cron_run:"Cron Run",review:"Review",confirm:"Confirm",reconcile:"Reconcile",ticket_triage:"Ticket triage",autopilot_retro:"Autopilot retro",goal_replan:"Goal replan",autopilot_self_review:"Autopilot self-review"}[t]??t}function Q2(t){return{orchestrator:"Orchestrator",team_lead:"Team Lead",agent:"Agent",system:"System"}[t]??t}function oC(t){const e=Date.now(),n=new Date(t).getTime(),s=e-n,r=Math.floor(s/6e4),a=Math.floor(r/60),o=Math.floor(a/24);return r<1?"just now":r<60?`${r}m ago`:a<24?`${a}h ago`:`${o}d ago`}function Ax(t){const e=new Date(t);return isNaN(e.getTime())?t:e.toLocaleString("en-US",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0})}function CX(t){return t===0?"—":t<.01?`$${t.toFixed(4)}`:`$${t.toFixed(2)}`}function Qx(t){return t===0?"—":t<1e3?t.toString():t<1e6?`${(t/1e3).toFixed(1)}K`:`${(t/1e6).toFixed(1)}M`}function kX(t){const e=[];if(e.push({id:`${t.id}-created`,kind:"status_change",label:"QUEUED",detail:"WorkItem created and added to pool.",timestamp:t.createdAt,status:"queued"}),t.startedAt&&e.push({id:`${t.id}-started`,kind:"status_change",label:"RUNNING",detail:t.target?`Claimed by agent: ${t.target}`:"Execution started.",timestamp:t.startedAt,status:"running"}),t.error){const n=t.completedAt||t.startedAt||t.createdAt;e.push({id:`${t.id}-error`,kind:"error",label:"ERROR",detail:t.error,timestamp:n,status:"failed"})}if(t.completedAt&&t.status==="done"&&e.push({id:`${t.id}-done`,kind:"status_change",label:"COMPLETED",detail:"Execution completed successfully.",timestamp:t.completedAt,status:"done"}),t.completedAt&&t.status==="failed"&&e.push({id:`${t.id}-failed`,kind:"status_change",label:"FAILED",detail:`Execution failed after ${t.retryCount}/${t.maxRetries} retries.`,timestamp:t.completedAt,status:"failed"}),t.status==="cancelled"){const n=t.completedAt||t.createdAt,s=t.cancelReason,r=typeof s=="string"&&s.length>0?`Cancelled: ${s}`:"Cancelled (no reason recorded).";e.push({id:`${t.id}-cancelled`,kind:"status_change",label:"CANCELLED",detail:r,timestamp:n,status:"cancelled"})}if(t.status==="blocked"){const n=t.blockedReason,s=typeof n=="string"&&n.length>0?`Blocked: ${n}`:"Blocked (no reason recorded).";e.push({id:`${t.id}-blocked`,kind:"status_change",label:"BLOCKED",detail:s,timestamp:t.startedAt||t.createdAt,status:"blocked"})}if(t.result&&Object.keys(t.result).length>0){const n=t.completedAt||t.startedAt||t.createdAt;e.push({id:`${t.id}-result`,kind:"progress_update",label:"RESULT DATA",detail:JSON.stringify(t.result,null,2),timestamp:n})}return e.sort((n,s)=>new Date(s.timestamp).getTime()-new Date(n.timestamp).getTime())}function BBe(t,e){if(t==="error")return Yd;if(t==="progress_update")return DH;if(t==="agent_reasoning"||t==="tool_action")return Ia;switch(e){case"queued":return jr;case"running":return Ia;case"done":return Ua;case"failed":return Yd;case"cancelled":return dee;case"blocked":return Kd;default:return jr}}function FBe(t,e){if(t==="error")return"text-red-400";if(t==="progress_update")return"text-blue-400";switch(e){case"queued":return"text-text-secondary-dark";case"running":return"text-green-400";case"done":return"text-blue-400";case"failed":return"text-red-400";case"cancelled":return"text-text-secondary-dark";case"blocked":return"text-yellow-400";default:return"text-text-secondary-dark"}}function UBe(t,e){return t==="error"?"border-red-500/30":e==="done"?"border-blue-500/30":e==="running"?"border-green-500/30":"border-border-dark"}const lP=({events:t})=>t.length===0?i.jsx("div",{className:"flex items-center justify-center py-8 text-text-secondary-dark text-sm","data-testid":"timeline-empty",children:"No activity recorded yet."}):i.jsx("div",{className:"relative","data-testid":"workitem-timeline",children:t.map((e,n)=>{const s=BBe(e.kind,e.status),r=FBe(e.kind,e.status),a=UBe(e.kind,e.status),o=n===t.length-1;return i.jsxs("div",{className:"relative flex gap-4 pb-6","data-testid":`timeline-event-${e.id}`,children:[!o&&i.jsx("div",{className:`absolute left-[15px] top-8 bottom-0 w-px border-l ${a}`}),i.jsx("div",{className:"relative z-10 flex-shrink-0 mt-0.5",children:i.jsx("div",{className:`p-1 rounded-full bg-surface-dark ${r}`,children:i.jsx(s,{className:"h-5 w-5"})})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx("span",{className:`text-sm font-semibold ${r}`,children:e.label}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:Ax(e.timestamp)})]}),e.detail&&i.jsx("div",{className:`mt-1 text-sm ${e.kind==="error"?"bg-red-500/10 border border-red-500/20 rounded-md p-2 text-red-300":e.kind==="progress_update"?"bg-surface-dark border border-border-dark rounded-md p-2 text-text-secondary-dark font-mono text-xs whitespace-pre-wrap overflow-x-auto max-h-40 overflow-y-auto":"text-text-secondary-dark"}`,children:e.detail})]})]},e.id)})});lP.displayName="WorkItemTimeline";const io=({icon:t,label:e,value:n,valueClass:s="text-text-primary-dark"})=>i.jsxs("div",{className:"flex items-center justify-between py-2",children:[i.jsxs("div",{className:"flex items-center gap-2 text-text-secondary-dark",children:[i.jsx(t,{className:"h-4 w-4"}),i.jsx("span",{className:"text-sm",children:e})]}),i.jsx("span",{className:`text-sm font-medium ${s}`,children:n})]}),AX=({item:t})=>{const e=zBe(t);return i.jsxs("div",{className:"space-y-4","data-testid":"workitem-metrics",children:[i.jsxs(tn,{variant:"default",padding:"md",children:[i.jsx("h3",{className:"text-xs font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:"Token Usage"}),i.jsxs("div",{className:"divide-y divide-border-dark",children:[i.jsx(io,{icon:_0,label:"Input Tokens",value:Qx(t.inputTokens)}),i.jsx(io,{icon:_0,label:"Output Tokens",value:Qx(t.outputTokens)}),i.jsx(io,{icon:rR,label:"Cost",value:CX(t.cost),valueClass:t.cost>0?"text-yellow-400":"text-text-primary-dark"})]})]}),i.jsxs(tn,{variant:"default",padding:"md",children:[i.jsx("h3",{className:"text-xs font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:"Execution"}),i.jsxs("div",{className:"divide-y divide-border-dark",children:[i.jsx(io,{icon:$t,label:"Retries",value:`${t.retryCount} / ${t.maxRetries}`}),i.jsx(io,{icon:jr,label:"Duration",value:e}),i.jsx(io,{icon:oy,label:"Owner",value:Q2(t.owner)}),t.target&&i.jsx(io,{icon:ay,label:"Agent",value:t.target})]})]}),(t.requestId||t.missionId||t.projectTaskId||t.triggerId)&&i.jsxs(tn,{variant:"default",padding:"md",children:[i.jsx("h3",{className:"text-xs font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:"Linked References"}),i.jsxs("div",{className:"divide-y divide-border-dark",children:[t.requestId&&i.jsx(io,{icon:tp,label:"Request",value:dx(t.requestId)}),t.missionId&&i.jsx(io,{icon:tp,label:"Mission",value:dx(t.missionId)}),t.projectTaskId&&i.jsx(io,{icon:tp,label:"Project Task",value:dx(t.projectTaskId)}),t.triggerId&&i.jsx(io,{icon:tp,label:"Trigger",value:dx(t.triggerId)}),t.parentWorkItemId&&i.jsx(io,{icon:tp,label:"Parent Item",value:dx(t.parentWorkItemId)})]})]}),i.jsxs(tn,{variant:"default",padding:"md",children:[i.jsx("h3",{className:"text-xs font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:"Timestamps"}),i.jsxs("div",{className:"space-y-2 text-sm",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Created"}),i.jsx("span",{className:"text-text-primary-dark",children:Ax(t.createdAt)})]}),t.startedAt&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Started"}),i.jsx("span",{className:"text-text-primary-dark",children:Ax(t.startedAt)})]}),t.completedAt&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Completed"}),i.jsx("span",{className:"text-text-primary-dark",children:Ax(t.completedAt)})]}),t.scheduledAt&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Scheduled"}),i.jsx("span",{className:"text-text-primary-dark",children:Ax(t.scheduledAt)})]})]})]})]})};AX.displayName="WorkItemMetrics";function zBe(t){const e=t.startedAt?new Date(t.startedAt).getTime():null,n=t.completedAt?new Date(t.completedAt).getTime():t.startedAt?Date.now():null;if(!e||!n)return"--";const s=n-e,r=Math.floor(s/1e3)%60,a=Math.floor(s/6e4)%60,o=Math.floor(s/36e5);return o>0?`${o}h ${a}m`:a>0?`${a}m ${r}s`:`${r}s`}function dx(t){return t.length<=12?t:`${t.slice(0,8)}...`}let M_=null;function HBe(){return M_||(M_=Promise.resolve().then(()=>x$()).then(t=>Wce(t.flatMap(e=>e.tickets.map(n=>n.id)))).catch(t=>{throw M_=null,t})),M_}function TX(){const[t,e]=_.useState(()=>new Set);return _.useEffect(()=>{let n=!0;return HBe().then(s=>{n&&e(s)}).catch(()=>{}),()=>{n=!1}},[]),t}const NX=()=>{const{id:t}=Lc(),e=cs(),{names:n}=Bm(),s=TX(),[r,a]=_.useState(null),[o,l]=_.useState(!0),[c,d]=_.useState(null),[u,h]=_.useState(!1),f=_.useCallback(async(y=!0)=>{if(t){y?l(!0):h(!0),d(null);try{const b=await lt.getWorkItem(t);a(b)}catch(b){const S=b instanceof Error?b.message:"Failed to load run";d(S)}finally{l(!1),h(!1)}}},[t]);_.useEffect(()=>{f(!0)},[f]),_.useEffect(()=>{if(!r||r.status!=="running")return;const y=setInterval(()=>{f(!1)},1e4);return()=>clearInterval(y)},[r==null?void 0:r.status,f]);const p=()=>{e(qt.runs())},x=()=>{f(!1)};if(o)return i.jsx("div",{className:"flex items-center justify-center h-64","data-testid":"workitem-detail-loading",children:i.jsx(zt,{})});if(c)return i.jsxs("div",{className:"p-6","data-testid":"workitem-detail-error",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:Fa,onClick:p,className:"mb-6",children:"Back to Runs"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsxs("div",{className:"flex flex-col items-center text-center py-8",children:[i.jsx("p",{className:"text-danger text-lg font-medium mb-2",children:"Failed to load run"}),i.jsx("p",{className:"text-text-2 text-sm mb-4",children:c}),i.jsx(de,{variant:"secondary",size:"sm",icon:$t,onClick:()=>f(!0),children:"Retry"})]})})]});if(!r)return i.jsxs("div",{className:"p-6","data-testid":"workitem-detail-not-found",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:Fa,onClick:p,className:"mb-6",children:"Back to Runs"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsx(is,{icon:bee,title:"Run not found.",compact:!0})})]});const v=kX(r),m=Jd(r.target,n,!0),g=k$(r.title,s);return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-6","data-testid":"workitem-detail",children:[i.jsx(_r,{className:"mb-0",eyebrow:i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:qt.ticketsBoard(),className:"text-text-2 hover:text-text",children:"Tickets"}),i.jsx("span",{className:"text-text-3",children:"/"}),i.jsx(hs,{to:qt.runs(),className:"text-text-2 hover:text-text","data-testid":"workitem-detail-back",children:"Runs"})]}),title:r.title,subtitle:i.jsxs(i.Fragment,{children:[m?`${Q2(r.owner)} · ${m}`:Q2(r.owner),` · created ${oC(r.createdAt)} · `,i.jsxs("span",{className:"font-mono text-text-3",title:r.id,children:["run ",dN(r.id)]})]}),actions:i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:x,loading:u,"data-testid":"workitem-detail-refresh"}),"data-testid":"workitem-detail-header"}),i.jsxs("div",{className:"-mt-2 flex flex-wrap items-center gap-x-4 gap-y-2 text-[13px] text-text-2",children:[i.jsx(sn,{tone:GBe(r.status),children:aP(r.status)}),i.jsx("span",{children:oP(r.type)}),i.jsxs("span",{children:["Retry ",r.retryCount,"/",r.maxRetries]}),g&&i.jsx("span",{children:g}),r.requestId&&i.jsxs(hs,{to:qt.request(r.requestId),className:"font-semibold text-primary-text hover:underline",children:["Request ",dN(r.requestId)]}),r.missionId&&i.jsxs(hs,{to:qt.goal(r.missionId),className:"font-semibold text-primary-text hover:underline",children:["Goal ",dN(r.missionId)]})]}),r.description&&i.jsx("p",{className:"whitespace-pre-wrap text-sm leading-relaxed text-text-2",children:r.description}),i.jsxs("section",{"aria-labelledby":"workitem-timeline-heading",className:"rounded-2xl bg-surface p-4",children:[i.jsx("h2",{id:"workitem-timeline-heading",className:"mb-4 text-[15px] font-bold text-text",children:"Activity timeline"}),i.jsx(lP,{events:v})]}),i.jsx(ni,{title:"Details",summary:"Tokens, cost, retries, duration, links and timestamps",children:i.jsx(AX,{item:r})})]})};function GBe(t){return t==="cancelled"||t==="queued"||t==="scheduled"?"neutral":rE(t)}NX.displayName="WorkItemDetail";function dN(t){return t.length<=12?t:t.slice(0,8)}const ux=new Set(["open","waiting_owner","ready","overdue"]),$Be={open:{label:"Open",variant:"info"},waiting_owner:{label:"Waiting on you",variant:"warning"},ready:{label:"Ready to deliver",variant:"warning"},overdue:{label:"Overdue",variant:"error"},delivered:{label:"Delivered",variant:"success"},resolved:{label:"Answered",variant:"success"},superseded:{label:"Superseded",variant:"default"},expired:{label:"Expired",variant:"default"},cancelled:{label:"Cancelled",variant:"default"},skipped:{label:"Skipped",variant:"default"}};function Xz(t){if(!t)return"";const e=new Date(t);return Number.isNaN(e.getTime())?"":e.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}const WBe=({items:t,onSkip:e})=>{const[n,s]=an.useState(null),[r,a]=an.useState(null),o=async d=>{if(e){s(d),a(null);try{await e(d)}catch(u){a(u instanceof Error?u.message:String(u))}finally{s(null)}}},l=[...t].sort((d,u)=>Number(ux.has(u.status))-Number(ux.has(d.status))||Date.parse(u.createdAt)-Date.parse(d.createdAt)),c=l.filter(d=>ux.has(d.status)).length;return i.jsxs(tn,{variant:"default",padding:"md","data-testid":"request-open-items",children:[i.jsxs("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:["Open items ",c>0?`(${c} open)`:""]}),r&&i.jsx("p",{className:"text-xs text-red-400 mb-2",role:"alert",children:r}),i.jsx("ul",{className:"flex flex-col gap-3",children:l.map(d=>{const u=$Be[d.status]??{label:d.status,variant:"default"};return i.jsxs("li",{className:"flex flex-col gap-1","data-testid":"request-open-item",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx(mn,{variant:d.type==="commitment"?"info":"warning",size:"sm",children:d.type==="commitment"?"Promise":"Question"}),i.jsx(mn,{variant:u.variant,size:"sm",children:u.label}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:d.agent}),d.type==="commitment"&&d.due&&ux.has(d.status)&&i.jsxs("span",{className:"text-xs text-text-secondary-dark",children:["due ",Xz(d.due)]}),d.decisionId&&i.jsx("span",{className:"text-xs text-text-secondary-dark font-mono",children:d.decisionId}),e&&ux.has(d.status)&&i.jsx(de,{size:"sm",variant:"ghost",className:"ml-auto min-h-8",disabled:n===d.id,onClick:()=>void o(d.id),title:d.type==="commitment"?"Drop this promise and cancel its follow-up":"Skip this question — the agent won't ask again",children:"Skip"})]}),i.jsx("p",{className:"text-sm text-text-primary-dark break-words",children:d.text}),d.answer&&i.jsxs("p",{className:"text-xs text-text-secondary-dark",children:["Answer: ",d.answer]}),d.status==="ready"&&d.readyAt&&i.jsxs("p",{className:"text-xs text-amber-400",children:["The work was ready at ",Xz(d.readyAt),"; the agent was asked to deliver it."]})]},d.id)})})]})},VBe="/api/traces";class MX extends Error{constructor(e,n){super(e),this.status=n,this.name="TraceApiError"}}async function jX(t){const e=await fetch(`${VBe}${t}`);let n={};try{n=await e.json()}catch{n={}}if(!e.ok||n.success===!1)throw new MX(n.error||`HTTP ${e.status}`,e.status);return n.data}function KBe(t){return t?`?stallMinutes=${encodeURIComponent(String(t))}`:""}async function qBe(t,e){try{return await jX(`/by-ref?${t}=${encodeURIComponent(e)}`)}catch(n){if(n instanceof MX&&n.status===404)return null;throw n}}function XBe(t,e){return jX(`/${encodeURIComponent(t)}/timeline${KBe(e)}`)}function YBe(t){return t==="done"?"success":t==="failed"?"danger":t==="waiting_on_owner"?"attention":t==="in_progress"?"primary":"neutral"}function Yz(t,e){return e>0?`${Math.round(t/e*100)}% of the time`:void 0}function JBe(t){const e=t.time,n=t.stalls.items.some(a=>a.ongoing),s=t.ownerTouches,r=t.rework;return[{id:"wall",label:"Wall time",value:zi(e.wallMs)},{id:"active",label:"Agents working",value:zi(e.activeMs),hint:Yz(e.activeMs,e.wallMs),title:e.activeSource==="inferred"?"Estimated from agent activity":void 0},{id:"owner-wait",label:"Waiting on you",value:zi(e.waitingOwnerMs),hint:Yz(e.waitingOwnerMs,e.wallMs),attention:e.waitingOwnerMs>0},{id:"touches",label:"Your touches",value:String(s.total),title:`Answered ${s.answered}, approved ${s.approved}, sent back ${s.sentBack}, corrected ${s.corrected}, other ${s.other??0}`},{id:"rework",label:"Rework",value:String(r.total),title:`Send-backs ${r.sendBacks}, retries ${r.retries}, failed verifications ${r.failedVerifications}, subagent send-backs ${r.subagentSendBacks}`,attention:r.total>0},{id:"stalls",label:"Stalls",value:String(t.stalls.count),hint:t.stalls.count>0?n?"one still going":zi(t.stalls.totalMs):void 0,attention:t.stalls.count>0},{id:"cost",label:"Cost",value:Nc(t.usage.costUsd),hint:`${A0(t.usage.totalTokens)} tokens`}]}function Jz(t,e){return t.length===0?"none":t.map(n=>`${e(n.key)} ${A0(n.totalTokens)} ${Nc(n.costUsd)}`).join(" · ")}const RX=({metrics:t,nameOf:e=n=>n})=>{var o;const n=JBe(t),s=t,r=Object.entries(s.stalls.byCause).filter(([,l])=>l>0).map(([l,c])=>`${rI[l]} ${c}`).join(" · "),a=s.interventions;return i.jsxs("section",{"aria-label":"Run metrics","data-testid":"trace-metrics-strip",children:[i.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] text-text-2",children:[i.jsx(sn,{tone:YBe(s.outcome.state),"data-testid":"trace-outcome",children:yde[s.outcome.state]}),((o=s.outcome.experiment)==null?void 0:o.verdict)&&i.jsxs("span",{children:["Experiment: ",s.outcome.experiment.verdict==="didnt"?"didn't work":s.outcome.experiment.verdict]}),s.outcome.workItems.total>0&&i.jsxs("span",{children:[s.outcome.workItems.done," of ",s.outcome.workItems.total," runs done",s.outcome.workItems.failed>0?` · ${s.outcome.workItems.failed} failed`:""]})]}),i.jsx("dl",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap sm:gap-3",children:n.map(l=>i.jsxs("div",{title:l.title,className:`min-w-0 rounded-2xl px-3 py-2 sm:min-w-[7.5rem] ${l.attention?"bg-attention-soft":"bg-surface"}`,"data-testid":`trace-metric-${l.id}`,children:[i.jsx("dt",{className:"truncate text-[12px] text-text-2",children:l.label}),i.jsx("dd",{className:`text-[15px] font-bold leading-snug ${l.attention?"text-attention":"text-text"}`,children:l.value}),l.hint&&i.jsx("dd",{className:"truncate text-[12px] text-text-3",children:l.hint})]},l.id))}),i.jsx(ni,{className:"mt-2",unmountWhenClosed:!0,title:"Details",summary:"Touches, rework, interventions, cost by agent and model","data-testid":"trace-metrics-details",children:i.jsxs("dl",{className:"grid grid-cols-1 gap-x-6 gap-y-1.5 text-[13px] sm:grid-cols-[auto_1fr]",children:[i.jsx("dt",{className:"text-text-2",children:"Your touches"}),i.jsxs("dd",{className:"text-text",children:["answered ",s.ownerTouches.answered," · approved ",s.ownerTouches.approved," · sent back ",s.ownerTouches.sentBack," · corrected ",s.ownerTouches.corrected," · other ",s.ownerTouches.other??0]}),i.jsx("dt",{className:"text-text-2",children:"Rework"}),i.jsxs("dd",{className:"text-text",children:["send-backs ",s.rework.sendBacks," · retries ",s.rework.retries," · failed verifications ",s.rework.failedVerifications," · subagent send-backs ",s.rework.subagentSendBacks]}),i.jsx("dt",{className:"text-text-2",children:"Crewly stepped in"}),i.jsxs("dd",{className:"text-text",children:["nudges ",a.nudges," · redeliveries ",a.redeliveries," · wakes ",a.wakes," · corrections ",a.corrections," · guard blocks ",a.guardBlocks," · misroutes ",a.misroutes]}),i.jsx("dt",{className:"text-text-2",children:"Time"}),i.jsxs("dd",{className:"text-text",children:["working ",zi(s.time.activeMs)," · waiting on you ",zi(s.time.waitingOwnerMs)," · waiting on agents ",zi(s.time.waitingAgentMs)," · idle ",zi(s.time.idleMs)]}),i.jsx("dt",{className:"text-text-2",children:"Stalls"}),i.jsx("dd",{className:"text-text",children:s.stalls.count===0?`none longer than ${s.stalls.thresholdMinutes}m`:`${r} (longer than ${s.stalls.thresholdMinutes}m)`}),i.jsx("dt",{className:"text-text-2",children:"By agent"}),i.jsx("dd",{className:"text-text",children:Jz(s.usage.byAgent,e)}),i.jsx("dt",{className:"text-text-2",children:"By model"}),i.jsx("dd",{className:"break-words text-text",children:Jz(s.usage.byModel,l=>l)})]})})]})};RX.displayName="MetricsStrip";function ZBe(t,e){if(t.kind==="stall"&&t.stall)return`Stalled ${zi(t.stall.ms)}${t.stall.ongoing?" and counting":""} — ${rI[t.stall.cause]}`;if(t.kind==="owner")return"You";if(t.kind==="system")return"Crewly";const n=t.session;if(!n)return t.title;const s=e(n);if(t.title===`${n} working`)return`${s} working`;if(t.title===`Harness → ${n}`)return`Crewly → ${s}`;const r=t.title.lastIndexOf(" → "),a=r>=0?t.title.slice(0,r):t.title;return`${a==="Owner"?"You":a} → ${s}`}function Zz(t,e){var o;const n=T0(t.start,e),s=T0(t.end,e),r=n===s?n:`${n}–${s}`;if(t.kind==="stall")return(o=t.stall)!=null&&o.ongoing?`since ${n}`:r;const a=[r,`${t.counts.events} ${t.counts.events===1?"event":"events"}`];return t.counts.skillCalls>0&&a.push(`${t.counts.skillCalls} skill ${t.counts.skillCalls===1?"call":"calls"}`),t.tokens>0&&a.push(`${A0(t.tokens)} tokens ${Nc(t.costUsd)}`),a.join(" · ")}const QBe=({event:t,nameOf:e,now:n})=>{const s=t.actor.kind==="agent"&&t.actor.session?e(t.actor.session):_de(t);return i.jsxs("li",{className:"flex min-w-0 gap-3 py-1.5 text-[13px]","data-testid":"trace-event",children:[i.jsx("span",{className:"w-12 shrink-0 font-mono text-[12px] text-text-3",children:T0(t.ts,n)}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"font-semibold text-text",children:bde(t.type)}),i.jsxs("span",{className:"text-text-3",children:[" · ",s]}),(t.outcome==="failed"||t.outcome==="blocked")&&i.jsx(sn,{className:"ml-2",size:"sm",tone:t.outcome==="failed"?"danger":"attention",children:t.outcome==="failed"?"Failed":"Blocked"}),i.jsx("span",{className:"block break-words text-text-2",children:t.summary})]})]})},IX=({group:t,nameOf:e=s=>s,now:n})=>{var h,f;const[s,r]=_.useState(!1),[a,o]=_.useState(!1),l=t.kind==="stall",c=t.events.filter(p=>MB.has(p.type)),d=a?t.events:t.events.filter(p=>!MB.has(p.type)),u=l||t.outcome==="blocked"?"bg-attention":t.outcome==="failed"?"bg-danger":t.kind==="owner"?"bg-primary":"bg-muted-dot";return i.jsxs("li",{className:`list-none border-b border-border-soft last:border-b-0 ${l?"bg-attention-soft":""}`,"data-testid":`trace-group-${t.id}`,"data-kind":t.kind,children:[i.jsx(Ts,{className:"border-b-0",primary:i.jsx("span",{className:l?"text-attention":void 0,children:ZBe(t,e)}),meta:l?`${Zz(t,n)} · ${((h=t.stall)==null?void 0:h.detail)??""}`:Zz(t,n),leading:i.jsx("span",{"aria-hidden":"true",className:`h-2.5 w-2.5 rounded-full ${u}${(f=t.stall)!=null&&f.ongoing?" animate-pulse":""}`}),trailing:t.kind!=="stall"&&(t.counts.errors>0||t.counts.blocks>0)?i.jsxs("span",{className:"text-[12px]",children:[t.counts.errors>0&&i.jsxs("span",{className:"text-danger",children:[t.counts.errors," failed"]}),t.counts.errors>0&&t.counts.blocks>0&&" · ",t.counts.blocks>0&&i.jsxs("span",{className:"text-attention",children:[t.counts.blocks," blocked"]})]}):void 0,onClick:l?void 0:()=>r(p=>!p),"data-testid":`trace-group-row-${t.id}`}),s&&!l&&i.jsxs("div",{className:"px-4 pb-3 sm:pl-12","data-testid":`trace-group-events-${t.id}`,children:[i.jsx("ul",{className:"divide-y divide-border-soft",children:d.map((p,x)=>i.jsx(QBe,{event:p,nameOf:e,now:n},`${p.ts}-${x}`))}),c.length>0&&i.jsx(de,{variant:"link",size:"xs",onClick:()=>o(p=>!p),"data-testid":`trace-group-show-all-${t.id}`,children:a?"Hide routine events":`Show all ${t.events.length} events (${c.length} routine)`})]})]})};IX.displayName="TimelineGroupRow";const eFe=3e4,tFe=5*6e4,nFe=new Set(["done","cancelled","failed"]),lC=({traceId:t,refParam:e,refId:n,nameOf:s,pollMs:r=eFe,now:a,onLoaded:o})=>{const[l,c]=_.useState({kind:"loading"}),[d,u]=_.useState(!1),h=_.useRef(t??null),f=_.useRef(null),p=_.useRef(0),x=_.useRef(o);x.current=o;const v=_.useCallback(async y=>{var b;y&&u(!0);try{let S=t??h.current;if(!S&&e&&n){const T=await qBe(e,n);S=(T==null?void 0:T.traceId)??null}if(!S){c({kind:"none"});return}h.current=S;const E=await XBe(S),k=`${E.metrics.eventCount}|${E.metrics.window.end}`;k===f.current?p.current+=1:(f.current=k,p.current=0),c({kind:"ready",data:E}),(b=x.current)==null||b.call(x,E)}catch(S){y||c({kind:"error",message:S instanceof Error?S.message:"Failed to load the timeline"})}finally{u(!1)}},[t,e,n]);_.useEffect(()=>{h.current=t??null,f.current=null,p.current=0,c({kind:"loading"}),v(!1)},[v,t]);const m=l.kind==="ready"&&nFe.has(l.data.metrics.outcome.state);if(_.useEffect(()=>{if(!r||l.kind!=="ready"||m)return;let y,b=!1;const S=()=>{if(b||document.hidden)return;const k=Math.max(r,Math.min(r*2**p.current,tFe));y=setTimeout(()=>{v(!0).then(S)},k)},E=()=>{clearTimeout(y),!document.hidden&&!b&&v(!0).then(S)};return S(),document.addEventListener("visibilitychange",E),()=>{b=!0,clearTimeout(y),document.removeEventListener("visibilitychange",E)}},[r,l.kind,m,v]),l.kind==="loading")return i.jsx("div",{className:"flex justify-center py-10","data-testid":"trace-timeline-loading",children:i.jsx(zt,{})});if(l.kind==="none")return i.jsx(is,{icon:du,title:"No timeline for this yet",description:"A timeline is recorded for work started after run traces were turned on.",compact:!0,"data-testid":"trace-timeline-none"});if(l.kind==="error")return i.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center","data-testid":"trace-timeline-error",children:[i.jsx("p",{className:"text-sm text-danger",children:l.message}),i.jsx(de,{variant:"secondary",size:"sm",icon:$t,onClick:()=>void v(!1),children:"Retry"})]});const{data:g}=l;return i.jsxs("div",{className:"flex flex-col gap-4","data-testid":"trace-timeline",children:[i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx(RX,{metrics:g.metrics,nameOf:s})}),i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh timeline",onClick:()=>void v(!0),loading:d,"data-testid":"trace-timeline-refresh"})]}),g.groups.length===0?i.jsx("p",{className:"py-6 text-[13px] text-text-3","data-testid":"trace-timeline-empty",children:"Nothing has happened in this run yet."}):i.jsx("ol",{className:"overflow-hidden rounded-2xl bg-surface","aria-label":"Run timeline","data-testid":"trace-timeline-groups",children:g.groups.map(y=>i.jsx(IX,{group:y,nameOf:s,now:a},y.id))}),g.truncated&&i.jsx("p",{className:"text-[12px] text-text-3",children:"This run hit the trace size limit; later events were not recorded."})]})};lC.displayName="TraceTimeline";const sFe={overview:"Overview",timeline:"Timeline"},Qz={open:"text-primary-text",in_progress:"text-primary-text",blocked:"text-danger",waiting_confirmation:"text-attention",awaiting_followup:"text-attention",done:"text-success",cancelled:"text-text-2"};function ej(t){return{open:"Open",in_progress:"In Progress",blocked:"Blocked",waiting_confirmation:"Waiting Confirmation",awaiting_followup:"Awaiting Follow-up",done:"Completed",cancelled:"Cancelled"}[t]??t}const e6=["open","in_progress","done"],rFe=({currentStatus:t})=>{const e=e6.indexOf(t),n=t==="cancelled"||t==="blocked";return i.jsxs("ol",{className:"flex flex-wrap items-center gap-1.5 text-[13px]","aria-label":"Progress","data-testid":"request-progress-rail",children:[e6.map((s,r)=>{const a=s===t,o=e>=0&&r<=e;return i.jsxs(an.Fragment,{children:[r>0&&i.jsx("li",{"aria-hidden":"true",className:`h-px w-6 ${o?"bg-success":"bg-border"}`}),i.jsxs("li",{"aria-current":a?"step":void 0,className:`inline-flex items-center gap-1 ${a?`font-semibold ${Qz[s]??"text-text"}`:o?"text-success":"text-text-3"}`,children:[o&&!a&&i.jsx(Ua,{className:"h-3 w-3","aria-hidden":"true"}),ej(s)]})]},s)}),n&&i.jsxs(i.Fragment,{children:[i.jsx("li",{"aria-hidden":"true",className:"h-px w-6 bg-border"}),i.jsx("li",{"aria-current":"step",className:`font-semibold ${Qz[t]??"text-text-2"}`,children:ej(t)})]})]})},iFe=({workItems:t,onItemClick:e,names:n})=>{const[s,r]=_.useState(null);return t.length===0?i.jsx("p",{className:"py-6 text-[13px] text-text-3","data-testid":"request-workitems-empty",children:"No runs for this request yet."}):i.jsx("ul",{className:"overflow-hidden rounded-2xl bg-surface","data-testid":"request-workitems-list",children:t.map(a=>{const o=s===a.id,l=Jd(a.target,n,!0);return i.jsxs("li",{className:"list-none border-b border-border-soft last:border-b-0","data-testid":`request-workitem-${a.id}`,children:[i.jsx(Ts,{className:"border-b-0",primary:a.title,meta:[oP(a.type),l,oC(a.createdAt)].filter(Boolean).join(" · "),trailing:i.jsx(sn,{tone:a.status==="cancelled"||a.status==="queued"||a.status==="scheduled"?"neutral":rE(a.status),children:aP(a.status)}),onClick:()=>r(o?null:a.id),actions:[i.jsx(de,{variant:"link",size:"xs",onClick:()=>e(a.id),"data-testid":`request-workitem-detail-link-${a.id}`,children:"Details"},"details")],"data-testid":`request-workitem-row-${a.id}`}),o&&i.jsx("div",{className:"border-t border-border-soft px-4 py-3","data-testid":`request-workitem-timeline-${a.id}`,children:i.jsx(lP,{events:kX(a)})})]},a.id)})})},LX=()=>{const{id:t}=Lc(),e=cs(),{names:n}=Bm(),[s,r]=uu(_h),a=_.useCallback(N=>Jd(N,n)??N,[n]),[o,l]=_.useState(null),[c,d]=_.useState([]),[u,h]=_.useState(!0),[f,p]=_.useState(null),[x,v]=_.useState(!1),[m,g]=_.useState(null),y=_.useCallback(async(N=!0)=>{if(t){N?h(!0):v(!0),p(null);try{const[L,I,D]=await Promise.all([lt.getRequest(t),lt.getWorkItemsByRequest(t),Promise.resolve().then(()=>lt.getRequestWhereabouts(t)).catch(()=>null)]);g(D&&!D.finished?D.summary:null),l(L),d(I.sort((z,U)=>new Date(U.createdAt).getTime()-new Date(z.createdAt).getTime()))}catch(L){const I=L instanceof Error?L.message:"Failed to load request";p(I)}finally{h(!1),v(!1)}}},[t]);_.useEffect(()=>{y(!0)},[y]),_.useEffect(()=>{if(!o||o.status==="done"||o.status==="cancelled")return;const N=setInterval(()=>{y(!1)},15e3);return()=>clearInterval(N)},[o==null?void 0:o.status,y]);const b=_.useCallback(()=>{e(qt.requests())},[e]),S=_.useCallback(N=>{e(qt.run(N))},[e]),E=_.useCallback(()=>{y(!1)},[y]),k=_.useCallback(async N=>{if(t)try{const L=N==="confirmed"?"done":"cancelled";await lt.updateRequest(t,{status:L}),y(!1)}catch(L){const I=L instanceof Error?L.message:"Failed to update request";p(I)}},[t,y]),T=_.useMemo(()=>o?o.totalInputTokens+o.totalOutputTokens:0,[o]),A=_.useMemo(()=>{if(!o)return"";const N=new Date(o.createdAt).getTime(),I=(o.completedAt?new Date(o.completedAt).getTime():Date.now())-N,D=Math.floor(I/6e4),z=Math.floor(D/60);return D<1?"< 1m":z<1?`${D}m`:`${z}h ${D%60}m`},[o]);if(u)return i.jsx("div",{className:"flex items-center justify-center h-64","data-testid":"request-detail-loading",children:i.jsx(zt,{})});if(f)return i.jsxs("div",{className:"p-6","data-testid":"request-detail-error",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:Fa,onClick:b,className:"mb-6",children:"Back to Requests"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsxs("div",{className:"flex flex-col items-center text-center py-8",children:[i.jsx("p",{className:"text-danger text-lg font-medium mb-2",children:"Failed to load Request"}),i.jsx("p",{className:"text-text-2 text-sm mb-4",children:f}),i.jsx(de,{variant:"secondary",size:"sm",icon:$t,onClick:()=>y(!0),children:"Retry"})]})})]});if(!o)return i.jsxs("div",{className:"p-6","data-testid":"request-detail-not-found",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:Fa,onClick:b,className:"mb-6",children:"Back to Requests"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsx(is,{icon:Cl,title:"Request not found.",compact:!0})})]});const M=[`Created ${oC(o.createdAt)}`,o.intentCategory?o.intentCategory.replace(/_/g," "):null,o.intentLevel?`Intent level ${o.intentLevel}`:null,o.priority&&o.priority!=="normal"?`${o.priority.charAt(0).toUpperCase()}${o.priority.slice(1)} priority`:null].filter(Boolean);return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-6","data-testid":"request-detail",children:[i.jsx(_r,{className:"mb-0",eyebrow:i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:qt.ticketsBoard(),className:"text-text-2 hover:text-text",children:"Tickets"}),i.jsx("span",{className:"text-text-3",children:"/"}),i.jsx(hs,{to:qt.requests(),className:"text-text-2 hover:text-text","data-testid":"request-detail-back",children:"Requests"})]}),title:o.title,subtitle:i.jsx(i.Fragment,{children:M.map((N,L)=>i.jsxs(an.Fragment,{children:[L>0&&" · ",N]},L))}),actions:i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:E,loading:x,"data-testid":"request-detail-refresh"}),tabs:i.jsx(Oc,{"aria-label":"Request views",idPrefix:"request",value:s,onChange:N=>r(N),tabs:_h.map(N=>({value:N,label:sFe[N]}))}),"data-testid":"request-detail-header"}),s==="timeline"?i.jsx("div",{role:"tabpanel",id:"request-panel-timeline","aria-labelledby":"request-tab-timeline","data-testid":"request-panel-timeline",children:i.jsx(lC,{traceId:o.traceId,refParam:"requestId",refId:o.id,nameOf:a})}):i.jsxs("div",{role:"tabpanel",id:"request-panel-overview","aria-labelledby":"request-tab-overview",className:"flex flex-col gap-6","data-testid":"request-panel-overview",children:[i.jsxs("div",{className:"-mt-2 flex flex-wrap items-center gap-x-4 gap-y-2 text-[13px] text-text-2",children:[i.jsx(sn,{tone:aFe(o.status),children:ej(o.status)}),o.requiresConfirmation&&i.jsx("span",{className:"font-semibold text-attention",children:"Requires confirmation"}),typeof o.ticketNumber=="number"&&i.jsxs("span",{children:["TKT-",String(o.ticketNumber).padStart(3,"0")]}),i.jsx(rFe,{currentStatus:o.status})]}),m&&i.jsxs("p",{className:"-mt-3 text-[13px] text-text-2","data-testid":"request-now-with",children:[i.jsx("span",{className:"font-semibold text-text",children:"Now: "}),m]}),o.requiresConfirmation&&o.status==="waiting_confirmation"&&i.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-2xl bg-attention-soft px-4 py-3","data-testid":"request-action-area",children:[i.jsx("span",{className:"mr-auto text-sm text-text",children:"This request needs your confirmation before it completes"}),i.jsx(de,{variant:"secondary",size:"sm",onClick:()=>k("rejected"),children:"Reject"}),i.jsx(de,{variant:"primary",size:"sm",onClick:()=>k("confirmed"),children:"Approve"})]}),o.openItems&&o.openItems.length>0&&i.jsx(WBe,{items:o.openItems,onSkip:async N=>{await _re(o.id,N),await y(!1)}}),i.jsxs("section",{"aria-labelledby":"request-message-heading",children:[i.jsx("h2",{id:"request-message-heading",className:"mb-2 text-[15px] font-bold text-text",children:"Original message"}),o.description?i.jsx("p",{className:"whitespace-pre-wrap text-sm leading-relaxed text-text",children:o.description}):i.jsx("p",{className:"text-sm italic text-text-3",children:"No description provided."}),(o.sourceConversationItemId||o.tags.length>0)&&i.jsxs("p",{className:"mt-3 flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] text-text-3",children:[o.sourceConversationItemId&&i.jsxs("span",{children:["Source: ",i.jsx("span",{className:"font-mono",children:o.sourceConversationItemId})]}),o.tags.map(N=>i.jsx("span",{className:"rounded-full bg-surface-2 px-2 py-0.5 text-text-2",children:N},N))]})]}),i.jsxs("section",{"data-testid":"request-detail-workitems","aria-labelledby":"request-runs-heading",children:[i.jsxs("h2",{id:"request-runs-heading",className:"mb-2 text-[15px] font-bold text-text",children:["Runs ",i.jsx("span",{className:"text-[13px] font-normal text-text-2",children:c.length})]}),i.jsx(iFe,{workItems:c,onItemClick:S,names:n})]}),i.jsx(ni,{title:"Statistics",summary:"Tokens, cost, elapsed time, runs",children:i.jsxs("dl",{className:"grid max-w-md grid-cols-[1fr_auto] gap-x-6 gap-y-2 text-sm","data-testid":"request-detail-stats",children:[i.jsxs("dt",{className:"flex items-center gap-1.5 text-text-2",children:[i.jsx(_0,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Total tokens"]}),i.jsx("dd",{className:"text-right font-semibold text-text",children:Qx(T)}),i.jsx("dt",{className:"pl-5 text-text-3",children:"Input"}),i.jsx("dd",{className:"text-right text-text-2",children:Qx(o.totalInputTokens)}),i.jsx("dt",{className:"pl-5 text-text-3",children:"Output"}),i.jsx("dd",{className:"text-right text-text-2",children:Qx(o.totalOutputTokens)}),i.jsxs("dt",{className:"flex items-center gap-1.5 text-text-2",children:[i.jsx(rR,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Total cost"]}),i.jsx("dd",{className:"text-right font-semibold text-text",children:CX(o.totalCost)}),i.jsxs("dt",{className:"flex items-center gap-1.5 text-text-2",children:[i.jsx(jr,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Elapsed time"]}),i.jsx("dd",{className:"text-right font-semibold text-text",children:A}),i.jsxs("dt",{className:"flex items-center gap-1.5 text-text-2",children:[i.jsx(fM,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Runs"]}),i.jsx("dd",{className:"text-right font-semibold text-text",children:c.length})]})})]})]})};function aFe(t){return t==="open"||t==="in_progress"||t==="awaiting_followup"?"primary":t==="cancelled"?"neutral":rE(t)}LX.displayName="RequestDetail";const oFe="/api/experiments";class PX extends Error{constructor(e,n){super(e),this.status=n,this.name="ExperimentsApiError"}}async function DX(t){const e=await fetch(`${oFe}${t}`);let n={};try{n=await e.json()}catch{n={}}if(!e.ok||n.success===!1)throw new PX(n.error||`HTTP ${e.status}`,e.status);return n.data}function lFe(){return DX("")}function cFe(t){return DX(`/${encodeURIComponent(t)}`)}function OX(t){return t.status==="done"?t.verdict==="worked"?{label:"Worked",tone:"success"}:t.verdict==="didnt"?{label:"Didn't work",tone:"danger"}:{label:"Inconclusive",tone:"attention"}:t.status==="running"?{label:"Measuring",tone:"primary"}:t.status==="cancelled"?{label:"Cancelled",tone:"neutral"}:{label:"Not shipped",tone:"neutral"}}function BX(t){if(t.metric.label)return t.metric.label;const e=t.metric.page??t.metric.query??t.metric.event;return`${t.metric.source.toUpperCase()} ${t.metric.measure}${e?` · ${e}`:""}`}const dFe=()=>{const t=cs(),[e,n]=_.useState(null),[s,r]=_.useState(null),[a,o]=_.useState(!1),l=_.useCallback(async()=>{r(null),o(!1);try{const c=await lFe();n([...c].sort((d,u)=>u.updatedAt.localeCompare(d.updatedAt)))}catch(c){c instanceof PX&&c.status===503?o(!0):r(c instanceof Error?c.message:"Failed to load experiments")}},[]);return _.useEffect(()=>{l()},[l]),a?i.jsx(is,{icon:tm,title:"Experiments are not running",description:"Experiment cards are switched off on this machine, or Crewly is still starting. Nothing to show yet.",action:i.jsx(de,{variant:"secondary",size:"sm",icon:$t,onClick:()=>void l(),children:"Check again"}),"data-testid":"experiments-off"}):s?i.jsxs("div",{className:"flex flex-col items-center gap-3 py-10 text-center","data-testid":"experiments-error",children:[i.jsx("p",{className:"text-sm text-danger",children:s}),i.jsx(de,{variant:"secondary",size:"sm",icon:$t,onClick:()=>void l(),children:"Retry"})]}):e?e.length===0?i.jsx(is,{icon:tm,title:"No experiments yet",description:"An agent attaches an experiment to a ticket that should move a number; it is measured automatically after the change ships.","data-testid":"experiments-empty"}):i.jsx("ul",{className:"overflow-hidden rounded-2xl bg-surface","data-testid":"experiments-list",children:e.map(c=>{const d=OX(c),u=[c.id,BX(c),c.ticket?c.ticket.id:null,`${c.windowDays}-day window`].filter(Boolean).join(" · ");return i.jsx("li",{className:"list-none",children:i.jsx(Ts,{primary:c.title,meta:u,trailing:i.jsx(sn,{tone:d.tone,children:d.label}),onClick:()=>t(qt.experiment(c.id)),"data-testid":`experiment-row-${c.id}`})},c.id)})}):i.jsx("div",{className:"flex justify-center py-10","data-testid":"experiments-loading",children:i.jsx(zt,{})})},uFe={overview:"Overview",timeline:"Timeline"};function v1(t){return!t||t.total===null?"—":`${Number.isInteger(t.total)?t.total.toLocaleString():t.total.toFixed(3)} (${t.start} – ${t.end})`}function t6(t){return t?[`${t.ticketsShipped} shipped (${t.ticketsStarted} started)`,t.ownerTouchesPerTicket===null?`${t.ownerTouches} owner touches`:`${t.ownerTouchesPerTicket} owner touches per ticket`,`stalls ${t.stalls===0?"none":zi(t.stallMs)}`,t.costPerShippedTicket===null?`${Nc(t.costUsd)} spent`:`${Nc(t.costPerShippedTicket)} per shipped ticket`].join(" · "):"Not measured yet"}const hFe=({scope:t})=>{var e;return i.jsxs("section",{"aria-labelledby":"experiment-autopilot-heading","data-testid":"experiment-autopilot",children:[i.jsxs("h2",{id:"experiment-autopilot-heading",className:"mb-2 text-[15px] font-bold text-text",children:["Autopilot: ",t.projectName,t.label?` · ${t.label}`:""]}),i.jsxs("dl",{className:"grid max-w-xl grid-cols-[auto_1fr] gap-x-6 gap-y-2 text-sm",children:[t.processBaseline&&!t.processBaseline.noData&&i.jsxs(i.Fragment,{children:[i.jsx("dt",{className:"text-text-2",children:"Before"}),i.jsx("dd",{className:"text-text",children:t6(t.processBaseline)})]}),i.jsx("dt",{className:"text-text-2",children:"During"}),i.jsx("dd",{className:"text-text",children:(e=t.processResult)!=null&&e.noData?"No autopilot work recorded":t6(t.processResult)}),t.outcomes.map((n,s)=>i.jsxs(an.Fragment,{children:[i.jsx("dt",{className:"text-text-2",children:n.metric.label??`${n.metric.source} ${n.metric.measure}${n.metric.page?` ${n.metric.page}`:""}`}),i.jsx("dd",{className:"break-words text-text",children:n.verdictReason??(n.lastError?`Fetch failed: ${n.lastError}`:`${v1(n.baseline)} → ${v1(n.result)}`)})]},s))]})]})},FX=()=>{const{id:t=""}=Lc(),[e,n]=uu(_h),[s,r]=_.useState(null),[a,o]=_.useState(null),[l,c]=_.useState(!0),d=_.useCallback(async()=>{c(!0),o(null);try{r(await cFe(t))}catch(p){o(p instanceof Error?p.message:"Failed to load the experiment")}finally{c(!1)}},[t]);_.useEffect(()=>{d()},[d]);const u=i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:qt.ticketsBoard(),className:"text-text-2 hover:text-text",children:"Tickets"}),i.jsx("span",{className:"text-text-3",children:"/"}),i.jsx(hs,{to:qt.experiments(),className:"text-text-2 hover:text-text","data-testid":"experiment-detail-back",children:"Experiments"})]});if(l&&!s)return i.jsx("div",{className:"flex h-64 items-center justify-center","data-testid":"experiment-detail-loading",children:i.jsx(zt,{})});if(a||!s)return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-4 sm:p-6","data-testid":"experiment-detail-error",children:[i.jsx(_r,{className:"mb-0",eyebrow:u,title:"Experiment"}),i.jsx(is,{icon:tm,title:"Experiment not found",description:a??void 0,action:i.jsx(de,{variant:"secondary",size:"sm",icon:$t,onClick:()=>void d(),children:"Retry"})})]});const h=OX(s),f=s.traceId.startsWith("tr-")?s.traceId:null;return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-4 sm:p-6","data-testid":"experiment-detail",children:[i.jsx(_r,{className:"mb-0",eyebrow:u,title:s.title,subtitle:`${s.id} · ${BX(s)} · ${s.windowDays}-day window · by ${s.createdBy}`,actions:i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:()=>void d(),loading:l}),tabs:i.jsx(Oc,{"aria-label":"Experiment views",idPrefix:"experiment",value:e,onChange:p=>n(p),tabs:_h.map(p=>({value:p,label:uFe[p]}))})}),e==="timeline"?i.jsx("div",{role:"tabpanel",id:"experiment-panel-timeline","aria-labelledby":"experiment-tab-timeline","data-testid":"experiment-panel-timeline",children:i.jsx(lC,{traceId:f,refParam:"experimentId",refId:s.id})}):i.jsxs("div",{role:"tabpanel",id:"experiment-panel-overview","aria-labelledby":"experiment-tab-overview",className:"flex flex-col gap-6","data-testid":"experiment-panel-overview",children:[i.jsxs("div",{className:"-mt-2 flex flex-wrap items-center gap-x-4 gap-y-2 text-[13px] text-text-2",children:[i.jsx(sn,{tone:h.tone,children:h.label}),s.ticket&&i.jsxs("span",{children:["Ticket ",s.ticket.id]}),s.dueAt&&s.status==="running"&&i.jsxs("span",{children:["Measured after ",s.dueAt.slice(0,10)]})]}),i.jsxs("section",{"aria-labelledby":"experiment-hypothesis-heading",children:[i.jsx("h2",{id:"experiment-hypothesis-heading",className:"mb-2 text-[15px] font-bold text-text",children:"Hypothesis"}),i.jsx("p",{className:"whitespace-pre-wrap text-sm leading-relaxed text-text",children:s.hypothesis})]}),i.jsxs("dl",{className:"grid max-w-xl grid-cols-[auto_1fr] gap-x-6 gap-y-2 text-sm","data-testid":"experiment-results",children:[i.jsx("dt",{className:"text-text-2",children:"Baseline"}),i.jsx("dd",{className:"text-text",children:v1(s.baseline)}),i.jsx("dt",{className:"text-text-2",children:"Result"}),i.jsx("dd",{className:"text-text",children:v1(s.result)}),i.jsx("dt",{className:"text-text-2",children:"Verdict"}),i.jsx("dd",{className:"text-text",children:s.verdict?`${h.label}${s.verdictReason?` — ${s.verdictReason}`:""}`:"Not measured yet"}),s.lastError&&i.jsxs(i.Fragment,{children:[i.jsx("dt",{className:"text-text-2",children:"Last error"}),i.jsx("dd",{className:"break-words text-danger",children:s.lastError})]})]}),s.autopilot&&i.jsx(hFe,{scope:s.autopilot}),i.jsxs("section",{"aria-labelledby":"experiment-log-heading",children:[i.jsx("h2",{id:"experiment-log-heading",className:"mb-2 text-[15px] font-bold text-text",children:"Card log"}),i.jsx("ol",{className:"flex flex-col gap-1.5 text-[13px]","data-testid":"experiment-card-log",children:[...s.timeline].reverse().map((p,x)=>i.jsxs("li",{className:"flex gap-3",children:[i.jsx("span",{className:"w-28 shrink-0 text-text-3",children:T0(p.at)}),i.jsxs("span",{className:"min-w-0 break-words text-text",children:[i.jsx("span",{className:"font-semibold",children:p.event.replace(/_/g," ")}),p.detail?i.jsxs("span",{className:"text-text-2",children:[" — ",p.detail]}):null]})]},`${p.at}-${x}`))})]})]})]})};FX.displayName="ExperimentDetail";const fFe={request:"Request",goal:"Goal",experiment:"Experiment",owner_message:"Your message",autopilot:"Autopilot run",ticket:"Ticket",triage:"Autopilot triage"},UX=()=>{const{traceId:t=""}=Lc(),{names:e}=Bm(),[n,s]=_.useState(null),r=_.useCallback(o=>Jd(o,e)??o,[e]),a=_.useCallback(o=>s(o.root),[]);return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-4 sm:p-6","data-testid":"trace-detail",children:[i.jsx(_r,{className:"mb-0",eyebrow:i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:qt.ticketsBoard(),className:"text-text-2 hover:text-text",children:"Tickets"}),i.jsx("span",{className:"text-text-3",children:"/"}),i.jsx("span",{className:"text-text-2",children:"Run timeline"})]}),title:(n==null?void 0:n.summary)??"Run timeline",subtitle:n?`${fFe[n.kind]} · started ${T0(n.createdAt)}`:void 0}),i.jsx(lC,{traceId:t,nameOf:r,onLoaded:a})]})};UX.displayName="TraceDetail";const pFe=t=>i.jsx(T$,{...t});function mFe(t){return{active:"Active",blocked:"Blocked",waiting_confirmation:"Waiting Confirmation",done:"Done"}[t]??t}function n6(t){return t.charAt(0).toUpperCase()+t.slice(1)}function gFe(t){const e=Date.now(),n=new Date(t).getTime(),s=e-n,r=Math.floor(s/6e4),a=Math.floor(r/60),o=Math.floor(a/24);return r<1?"just now":r<60?`${r}m ago`:a<24?`${a}h ago`:`${o}d ago`}function xFe(t){return t===0?"$0.00":t<.01?`$${t.toFixed(4)}`:`$${t.toFixed(2)}`}function yFe(t){return{total:t.length,active:t.filter(e=>e.status==="active").length,blocked:t.filter(e=>e.status==="blocked").length,waitingConfirmation:t.filter(e=>e.status==="waiting_confirmation").length,done:t.filter(e=>e.status==="done").length,totalCost:t.reduce((e,n)=>e+(n.totalCost||0),0)}}function vFe(t){switch(t){case"open":case"ready":case"running":case"awaiting_followup":return"active";case"blocked":return"blocked";case"waiting_confirmation":return"waiting_confirmation";case"done":case"cancelled":return"done";default:return typeof console<"u"&&t&&console.warn("[RequestList] Unknown backend Request status:",t),"active"}}function bFe(t){switch(t){case"high":return"high";case"low":return"low";default:return"medium"}}const _Fe=new Set(["open","waiting_owner","ready","overdue"]);function SFe(t){return Array.isArray(t)?t.filter(e=>e&&typeof e=="object"&&_Fe.has(String(e.status))).length:0}function wFe(t){return t.map(e=>{const n=Array.isArray(e.workItemIds)?e.workItemIds:[],s=e.intentCategory;return{id:e.id||"",title:e.title||"Untitled Request",status:vFe(e.status||""),priority:bFe(e.priority||""),source:(e.tags||[]).includes("slack")?"slack":"api",requester:"user",category:s&&s.length>0?s:void 0,workItemCount:n.length,updatedAt:e.updatedAt||e.createdAt||new Date().toISOString(),missionLink:e.missionId?`Mission: ${e.missionId.slice(0,8)}`:void 0,totalInputTokens:e.totalInputTokens||0,totalOutputTokens:e.totalOutputTokens||0,totalCost:e.totalCost||0,ownerAgent:e.ownerAgent||void 0,openItemCount:SFe(e.openItems)}}).sort((e,n)=>new Date(n.updatedAt).getTime()-new Date(e.updatedAt).getTime())}const EFe=25,CFe=300,kFe={slack:kc,email:KH,chat:qH,api:lR,manual:JH},AFe={active:"primary",blocked:"danger",waiting_confirmation:"attention",done:"success"},hx={active:"Active",blocked:"Blocked",waiting_confirmation:"Waiting",done:"Done"},TFe={status:["active"],only:[]},NFe=()=>{const t=cs(),{names:e}=Bm(),[n,s]=_.useState([]),[r,a]=_.useState(!0),[o,l]=_.useState(null),[c,d]=_.useState(TFe),[u,h]=_.useState(""),[f,p]=_.useState("");_.useEffect(()=>{const y=setTimeout(()=>p(u),CFe);return()=>clearTimeout(y)},[u]);const x=_.useCallback(async()=>{a(!0),l(null);try{const y=await lt.getRequests();s(Array.isArray(y)?wFe(y):[])}catch(y){l(y instanceof Error?y.message:"Failed to load requests"),s([])}finally{a(!1)}},[]);_.useEffect(()=>{x()},[x]);const v=_.useMemo(()=>yFe(n),[n]),m=_.useMemo(()=>[{id:"status",label:"Status",single:!0,options:[{value:"active",label:hx.active,count:v.active},{value:"blocked",label:hx.blocked,count:v.blocked},{value:"waiting_confirmation",label:hx.waiting_confirmation,count:v.waitingConfirmation},{value:"done",label:hx.done,count:v.done}]},{id:"only",label:"Only",options:[{value:"assigned_to_me",label:"Assigned to me"},{value:"urgent",label:"Urgent"}]}],[v]),g=_.useMemo(()=>{var E;const y=(E=c.status)==null?void 0:E[0],b=c.only??[],S=f.trim().toLowerCase();return n.filter(k=>!(y&&k.status!==y||b.includes("urgent")&&k.priority!=="critical"&&k.priority!=="high"||b.includes("assigned_to_me")&&k.requester!=="user"||S&&!(k.title.toLowerCase().includes(S)||k.requester.toLowerCase().includes(S)||(k.missionLink??"").toLowerCase().includes(S))))},[n,c,f]);return i.jsxs("div",{className:"flex min-w-0 flex-col gap-4","data-testid":"requests-page",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(Zo,{groups:m,value:c,onChange:d}),i.jsx(tI,{value:u,onChange:h,placeholder:"Search requests…","data-testid":"request-search-input"}),i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:()=>void x(),className:"ml-auto"})]}),r?i.jsx("div",{"data-testid":"request-list-loading",children:i.jsx(sE,{count:4})}):o?i.jsxs("div",{className:"flex flex-col items-center gap-3 py-16 text-text-2","data-testid":"request-list-error",children:[i.jsx("span",{className:"text-sm text-danger",children:o}),i.jsx(de,{variant:"link",onClick:()=>void x(),children:"Retry"})]}):g.length===0?i.jsxs("div",{className:"flex flex-col items-center gap-3 py-16 text-text-2","data-testid":"request-list-empty",children:[i.jsx(VS,{className:"h-10 w-10 opacity-40","aria-hidden":"true"}),i.jsx("span",{className:"text-sm",children:n.length===0?"No requests yet. They appear here when you ask for something in Slack or chat.":"No requests match the current filters."})]}):i.jsx("div",{className:"overflow-hidden rounded-2xl bg-surface","data-testid":"request-list",children:i.jsx(fs,{limit:EFe,as:"ul","data-testid":"request-list-rows",children:g.map(y=>{const b=kFe[y.source]??VS,S=Jd(y.ownerAgent,e),E=[y.category?y.category.replace(/_/g," "):null,S?`via ${S}`:null,y.priority==="high"||y.priority==="critical"?"Urgent":null,y.workItemCount>0?`${y.workItemCount} run${y.workItemCount===1?"":"s"}`:null,y.missionLink?y.missionLink.replace(/^Mission:/,"Goal:"):null,gFe(y.updatedAt)].filter(Boolean),k=y.openItemCount??0;return i.jsx("li",{className:"list-none border-b border-border-soft last:border-b-0","data-testid":`request-row-${y.id}`,children:i.jsx(Ts,{leading:i.jsx("span",{title:n6(y.source),children:i.jsx(b,{className:"h-4 w-4 text-text-3","aria-label":n6(y.source)})}),primary:i.jsx("span",{title:y.title,children:eI(y.title)}),meta:i.jsxs(i.Fragment,{children:[k>0&&i.jsxs("span",{className:"font-semibold text-attention",title:"Promises or questions the agent still owes you",children:[k," open item",k===1?"":"s",E.length>0?" · ":""]}),E.join(" · ")]}),trailing:i.jsx(sn,{tone:AFe[y.status],title:mFe(y.status),children:hx[y.status]}),onClick:()=>t(qt.request(y.id)),className:"border-b-0","data-testid":`request-row-${y.id}-row`})},y.id)})})}),!r&&!o&&n.length>0&&i.jsxs("p",{className:"text-[13px] text-text-3","data-testid":"requests-total",children:[v.total," request",v.total===1?"":"s"," · total cost ",xFe(v.totalCost)]})]})},MFe=25,jFe=300,RFe=[{value:"running",label:"Running"},{value:"queued",label:"Queued"},{value:"done",label:"Completed"},{value:"failed",label:"Failed"},{value:"blocked",label:"Blocked"},{value:"cancelled",label:"Cancelled"}],s6={running:0,blocked:1,failed:2,done:3,completed:3,cancelled:4,queued:5,scheduled:5},zX=()=>{const t=cs(),{names:e}=Bm(),n=TX(),[s,r]=_.useState([]),[a,o]=_.useState(!0),[l,c]=_.useState(null),[d,u]=_.useState({status:[]}),[h,f]=_.useState(""),[p,x]=_.useState(""),v=_.useRef(),m=_.useCallback(E=>{f(E),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>x(E),jFe)},[]);_.useEffect(()=>()=>{v.current&&clearTimeout(v.current)},[]);const g=_.useCallback(async()=>{o(!0),c(null);try{const E=await lt.getWorkItems();r(Array.isArray(E)?E:[])}catch(E){c(E instanceof Error?E.message:"Failed to load runs")}finally{o(!1)}},[]);_.useEffect(()=>{g()},[g]);const y=_.useMemo(()=>{const E={};for(const k of s){const T=k.status==="scheduled"?"queued":k.status;E[T]=(E[T]||0)+1}return E},[s]),b=_.useMemo(()=>[{id:"status",label:"Status",single:!0,options:RFe.map(E=>({...E,count:y[E.value]??0}))}],[y]),S=_.useMemo(()=>{var T;const E=(T=d.status)==null?void 0:T[0],k=p.trim().toLowerCase();return s.filter(A=>!(E&&A.status!==E&&!(E==="queued"&&A.status==="scheduled")||k&&!(A.title.toLowerCase().includes(k)||A.id.toLowerCase().includes(k)||(A.target??"").toLowerCase().includes(k)||(Jd(A.target,e)??"").toLowerCase().includes(k)||A.type.toLowerCase().includes(k)))).sort((A,M)=>{const N=s6[A.status]??5,L=s6[M.status]??5;return N!==L?N-L:new Date(M.createdAt).getTime()-new Date(A.createdAt).getTime()})},[s,d,p,e]);return i.jsxs("div",{className:"flex min-w-0 flex-col gap-4","data-testid":"workitems-page",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(Zo,{groups:b,value:d,onChange:u}),i.jsx(tI,{value:h,onChange:m,placeholder:"Search by title, ID, agent…","data-testid":"workitems-search"}),i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:()=>void g(),className:"ml-auto","data-testid":"workitems-refresh"})]}),a&&i.jsx("div",{"data-testid":"workitems-loading",children:i.jsx(sE,{count:4})}),l&&!a&&i.jsxs(Ye,{variant:"error",title:"Failed to load runs",onClose:()=>c(null),"data-testid":"workitems-error",children:[l,i.jsx(de,{variant:"ghost",size:"sm",onClick:()=>void g(),className:"mt-2",children:"Retry"})]}),!a&&!l&&S.length===0&&i.jsxs("div",{className:"flex flex-col items-center gap-3 py-16 text-text-2","data-testid":"workitems-empty",children:[i.jsx(VS,{className:"h-10 w-10 opacity-40","aria-hidden":"true"}),i.jsx("span",{className:"text-sm",children:s.length===0?"No runs yet.":"No runs match the current filters."})]}),!a&&!l&&S.length>0&&i.jsx("div",{className:"overflow-hidden rounded-2xl bg-surface","data-testid":"workitems-list",children:i.jsx(fs,{limit:MFe,as:"ul",children:S.map(E=>{const k=k$(E.title,n),T=Jd(E.target,e,!0),A=[oP(E.type),T,k,oC(E.createdAt)].filter(Boolean).join(" · ");return i.jsx("li",{className:"list-none border-b border-border-soft last:border-b-0",children:i.jsx(Ts,{primary:i.jsx("span",{title:`${E.title} (${E.id.slice(0,8)})`,children:E.title}),meta:A,trailing:i.jsx(sn,{tone:rE(E.status==="cancelled"||E.status==="queued"||E.status==="scheduled"?"neutral":E.status),children:aP(E.status)}),onClick:()=>t(qt.run(E.id)),className:"border-b-0","data-testid":`workitem-row-${E.id}`})},E.id)})})}),!a&&!l&&s.length>0&&i.jsxs("p",{className:"text-[13px] text-text-3","data-testid":"workitems-total",children:[s.length," run",s.length===1?"":"s"," in the pool"]})]})};zX.displayName="WorkItems";const IFe=({onCreated:t})=>{const[e,n]=_.useState(!1),[s,r]=_.useState([]),[a,o]=_.useState([]),l=()=>{n(!0),Promise.resolve().then(()=>lt.getProjects()).then(c=>r((c??[]).map(d=>({id:d.id,name:d.name})))).catch(()=>r([])),Promise.resolve().then(()=>lt.getTeams()).then(c=>o(c??[])).catch(()=>o([]))};return i.jsxs(i.Fragment,{children:[i.jsx(de,{size:"sm",icon:qn,onClick:l,"data-testid":"tickets-new-ticket",children:hi.NEW_TICKET}),i.jsx(A$,{open:e,ticket:null,projects:s,teams:a,onClose:()=>n(!1),onSaved:t})]})},LFe={board:"Board",requests:"Requests",runs:"Runs",experiments:"Experiments"},PFe={board:"Everything your crew is working on",requests:"Everything you asked for, from every channel",runs:"What the agents actually ran",experiments:"Changes that should move a number, and whether they did"},DFe=()=>{const[t,e]=uu(MO),[n,s]=_.useState(0),[r,a]=_.useState(null),o=_.useCallback(l=>a(l.toReview),[]);return i.jsxs("div",{children:[i.jsx(_r,{title:"Tickets",subtitle:PFe[t],actions:i.jsx(IFe,{onCreated:()=>s(l=>l+1)}),tabs:i.jsx(Oc,{"aria-label":"Tickets views",idPrefix:"tickets",value:t,onChange:l=>e(l),tabs:MO.map(l=>({value:l,label:LFe[l],...l==="board"&&r?{count:r,attention:!0}:{}}))})}),i.jsxs("div",{role:"tabpanel",id:`tickets-panel-${t}`,"aria-labelledby":`tickets-tab-${t}`,"data-testid":`tickets-panel-${t}`,children:[t==="board"&&i.jsx(pFe,{showNewTicket:!1,refreshKey:n,onCountsChange:o}),t==="requests"&&i.jsx(NFe,{}),t==="runs"&&i.jsx(zX,{}),t==="experiments"&&i.jsx(dFe,{})]})]})},OFe=({member:t,teamId:e,onClose:n})=>{const[s,r]=_.useState(null),[a,o]=_.useState(!1),[l,c]=_.useState(null),[d,u]=_.useState(!1),[h,f]=_.useState(null),[p,x]=_.useState(!1),[v,m]=_.useState("prompt"),g=_.useRef(null);_.useEffect(()=>(y(),()=>{S()}),[t.id,e]);const y=async()=>{if(!t.sessionName){c("No active session for this team member");return}try{o(!0),c(null),jt.isConnected()||await jt.connect(),b(),jt.subscribeToSession(t.sessionName),await E()}catch(L){console.error("Error initializing terminal:",L),c("Failed to connect to terminal"),x(!1)}finally{o(!1)}},b=()=>{if(!t.sessionName)return;const L=G=>{G.sessionName===t.sessionName&&(r(K=>({...K,memberId:t.id,memberName:t.name,sessionName:t.sessionName,output:G.content,timestamp:G.timestamp})),setTimeout(()=>{g.current&&(g.current.scrollTop=g.current.scrollHeight)},10))},I=G=>{G.sessionName===t.sessionName&&(r({memberId:t.id,memberName:t.name,sessionName:t.sessionName,output:G.content,timestamp:G.timestamp}),x(!0),c(null))},D=G=>{G.sessionName===t.sessionName&&(console.log("Successfully subscribed to session:",G.sessionName),x(!0),c(null))},z=G=>{G.sessionName===t.sessionName&&(console.error("WebSocket error for session:",G),c(G.error||"WebSocket error occurred"),x(!1))},U=()=>{x(!0)};return jt.on("terminal_output",L),jt.on("initial_terminal_state",I),jt.on("subscription_confirmed",D),jt.on("error",z),jt.on("connected",U),()=>{jt.off("terminal_output",L),jt.off("initial_terminal_state",I),jt.off("subscription_confirmed",D),jt.off("error",z),jt.off("connected",U)}},S=()=>{h&&clearInterval(h),t.sessionName&&jt.isConnected()&&jt.unsubscribeFromSession(t.sessionName)};_.useEffect(()=>{if(d){const L=setInterval(()=>{E()},15e3);f(L)}else h&&(clearInterval(h),f(null));return()=>{h&&clearInterval(h)}},[d]);const E=async()=>{if(!t.sessionName){c("No active session for this team member");return}o(!0),c(null);try{const L=await fetch(`/api/teams/${e}/members/${t.id}/session?lines=100`);if(L.ok){const I=await L.json();I.success?r(I.data):c(I.error||"Failed to fetch session data")}else{const I=await L.json();c(I.error||"Failed to fetch session data")}}catch(L){c("Network error while fetching session data"),console.error("Error fetching session data:",L)}finally{o(!1)}},k=L=>({orchestrator:"text-primary",pm:"text-blue-400",developer:"text-emerald-400",qa:"text-amber-400",tester:"text-red-400",designer:"text-pink-400"})[L]||"text-text-secondary-dark",T=L=>({activating:"warning",active:"success"})[L]||"default",A=L=>L==="in_progress"?"success":"default",M=L=>new Date(L).toLocaleString(),N=i.jsxs("span",{className:"flex flex-col gap-2",children:[i.jsx("span",{children:t.name}),i.jsxs("span",{className:"flex flex-wrap items-center gap-1.5",children:[i.jsx(mn,{className:k(t.role),children:t.role}),i.jsxs(mn,{variant:T(t.agentStatus),children:["Agent: ",t.agentStatus]}),i.jsxs(mn,{variant:A(t.workingStatus),children:["Work: ",t.workingStatus]})]})]});return i.jsx(Pr,{isOpen:!0,onClose:n,title:N,size:"xxl",children:i.jsxs(eE,{value:v,onValueChange:L=>m(L),children:[i.jsxs(tE,{"aria-label":"Member details",children:[i.jsx(Bh,{value:"prompt",children:"System Prompt"}),i.jsx(Bh,{value:"terminal",children:"Terminal Output"})]}),i.jsx(C0,{value:"prompt",children:i.jsx("pre",{className:"max-h-[55vh] overflow-auto whitespace-pre-wrap rounded-2xl border border-border-dark bg-background-dark p-4 text-xs font-mono text-text-primary-dark",children:t.systemPrompt})}),i.jsxs(C0,{value:"terminal",className:"space-y-3",children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[i.jsx("div",{className:"text-xs text-text-secondary-dark",children:t.sessionName&&i.jsxs("span",{children:["Session: ",t.sessionName]})}),i.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[i.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-text-secondary-dark",children:[i.jsx(NR,{status:p?"online":"offline",size:"sm"}),p?"Live":"Offline"]}),i.jsx(vi,{size:"sm",label:"Auto-refresh (fallback)",checked:d,onChange:L=>u(L.target.checked),disabled:p}),i.jsx(de,{onClick:E,disabled:p,loading:a,variant:"secondary",size:"sm",children:a?"Loading...":"Manual Refresh"})]})]}),a&&!s&&i.jsx(zt,{size:"md",text:"Loading session data...",className:"py-8"}),l&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs(Ye,{variant:"error",children:["Error: ",l]}),i.jsx(de,{onClick:E,variant:"outline",size:"sm",children:"Retry"})]}),s&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs("p",{className:"text-xs text-text-secondary-dark",children:["Last updated: ",M(s.timestamp)]}),i.jsx("pre",{className:"max-h-[50vh] overflow-auto whitespace-pre-wrap rounded-2xl border border-border-dark bg-background-dark p-4 text-xs font-mono text-text-primary-dark",ref:g,children:s.output||"No output available"})]}),!a&&!l&&!s&&i.jsx(is,{compact:!0,title:"No session data available"})]})]})})},BFe={xs:"w-6 h-6 text-xs",sm:"w-8 h-8 text-sm",md:"w-10 h-10 text-base",lg:"w-12 h-12 text-lg",xl:"w-16 h-16 text-xl"},FFe={active:"bg-green-500",inactive:"bg-text-secondary-dark",activating:"bg-yellow-500"},UFe=({name:t,avatar:e,size:n="md",className:s="",showStatus:r=!1,status:a,ringClass:o=""})=>{const l=BFe[n],c=()=>{if(e&&(e.startsWith("http")||e.startsWith("data:")))return i.jsx("img",{src:e,alt:`${t}'s avatar`,title:t,className:`${l} rounded-full object-cover ${o} ${s}`});if(e)return i.jsx("div",{className:`${l} rounded-full bg-background-dark border border-border-dark flex items-center justify-center ${o} ${s}`,title:t,children:i.jsx("span",{children:e})});const d=t?t.charAt(0).toUpperCase():"";return i.jsx("div",{className:`${l} rounded-full bg-background-dark border border-border-dark flex items-center justify-center ${o} ${s}`,title:t,children:d})};return i.jsxs("div",{className:"relative inline-block",children:[c(),r&&a&&i.jsx("span",{className:`absolute bottom-0 right-0 w-3 h-3 ${FFe[a]} rounded-full border-2 border-surface-dark`,title:a})]})};function zFe(t){const e=new Map;for(const n of t)if(n.parentTeamId){const s=e.get(n.parentTeamId)||[];s.push(n),e.set(n.parentTeamId,s)}return e}const HX=({team:t,depth:e,childrenMap:n,projectMap:s,onTeamClick:r})=>{var f;const a=n.get(t.id)||[],[o,l]=_.useState(!0),c=a.length>0,d=t.members||[],u=d.some(p=>p.agentStatus==="active"),h=(f=t.projectIds)!=null&&f[0]?s[t.projectIds[0]]:void 0;return i.jsxs("div",{"data-testid":`tree-node-${t.id}`,children:[i.jsxs("div",{className:"flex items-center gap-2 py-2 px-3 rounded-lg hover:bg-background-dark cursor-pointer transition-colors group",style:{paddingLeft:`${e*24+12}px`},onClick:()=>r(t.id),children:[c?i.jsx("button",{onClick:p=>{p.stopPropagation(),l(!o)},className:"p-0.5 text-text-secondary-dark hover:text-text-primary-dark","data-testid":`toggle-${t.id}`,"aria-label":o?"Collapse":"Expand","aria-expanded":o,children:o?i.jsx(Eo,{className:"w-4 h-4"}):i.jsx(cr,{className:"w-4 h-4"})}):i.jsx("span",{className:"w-5"}),i.jsx("span",{className:"font-medium text-sm truncate",children:t.name}),u&&i.jsx("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] font-medium rounded-full bg-green-500/10 text-green-400",children:"Active"}),i.jsxs("span",{className:"text-xs text-text-secondary-dark ml-auto flex items-center gap-1",children:[i.jsx(vr,{className:"w-3 h-3"}),d.length]}),h&&i.jsxs("span",{className:"text-xs text-text-secondary-dark flex items-center gap-1 ml-2",children:[i.jsx(Xo,{className:"w-3 h-3"}),h]}),i.jsx("div",{className:"flex items-center ml-2",children:d.slice(0,3).map((p,x)=>i.jsx("div",{style:{marginLeft:x===0?0:-4},children:i.jsx(UFe,{name:p.name,avatar:p.avatar,size:"xs",ringClass:"ring-1 ring-surface-dark"})},p.id))})]}),c&&o&&i.jsx("div",{"data-testid":`children-${t.id}`,children:a.map(p=>i.jsx(HX,{team:p,depth:e+1,childrenMap:n,projectMap:s,onTeamClick:r},p.id))})]})},HFe=({teams:t,projectMap:e,onTeamClick:n})=>{const s=_.useMemo(()=>zFe(t),[t]),r=_.useMemo(()=>t.filter(a=>!a.parentTeamId),[t]);return r.length===0?i.jsx("div",{className:"text-center py-8 text-text-secondary-dark text-sm",children:"No teams to display"}):i.jsx("div",{className:"bg-surface-dark border border-border-dark rounded-xl p-2","data-testid":"teams-tree-view",children:r.map(a=>i.jsx(HX,{team:a,depth:0,childrenMap:s,projectMap:e,onTeamClick:n},a.id))})};function GFe(t){return(t.members??[]).reduce((e,n)=>{const s=n.readyAt||n.updatedAt;return s?e?new Date(s)>new Date(e)?s:e:s:e},null)}function $Fe(t,e,n){var a;const s=t.members??[];return(((a=t.projectIds)==null?void 0:a.length)??0)>0?{label:e??"Project",needsProject:!1}:s.some(o=>o.role==="orchestrator"||o.role==="auditor")?{label:"System team",needsProject:!1}:t.parentTeamId||(n??0)>0?{label:"Parent team",needsProject:!1}:{label:"No project yet",needsProject:!0}}const WFe=({team:t,projectName:e,subTeamCount:n,onOpen:s,onEdit:r,onStart:a,onStop:o,onOpenChat:l,onOpenWiki:c,onDelete:d,isPinned:u=!1,onTogglePin:h,onPause:f,onResume:p})=>{const[x,v]=_.useState(null),m=t.members??[],g=m.some(N=>N.agentStatus==="active"),y=m.filter(N=>N.loginRequired),b=$Fe(t,e,n),S=D$(t),E=GFe(t),k=(n??0)>0?`${n} sub-team${n===1?"":"s"} · ${m.length} member${m.length===1?"":"s"}`:m.length===0?"No members":m.map(N=>N.name).join(", "),T=i.jsxs(i.Fragment,{children:[i.jsx("span",{className:b.needsProject?"text-attention":void 0,"data-testid":b.needsProject?"assign-project-cta":void 0,children:b.label}),i.jsx("span",{className:"text-text-3",children:" · "}),i.jsx("span",{children:k}),E&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-3",children:" · "}),i.jsx("span",{title:`Last activity: ${new Date(E).toLocaleString()}`,children:Ml(E)})]})]}),A=[{label:"View team",onClick:()=>s(t.id)},...r?[{label:"Edit team",onClick:()=>r(t.id)}]:[],...l?[{label:"Open chat",onClick:()=>l(t.id)}]:[],...c?[{label:"Open wiki",onClick:()=>c(t.id)}]:[],...h?[{label:u?"Unpin from favorites":"Pin to favorites",onClick:h}]:[],...!S&&f?[{label:"Pause team…",onClick:()=>f(t.id)}]:[],...S&&p?[{label:"Resume team",onClick:()=>p(t.id)}]:[],...d?[{label:"Delete team",danger:!0,separator:!0,onClick:()=>v("delete")}]:[]],M=S&&p?i.jsx(de,{variant:"secondary",size:"xs",onClick:()=>p(t.id),"data-testid":`resume-btn-${t.id}`,children:"Resume"},"resume"):g?o&&i.jsx(de,{variant:"secondary",size:"xs",onClick:()=>v("stop"),"data-testid":`stop-btn-${t.id}`,children:"Stop"},"stop"):a&&i.jsx(de,{variant:"secondary",size:"xs",onClick:()=>a(t.id),"data-testid":`start-btn-${t.id}`,children:"Start"},"start");return i.jsxs(i.Fragment,{children:[i.jsx(Ts,{"data-testid":`team-row-${t.id}`,onClick:()=>s(t.id),primary:i.jsxs("span",{className:"inline-flex min-w-0 items-center gap-2",children:[i.jsx("span",{className:"truncate",children:t.name}),u&&i.jsx(iy,{className:"h-3.5 w-3.5 shrink-0 text-text-3","aria-label":"Pinned"})]}),meta:T,trailing:i.jsxs("span",{className:"flex items-center gap-2",children:[y.length>0&&i.jsx("span",{className:"flex items-center gap-1","data-testid":"team-sign-in-needed",children:y.map(N=>i.jsx(zR,{loginRequired:N.loginRequired,agentLabel:N.name,runtimeType:N.runtimeType},N.id))}),S?i.jsx("span",{title:O$(t),"data-testid":`team-paused-${t.id}`,children:i.jsx(sn,{tone:"attention",children:"Paused"})}):i.jsx(sn,{tone:g?"success":"neutral",children:g?"Active":"Idle"})]}),actions:M?[M]:void 0,overflow:A,overflowLabel:`More actions for ${t.name}`}),i.jsx(G0,{isOpen:x==="stop",onCancel:()=>v(null),onConfirm:()=>{v(null),o==null||o(t.id)},title:"Stop Team",message:`Are you sure you want to stop all agents in "${t.name}"? Active work will be interrupted.`,confirmLabel:"Stop Team",confirmVariant:"danger"}),i.jsx(G0,{isOpen:x==="delete",onCancel:()=>v(null),onConfirm:()=>{v(null),d==null||d(t.id)},title:"Delete Team",message:`Delete team "${t.name}"? Its members and terminal sessions are removed. This cannot be undone.`,confirmLabel:"Delete",confirmVariant:"danger"})]})},r6=3e4,VFe=3e5,KFe=2;function qFe(t,e,n,s){const[r,a]=_.useState([]),[o,l]=_.useState(!1),[c,d]=_.useState(null),u=_.useRef(null),h=_.useRef(!0),f=_.useRef(0),p=_.useRef(null),x=_.useRef(!1),v=_.useRef(t),m=_.useRef(n),g=_.useRef(s),y=_.useRef(e);v.current=t,m.current=n,g.current=s,y.current=e;const b=_.useCallback(()=>f.current===0?r6:Math.min(r6*Math.pow(KFe,f.current),VFe),[]),S=_.useCallback(()=>{if(!h.current||!y.current)return;u.current&&clearTimeout(u.current);const A=b();u.current=setTimeout(()=>{k()},A)},[b]),E=_.useCallback(async()=>{var A;if(!x.current){x.current=!0;try{const N=await(await fetch("/api/cloud/device-id")).json();N.success&&((A=N.data)!=null&&A.deviceId)&&(p.current=N.data.deviceId)}catch{}}},[]),k=_.useCallback(async()=>{const A=v.current;if(!A||!h.current)return;await E();const M={"Content-Type":"application/json",Authorization:`Bearer ${A}`};try{const N={deviceName:g.current,teams:m.current};p.current&&(N.deviceId=p.current),await fetch(`${GM}/devices/heartbeat`,{method:"POST",headers:M,body:JSON.stringify(N)});const I=await(await fetch(`${GM}/devices`,{headers:M})).json();h.current&&I.success&&(a(I.data||[]),d(null),f.current=0)}catch(N){h.current&&(f.current=Math.min(f.current+1,10),d(N instanceof Error?N.message:"Heartbeat failed"))}S()},[S,E]),T=_.useCallback(async()=>{l(!0),f.current=0,await k(),h.current&&l(!1)},[k]);return _.useEffect(()=>{if(h.current=!0,!e||!t){a([]),f.current=0;return}return l(!0),k().finally(()=>{h.current&&l(!1)}),()=>{h.current=!1,u.current&&(clearTimeout(u.current),u.current=null)}},[e,t,k]),{devices:r,isLoading:o,error:c,refresh:T}}function XFe(){const[t,e]=_.useState(null),[n,s]=_.useState(!0),[r,a]=_.useState(!1),[o,l]=_.useState(null),c=_.useRef(!0),d=_.useCallback(async()=>{try{const p=await lt.getCloudStatus();c.current&&(e(p),l(null))}catch{c.current&&e({connected:!1,tier:null,cloudUrl:null,status:"disconnected"})}},[]);_.useEffect(()=>(c.current=!0,(async()=>{await d(),c.current&&s(!1)})(),()=>{c.current=!1}),[d]);const u=_.useCallback(async(p,x)=>{a(!0),l(null);try{const v=await lt.connectToCloud(p,x);return c.current&&e({connected:v.connected,tier:v.tier,cloudUrl:v.cloudUrl,status:"connected"}),!0}catch(v){return c.current&&l(v instanceof Error?v.message:"Connection failed"),!1}finally{c.current&&a(!1)}},[]),h=_.useCallback(async()=>{a(!0),l(null);try{return await lt.disconnectFromCloud(),c.current&&e({connected:!1,tier:null,cloudUrl:null,status:"disconnected"}),!0}catch(p){return c.current&&l(p instanceof Error?p.message:"Disconnect failed"),!1}finally{c.current&&a(!1)}},[]),f=_.useCallback(async()=>{await d()},[d]);return{isConnected:(t==null?void 0:t.connected)??!1,tier:(t==null?void 0:t.tier)??null,isLoading:n,isActioning:r,error:o,connect:u,disconnect:h,refresh:f}}const YFe=6,i6=t=>{var e;return((e=t.members)==null?void 0:e.some(n=>n.agentStatus==="active"))??!1},JFe=({createOpen:t,onCreateOpenChange:e,onCount:n})=>{var Te,se;const s=cs(),{isPinned:r,togglePin:a}=Z1(),[o,l]=_.useState([]),[c,d]=_.useState(""),[u,h]=_.useState({status:[],project:[]}),f=((Te=u.status)==null?void 0:Te[0])??"all",p=((se=u.project)==null?void 0:se[0])??"all",[x,v]=_.useState(!1),m=t??x,g=_.useCallback(W=>{e?e(W):v(W)},[e]),[y,b]=_.useState(null),[S,E]=_.useState(""),[k,T]=_.useState(!0),[A,M]=_.useState("list"),[N,L]=_.useState([]),{showError:I,AlertComponent:D}=Jh(),z=Object.fromEntries(N.map(W=>[W.id,W.name])),{isConnected:U,tier:G}=XFe(),{getAccessToken:K}=jm(),P=U&&G==="pro"?K():null,B=_.useMemo(()=>o.map(W=>({id:W.id,name:W.name,memberCount:W.members.length})),[o]),R=U&&G==="pro",{devices:F,isLoading:q,refresh:$}=qFe(P,R,B,typeof window<"u"&&window.location.hostname||"My Device"),re=_.useMemo(()=>{let W=o;return c&&(W=W.filter(ae=>{var ee;return ae.name.toLowerCase().includes(c.toLowerCase())||ae.description&&ae.description.toLowerCase().includes(c.toLowerCase())||((ee=ae.projectIds)==null?void 0:ee.length)>0&&ae.projectIds.some(le=>le.toLowerCase().includes(c.toLowerCase()))||ae.members.some(le=>le.name.toLowerCase().includes(c.toLowerCase())||le.role.toLowerCase().includes(c.toLowerCase()))})),f!=="all"&&(W=W.filter(ae=>f==="active"?ae.members.some(ee=>ee.agentStatus==="active"):f==="inactive"?!ae.members.some(ee=>ee.agentStatus==="active"):!0)),p!=="all"&&(W=W.filter(ae=>{var ee;return(ee=ae.projectIds)==null?void 0:ee.includes(p)})),W=W.filter(ae=>!ae.parentTeamId),W},[o,c,f,p]),ne=_.useMemo(()=>{const W=new Map;for(const ae of o)ae.parentTeamId&&W.set(ae.parentTeamId,(W.get(ae.parentTeamId)||0)+1);return W},[o]),J=_.useCallback(W=>{l(ae=>ae.map(ee=>ee.id===W.teamId?{...ee,members:ee.members.map(le=>le.id===W.memberId||le.sessionName===W.sessionName?{...le,agentStatus:W.agentStatus}:le)}:ee))},[]);_.useEffect(()=>{X(),H()},[]),_.useEffect(()=>(jt.on("team_member_status_changed",J),()=>{jt.off("team_member_status_changed",J)}),[J]);const H=async()=>{try{const W=await lt.getProjects();L(W.map(ae=>({id:ae.id,name:ae.name})))}catch(W){Na(W,{context:"Loading projects for filter"})}},X=async()=>{try{const ae=(await lt.getTeams()).map(ee=>({...ee,members:qR(ee.members)}));l(ae)}catch(W){Na(W,{context:"fetchTeams"}),l([])}finally{T(!1)}},Z=async W=>{try{const ae=await lt.createTeam(W);l(ee=>[...ee,ae]),g(!1)}catch(ae){Na(ae,{context:"handleCreateTeam"}),I("Error creating team: "+(ae instanceof Error?ae.message:"Unknown error"))}},oe=async W=>{try{await lt.startTeam(W)}catch(ae){Na(ae,{context:"handleStartTeam"}),I("Failed to start team: "+(ae instanceof Error?ae.message:"Unknown error"))}},ye=async W=>{try{await lt.stopTeam(W)}catch(ae){Na(ae,{context:"handleStopTeam"}),I("Failed to stop team: "+(ae instanceof Error?ae.message:"Unknown error"))}},[Q,Ce]=_.useState(null),[ie,ge]=_.useState(!1),he=async W=>{if(Q){ge(!0);try{await lt.pauseTeam(Q.id,W),Ce(null),await X()}catch(ae){I("Failed to pause team: "+(ae instanceof Error?ae.message:"Unknown error"))}finally{ge(!1)}}},ke=async W=>{try{await lt.resumeTeam(W),await X()}catch(ae){I("Failed to resume team: "+(ae instanceof Error?ae.message:"Unknown error"))}},Y=async W=>{try{await lt.deleteTeam(W),l(ae=>ae.filter(ee=>ee.id!==W))}catch(ae){I("Failed to delete team: "+(ae instanceof Error?ae.message:"Unknown error"))}},Ae=_.useMemo(()=>o.filter(W=>!W.parentTeamId),[o]);_.useEffect(()=>{k||n==null||n(Ae.length)},[k,Ae.length,n]);const Ee=()=>{b(null),E("")};if(k)return i.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:i.jsx(zt,{size:"xl",text:"Loading teams..."})});const _e=!!c||f!=="all"||p!=="all";return i.jsxs("div",{"data-testid":"teams-list-page",children:[i.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2","data-testid":"teams-toolbar",children:[i.jsx(Zo,{value:u,onChange:h,groups:[{id:"status",label:"Status",single:!0,options:[{value:"active",label:"Active",count:Ae.filter(i6).length},{value:"inactive",label:"Idle",count:Ae.filter(W=>!i6(W)).length}]},...N.length>0?[{id:"project",label:"Project",single:!0,options:N.map(W=>({value:W.id,label:W.name}))}]:[]]}),i.jsx(YR,{label:"Search teams",value:c,onChange:d}),i.jsxs("div",{className:"ml-auto flex items-center gap-1",role:"group","aria-label":"View",children:[i.jsx(Zt,{icon:Cee,size:"xs","aria-label":"List view",title:"List view","aria-pressed":A==="list",className:A==="list"?"text-primary-text bg-primary-soft":"text-text-2",onClick:()=>M("list")}),i.jsx(Zt,{icon:S0,size:"xs","aria-label":"Tree view",title:"Tree view (parent and sub-teams)","aria-pressed":A==="tree",className:A==="tree"?"text-primary-text bg-primary-soft":"text-text-2",onClick:()=>M("tree")})]})]}),A==="tree"?o.length>0&&i.jsx(HFe,{teams:o,projectMap:z,onTeamClick:W=>s(qt.team(W))}):re.length>0?i.jsx("div",{className:"rounded-2xl border border-border-soft","data-testid":"teams-list",children:i.jsx(fs,{limit:YFe,"data-testid":"teams-show-all",children:re.map(W=>{var ae;return i.jsx(WFe,{team:W,projectName:((ae=W.projectIds)==null?void 0:ae.length)>0?z[W.projectIds[0]]:void 0,subTeamCount:ne.get(W.id),onOpen:ee=>s(qt.team(ee)),onEdit:ee=>s(`${qt.team(ee)}?edit=true`),onStart:oe,onStop:ye,onOpenChat:ee=>s(`${Yt.chat}?${Gd}=${ee}`),onOpenWiki:ee=>s(`${Yt.wiki}?${Gd}=${ee}`),onDelete:Y,isPinned:r(W.id),onTogglePin:()=>a({id:W.id,name:W.name,type:"team"}),onPause:()=>Ce(W),onResume:ke},W.id)})})}):i.jsx(is,{icon:vr,title:"No teams found",description:_e?"Try adjusting your search or filters":"Create your first team to get started",action:_e?void 0:i.jsx(de,{variant:"primary",icon:qn,onClick:()=>g(!0),children:"Create Team"}),className:"py-16"}),R&&i.jsxs(ni,{title:`Online devices (${F.length})`,summary:"Other machines on your account and their teams",className:"mt-8","data-testid":"online-devices",children:[i.jsx("div",{className:"mb-3 flex justify-end",children:i.jsx(Zt,{icon:$t,size:"xs",onClick:$,title:"Refresh devices","aria-label":"Refresh devices"})}),q?i.jsx(zt,{size:"sm",text:"Discovering devices..."}):F.length===0?i.jsx(is,{compact:!0,icon:Tm,title:"No other devices online",description:"Other Pro users will appear here when they are online"}):i.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:F.map(W=>i.jsxs(tn,{padding:"md",children:[i.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[i.jsx(NR,{status:"online",size:"sm",pulse:!0}),i.jsx("span",{className:"truncate text-sm font-semibold text-text",children:W.deviceName})]}),i.jsx("p",{className:"mb-3 truncate text-xs text-text-2",children:W.email}),W.teams.length>0&&i.jsx("ul",{className:"space-y-1 text-[13px]",children:W.teams.map(ae=>i.jsxs("li",{className:"flex items-center justify-between gap-2",children:[i.jsx("span",{className:"truncate text-text",children:ae.name}),i.jsxs("span",{className:"shrink-0 text-text-2",children:[ae.memberCount," member",ae.memberCount!==1?"s":""]})]},ae.id))})]},W.deviceId))})]}),i.jsx(V$,{isOpen:m,onClose:()=>g(!1),onSubmit:Z}),y&&S&&i.jsx(OFe,{member:y,teamId:S,onClose:Ee}),i.jsx(B$,{isOpen:!!Q,teamName:(Q==null?void 0:Q.name)??"",issueRepo:Q==null?void 0:Q.issueRepo,busy:ie,onCancel:()=>Ce(null),onConfirm:he}),i.jsx(D,{})]})},ZFe={teams:"Teams",goals:"Goals"},QFe={teams:"Your crews and the goals they work toward",goals:"Company → team → project goals and their key results"},e4e=()=>{const[t,e]=uu(jO),[n,s]=Pc(),[r,a]=_.useState(!1),[o,l]=_.useState(!1),[c,d]=_.useState(0),[u,h]=_.useState(null),[f,p]=_.useState(null);_.useEffect(()=>{if(n.get("create")!=="true")return;t==="goals"?l(!0):a(!0);const g=new URLSearchParams(n);g.delete("create"),s(g,{replace:!0})},[n,s,t]);const x=_.useCallback(g=>h(g),[]),v=_.useCallback(g=>p(g),[]),m=t==="teams"?i.jsx(de,{variant:"primary",icon:qn,onClick:()=>a(!0),"data-testid":"teams-new",children:"New team"}):i.jsxs(i.Fragment,{children:[i.jsx(de,{variant:"primary",icon:qn,onClick:()=>l(!0),"data-testid":"missions-new",children:"New goal"}),i.jsx(Co,{icon:pa,label:"More goal actions",buttonClassName:"inline-flex h-10 w-10 items-center justify-center rounded-2xl border border-border-soft text-text-2 transition-colors hover:bg-surface-hover hover:text-text",items:[{label:"Refresh",onClick:()=>d(g=>g+1)}]})]});return i.jsxs("div",{className:"p-6 max-w-5xl mx-auto",children:[i.jsx(_r,{title:"Teams",subtitle:QFe[t],actions:m,tabs:i.jsx(Oc,{"aria-label":"Teams views",idPrefix:"teams",value:t,onChange:g=>e(g),tabs:jO.map(g=>({value:g,label:ZFe[g],count:g==="teams"?u:f?f.pending>0?f.pending:f.total:null,attention:g==="goals"&&((f==null?void 0:f.pending)??0)>0}))})}),i.jsxs("div",{role:"tabpanel",id:`teams-panel-${t}`,"aria-labelledby":`teams-tab-${t}`,"data-testid":`teams-panel-${t}`,children:[t==="teams"&&i.jsx(JFe,{createOpen:r,onCreateOpenChange:a,onCount:x}),t==="goals"&&i.jsx(SX,{createOpen:o,onCreateOpenChange:l,refreshKey:c,onCounts:v})]})]})},tj="connector",t4e=[{label:"Skills",value:"skill"},{label:"3D Models",value:"model"},{label:"Roles",value:"role"},{label:"MCP Tools",value:"mcp_tool"},{label:"Connectors",value:tj}],n4e=[{label:"Popular",value:"popular"},{label:"Highest Rated",value:"rating"},{label:"Newest",value:"newest"}],GX=5;function a6({view:t="browse",onPendingCount:e}={}){const{toasts:n,addToast:s,dismissToast:r}=AK();return i.jsxs(i.Fragment,{children:[t==="browse"?i.jsx(s4e,{addToast:s}):i.jsx(o4e,{addToast:s,onPendingCount:e}),i.jsx(TK,{toasts:n,onDismiss:r})]})}function s4e({addToast:t}){var A,M;const e=cs(),[n,s]=_.useState([]),[r,a]=_.useState(!0),[o,l]=_.useState(null),[c,d]=_.useState({}),[u,h]=_.useState(""),[f,p]=_.useState(null),x=((A=c.type)==null?void 0:A[0])??"all",v=((M=c.sort)==null?void 0:M[0])??"popular",m=_.useCallback(async()=>{try{a(!0),l(null);const N=await ZNe({type:x==="all"||x===tj?void 0:x,search:u||void 0,sort:v});s(N)}catch{l("Failed to load marketplace items")}finally{a(!1)}},[x,u,v]);_.useEffect(()=>{m()},[m]);const g=async(N,L,I,D)=>{p(N);try{const z=await L(N);t(z.message||`${I} ${N}`,z.success?"success":"error"),await m()}catch(z){t(z instanceof Error?z.message:D,"error")}p(null)},y=N=>g(N,wK,"Installed","Install failed"),b=N=>g(N,EK,"Uninstalled","Uninstall failed"),S=N=>g(N,eMe,"Updated","Update failed"),E=async()=>{try{await CK(),t("Registry refreshed","success"),await m()}catch{t("Failed to refresh registry","error")}},k=N=>e(`${Yt.marketplace}/${encodeURIComponent(N)}`),T=N=>RL.filter(L=>L.group===N).filter(L=>!u.trim()||`${L.name} ${L.description}`.toLowerCase().includes(u.trim().toLowerCase()));return i.jsxs("div",{className:"space-y-5","data-testid":"marketplace-browse",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx("label",{htmlFor:"marketplace-search",className:"sr-only",children:"Search marketplace"}),i.jsxs("div",{className:"relative min-w-0 flex-1 basis-56",children:[i.jsx(Tl,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-3","aria-hidden":"true"}),i.jsx("input",{id:"marketplace-search",type:"text",placeholder:"Search...",value:u,onChange:N=>h(N.target.value),className:"h-9 w-full rounded-2xl border border-border bg-surface pl-9 pr-3 text-sm text-text placeholder:text-text-3 focus:border-primary focus:outline-none"})]}),i.jsx(Zo,{value:c,onChange:d,groups:[{id:"type",label:"Type",single:!0,options:t4e},{id:"sort",label:"Sort",single:!0,options:n4e}]}),i.jsx(Zt,{icon:$t,variant:"outline",onClick:()=>void E(),"aria-label":"Refresh marketplace",title:"Refresh marketplace"})]}),x===tj?i.jsxs("div",{className:"space-y-6","data-testid":"marketplace-connectors",children:[i.jsxs("p",{className:"text-[13px] text-text-2",children:["Connectors are not installed — you authorise them against your own account, and can revoke them at any time. Manage them on"," ",i.jsx(hs,{to:Yt.connections,className:"font-semibold text-primary-text hover:underline",children:"Connections"}),"."]}),bK.map(N=>{const L=T(N.id);return L.length===0?null:i.jsxs("section",{"aria-label":N.title,className:"space-y-2",children:[i.jsx("h2",{className:"px-1 text-[15px] font-semibold text-text",children:N.title}),i.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-soft bg-surface",children:L.map(I=>i.jsx(Ts,{"data-testid":`marketplace-connector-${I.id}`,leading:i.jsx(lR,{className:"h-4 w-4 text-text-3","aria-hidden":"true"}),primary:I.name,meta:I.description,actions:[i.jsx(hs,{to:`${Yt.connections}?platform=${I.id}`,className:"inline-flex h-8 items-center rounded-2xl bg-primary-soft px-3 text-sm font-semibold text-primary-text transition-colors hover:bg-primary/20",children:"Connect →"},"connect")]},I.id))})]},N.id)})]}):r?i.jsx(zt,{size:"md",text:"Loading marketplace...",className:"py-16"}):o?i.jsx(Ye,{variant:"error",children:o}):n.length===0?i.jsx(is,{icon:oR,title:"No items found."}):i.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-soft bg-surface",children:i.jsx(fs,{limit:GX,children:n.map(N=>i.jsx(r4e,{item:N,busy:f===N.id,onOpen:()=>k(N.id),onInstall:()=>void y(N.id),onUninstall:()=>void b(N.id),onUpdate:()=>void S(N.id)},N.id))})})]})}function r4e({item:t,busy:e,onOpen:n,onInstall:s,onUninstall:r,onUpdate:a}){const o=[{label:"View details",icon:YH,onClick:n}];let l,c=null;return t.installStatus==="not_installed"?l=[i.jsx(de,{variant:"primary",size:"sm",icon:oR,onClick:s,loading:e,children:e?"Installing...":"Install"},"install")]:t.installStatus==="installed"?(c=i.jsx(sn,{tone:"success",size:"sm",children:"Installed"}),l=[i.jsx(de,{variant:"outline",size:"sm",onClick:r,loading:e,children:e?"Removing...":"Uninstall"},"uninstall")]):t.installStatus==="update_available"&&(c=i.jsx(sn,{tone:"attention",size:"sm",children:"Update available"}),l=[i.jsx(de,{variant:"primary",size:"sm",icon:U1,onClick:a,loading:e,children:e?"Updating...":"Update"},"update"),i.jsx(de,{variant:"outline",size:"sm",onClick:r,disabled:e,children:"Remove"},"remove")]),i.jsx(Ts,{"data-testid":`marketplace-item-${t.id}`,primary:t.name,meta:i.jsxs(i.Fragment,{children:[i.jsx("span",{children:NK[t.type]??t.type}),i.jsx("span",{"aria-hidden":"true",children:" · "}),i.jsxs("span",{children:["by ",t.author]}),t.description&&i.jsxs(i.Fragment,{children:[i.jsx("span",{"aria-hidden":"true",children:" · "}),i.jsx("span",{title:t.description,children:t.description})]})]}),onClick:n,trailing:c,actions:l,overflow:o,overflowLabel:`More actions for ${t.name}`})}const i4e={pending:"attention",approved:"success",rejected:"danger"},a4e={pending:"Pending review",approved:"Approved",rejected:"Rejected"};function o4e({addToast:t,onPendingCount:e}){const[n,s]=_.useState([]),[r,a]=_.useState(!0),[o,l]=_.useState(null),[c,d]=_.useState(null),[u,h]=_.useState(null),f=_.useCallback(async()=>{try{a(!0),l(null);const x=await kK();s(x),e==null||e(x.filter(v=>v.status==="pending").length)}catch{l("Failed to load submissions")}finally{a(!1)}},[e]);_.useEffect(()=>{f()},[f]);const p=async(x,v)=>{d(x);try{const m=await tMe(x,v);t(m.message||`${v==="approve"?"Approved":"Rejected"}`,m.success?"success":"error"),await f(),v==="approve"&&await CK()}catch(m){t(m instanceof Error?m.message:"Review failed","error")}d(null)};return i.jsxs("div",{className:"space-y-5","data-testid":"marketplace-submissions",children:[i.jsxs("p",{className:"text-[13px] text-text-2",children:["Submit skills via CLI:"," ",i.jsx("code",{className:"rounded bg-surface-2 px-2 py-0.5 font-mono text-xs text-text",children:"crewly publish path/to/skill --submit"})]}),r?i.jsx(zt,{size:"md",text:"Loading submissions...",className:"py-16"}):o?i.jsx(Ye,{variant:"error",children:o}):n.length===0?i.jsx(is,{icon:lG,title:"No submissions yet."}):i.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-soft bg-surface",children:i.jsx(fs,{limit:GX,children:n.map(x=>{const v=c===x.id,m=u===x.id;return i.jsxs("div",{className:"border-b border-border-soft last:border-b-0","data-testid":`submission-${x.id}`,children:[i.jsx(Ts,{className:"border-b-0",primary:x.name,meta:`by ${x.author} · ${x.category} · ${uw(x.submittedAt)||new Date(x.submittedAt).toLocaleDateString()}`,onClick:()=>h(m?null:x.id),selected:m,trailing:i.jsx(sn,{tone:i4e[x.status]??"danger",size:"sm",children:a4e[x.status]??x.status}),actions:x.status==="pending"?[i.jsx(de,{variant:"success",size:"sm",onClick:()=>void p(x.id,"approve"),loading:v,children:v?"...":"Approve"},"approve"),i.jsx(de,{variant:"outline",size:"sm",onClick:()=>void p(x.id,"reject"),disabled:v,children:"Reject"},"reject")]:void 0}),m&&i.jsxs("div",{className:"space-y-2 px-4 pb-4 text-sm","data-testid":`submission-detail-${x.id}`,children:[i.jsx("p",{className:"text-text-2",children:x.description}),i.jsxs("p",{className:"text-[13px] text-text-3",children:["Version ",x.version," · submitted ",new Date(x.submittedAt).toLocaleString()]}),x.reviewNotes&&i.jsxs("p",{className:"text-[13px] italic text-text-2",children:["Review: ",x.reviewNotes]})]})]},x.id)})})})]})}const $X=[{value:"",label:"All Categories"},...Qde.map(t=>({value:t,label:H$(t)}))],l4e=5,c4e=({skill:t,onSave:e,onClose:n})=>{const s=(t==null?void 0:t.isBuiltin)??!1,[r,a]=_.useState({name:(t==null?void 0:t.name)||"",displayName:(t==null?void 0:t.name)||"",description:(t==null?void 0:t.description)||"",category:(t==null?void 0:t.category)||"development",promptContent:(t==null?void 0:t.promptContent)||"",triggers:[],tags:[]}),[o,l]=_.useState(!1),[c,d]=_.useState(null),u=async f=>{if(f.preventDefault(),d(null),!r.displayName.trim()){d("Display Name is required");return}if(!r.name.trim()){d("ID is required");return}if(!r.description.trim()){d("Description is required");return}l(!0);try{await e(r)}catch(p){d(p instanceof Error?p.message:"Failed to save skill")}finally{l(!1)}},h=i.jsxs(i.Fragment,{children:[i.jsx(de,{variant:"secondary",onClick:n,type:"button",children:"Cancel"}),i.jsx(de,{type:"submit",onClick:u,disabled:o,loading:o,children:o?"Saving...":"Save Skill"})]});return i.jsx(Xi,{isOpen:!0,onClose:n,title:t?"Edit Skill":"Create Skill",subtitle:t?"Modify skill configuration":"Configure a new skill for your agents",size:"lg",footer:h,children:i.jsxs("div",{className:"-m-6 max-h-[65vh] overflow-y-auto",children:[s&&t&&i.jsxs(Ye,{variant:"info",className:"mx-6 mt-4",children:[i.jsx("strong",{children:"Built-in Skill:"})," Changes will be saved as a user override. You can reset to defaults anytime."]}),c&&i.jsx("div",{className:"mx-6 mt-4",children:i.jsx(Ye,{variant:"error",children:c})}),i.jsxs("form",{onSubmit:u,className:"p-6 space-y-4",children:[i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-display-name",required:!0,children:"Display Name"}),i.jsx(Dt,{id:"skill-display-name",type:"text",value:r.displayName,onChange:f=>a({...r,displayName:f.target.value}),placeholder:"Code Review",required:!0})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-name",required:!0,children:"ID"}),i.jsx(Dt,{id:"skill-name",type:"text",value:r.name,onChange:f=>a({...r,name:f.target.value}),placeholder:"code-review",required:!0,disabled:!!t}),i.jsx("p",{className:"text-xs text-text-2 mt-1",children:"Lowercase letters, numbers, and hyphens only"})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-description",required:!0,children:"Description"}),i.jsx(er,{id:"skill-description",value:r.description,onChange:f=>a({...r,description:f.target.value}),placeholder:"Describe what this skill does...",rows:3,required:!0})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-category",children:"Category"}),i.jsx(xn,{id:"skill-category",value:r.category,onChange:f=>a({...r,category:f.target.value}),children:$X.filter(f=>f.value).map(f=>i.jsx("option",{value:f.value,children:f.label},f.value))})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-prompt",children:"Instructions (Markdown)"}),i.jsx(er,{id:"skill-prompt",value:r.promptContent,onChange:f=>a({...r,promptContent:f.target.value}),placeholder:`# Skill Instructions
4953
4953
 
4954
4954
  Provide detailed instructions for this skill...`,rows:8,className:"font-mono text-sm"})]})]})]})})},d4e=({skillName:t,onConfirm:e,onCancel:n})=>i.jsx(zte,{isOpen:!0,onClose:n,onConfirm:e,title:"Delete Skill",confirmText:"Delete",confirmVariant:"danger",message:i.jsxs("p",{className:"text-text-2",children:["Are you sure you want to delete ",i.jsx("strong",{className:"text-text",children:t}),"? This action cannot be undone."]})});function u4e(t){var n,s;if(!t.enableBrowserAutomation)return"Off";const e=["On"];return(n=t.browserProfile)!=null&&n.headless&&e.push("headless"),(s=t.browserProfile)!=null&&s.stealth&&e.push("stealth"),e.join(" · ")}const h4e=()=>{const{settings:t,updateSettings:e}=CL(),[n,s]=_.useState(null),[r,a]=_.useState(!1),[o,l]=_.useState("idle");if(_.useEffect(()=>{t&&(s(t.skills),a(!1))},[t]),!n)return null;const c=(h,f)=>{s({...n,[h]:f}),a(!0),l("idle")},d=(h,f)=>{s({...n,browserProfile:{...n.browserProfile,[h]:f}}),a(!0),l("idle")},u=async()=>{l("saving");try{await e({skills:n}),l("saved"),a(!1),setTimeout(()=>l("idle"),2e3)}catch{l("error")}};return i.jsx(ni,{title:i.jsxs("span",{className:"inline-flex items-center gap-2",children:[i.jsx(Tm,{className:"h-4 w-4 text-text-3","aria-hidden":"true"}),"Browser Automation"]}),summary:u4e(n),"data-testid":"browser-automation-settings",children:i.jsxs("div",{className:"space-y-5 pt-2",children:[i.jsx(vi,{id:"enableBrowserAutomation",label:"Enable Browser Automation",description:"Allow agents to use Playwright for browser tasks (navigate, click, screenshot, etc.)",checked:n.enableBrowserAutomation,onChange:h=>c("enableBrowserAutomation",h.target.checked)}),n.enableBrowserAutomation&&n.browserProfile&&i.jsxs("div",{className:"space-y-4 border-l-2 border-border-soft pl-4",children:[i.jsx(vi,{id:"headless",label:"Headless Mode",description:"Run browser invisibly in the background (recommended)",checked:n.browserProfile.headless,onChange:h=>d("headless",h.target.checked)}),i.jsx(vi,{id:"stealth",label:"Stealth Mode",description:"Use anti-detection features to avoid bot blocking (uses community fork)",checked:n.browserProfile.stealth,onChange:h=>d("stealth",h.target.checked)}),i.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"humanDelayMin",children:"Min Delay (ms)"}),i.jsx(Dt,{id:"humanDelayMin",type:"number",min:0,max:n.browserProfile.humanDelayMaxMs,value:n.browserProfile.humanDelayMinMs,onChange:h=>d("humanDelayMinMs",parseInt(h.target.value,10)||0)}),i.jsx("p",{className:"mt-1 text-xs text-text-2",children:"Minimum delay between actions"})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"humanDelayMax",children:"Max Delay (ms)"}),i.jsx(Dt,{id:"humanDelayMax",type:"number",min:n.browserProfile.humanDelayMinMs,max:1e4,value:n.browserProfile.humanDelayMaxMs,onChange:h=>d("humanDelayMaxMs",parseInt(h.target.value,10)||0)}),i.jsx("p",{className:"mt-1 text-xs text-text-2",children:"Maximum delay between actions"})]})]})]}),i.jsxs("div",{className:"flex items-center justify-end gap-3",children:[o==="saved"&&i.jsxs("span",{className:"flex items-center gap-1 text-sm text-success",children:[i.jsx(rs,{className:"h-4 w-4","aria-hidden":"true"})," Saved"]}),o==="error"&&i.jsxs("span",{className:"flex items-center gap-1 text-sm text-danger",children:[i.jsx(Si,{className:"h-4 w-4","aria-hidden":"true"})," Save failed"]}),i.jsx(de,{onClick:u,disabled:!r||o==="saving",icon:Xd,size:"sm",children:o==="saving"?"Saving...":"Save"})]})]})})},o6={info:{icon:qd,text:"text-primary-text"},warning:{icon:Kd,text:"text-attention"},requirement:{icon:Si,text:"text-danger"}};function f4e(t){const e=H$(t.category),n=[e.charAt(0).toUpperCase()+e.slice(1),t.isBuiltin?"Built-in":"Custom"];return t.skillType==="web-page"&&n.push(eue("web-page")),n.join(" · ")}const p4e=({onCountChange:t})=>{var R,F;const[e,n]=_.useState({}),[s,r]=_.useState(""),[a,o]=_.useState(null),[l,c]=_.useState(!1),[d,u]=_.useState(null),[h,f]=_.useState(null),[p,x]=_.useState(null),[v,m]=_.useState(null),g=((R=e.category)==null?void 0:R[0])??"",y=_.useMemo(()=>({category:g||void 0,search:s||void 0}),[g,s]),{skills:b,loading:S,error:E,refresh:k,create:T,update:A,remove:M,selectSkill:N,selectedSkill:L,clearSelection:I}=uE(y),D=!!(s||g);_.useEffect(()=>{!D&&!S&&(t==null||t(b.length))},[D,S,b.length,t]);const z=b.filter(q=>!q.isEnabled).length,U=_.useCallback(()=>{u(null),c(!0)},[]),G=_.useCallback(async q=>{u(q),await N(q.id),c(!0)},[N]),K=_.useCallback(async q=>{try{d!=null&&d.id?await A(d.id,q):await T(q),c(!1),u(null)}catch($){console.error("Failed to save skill:",$)}},[d,A,T]),P=_.useCallback(async q=>{try{await M(q),f(null)}catch($){console.error("Failed to delete skill:",$)}},[M]),B=_.useCallback(async(q,$)=>{x(q.id),m(null);try{await A(q.id,{isEnabled:$})}catch(re){m(re instanceof Error?re.message:`Could not ${$?"enable":"disable"} ${q.name}`)}finally{x(null)}},[A]);return i.jsxs("div",{className:"space-y-6","data-testid":"installed-skills",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx("label",{htmlFor:"search-filter",className:"sr-only",children:"Search skills"}),i.jsxs("div",{className:"relative min-w-0 flex-1 basis-56",children:[i.jsx(Tl,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-3","aria-hidden":"true"}),i.jsx("input",{id:"search-filter",type:"text",placeholder:"Search skills...",value:s,onChange:q=>r(q.target.value),className:"h-9 w-full rounded-2xl border border-border bg-surface pl-9 pr-3 text-sm text-text placeholder:text-text-3 focus:border-primary focus:outline-none"})]}),i.jsx(Zo,{value:e,onChange:n,groups:[{id:"category",label:"Category",single:!0,options:$X.filter(q=>q.value).map(q=>({value:q.value,label:q.label}))}]}),i.jsx(Zt,{icon:$t,variant:"outline",onClick:()=>void k(),loading:S,disabled:S,"aria-label":"Refresh skills",title:"Refresh skills"}),i.jsx(de,{onClick:U,icon:qn,size:"sm",children:"New Skill"})]}),!S&&b.length>0&&i.jsxs("p",{className:"-mt-3 px-1 text-[13px] text-text-2","data-testid":"installed-summary",children:[b.length," ",D?"shown":"installed",z>0?` · ${z} disabled`:" · all enabled"]}),E&&i.jsx(Ye,{variant:"error",children:i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsxs("span",{children:["Error: ",E]}),i.jsx(de,{variant:"outline",size:"sm",onClick:()=>void k(),children:"Retry"})]})}),v&&i.jsx(Ye,{variant:"error",children:v}),S&&b.length===0&&i.jsx("div",{className:"flex justify-center py-16",children:i.jsx(zt,{text:"Loading skills..."})}),!S&&b.length===0&&!E&&i.jsxs("div",{className:"py-12 text-center",children:[i.jsx(ay,{className:"mx-auto mb-3 h-10 w-10 text-text-3","aria-hidden":"true"}),i.jsx("h3",{className:"mb-1 text-[15px] font-semibold text-text",children:"No Skills Found"}),i.jsx("p",{className:"mb-5 text-sm text-text-2",children:D?"Try adjusting your filters":"Create your first skill to get started"}),!D&&i.jsx(de,{onClick:U,icon:qn,size:"sm",children:"Create Skill"})]}),b.length>0&&i.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-soft bg-surface",children:i.jsx(fs,{limit:l4e,children:b.map(q=>i.jsx(m4e,{skill:q,open:a===q.id,busy:p===q.id,onOpen:()=>o($=>$===q.id?null:q.id),onEdit:()=>void G(q),onDelete:()=>f(q.id),onToggle:$=>void B(q,$)},q.id))})}),i.jsx(h4e,{}),l&&i.jsx(c4e,{skill:L||d,onSave:K,onClose:()=>{c(!1),u(null),I()}}),h&&i.jsx(d4e,{skillId:h,skillName:((F=b.find(q=>q.id===h))==null?void 0:F.name)||"",onConfirm:()=>void P(h),onCancel:()=>f(null)})]})},m4e=({skill:t,open:e,busy:n,onOpen:s,onEdit:r,onDelete:a,onToggle:o})=>{var u,h;const l=(u=t.notices)==null?void 0:u.some(f=>f.type==="requirement"),c=t.isEnabled?l?i.jsx(sn,{tone:"attention",size:"sm",children:"Needs setup"}):null:i.jsx(sn,{tone:"neutral",size:"sm",children:"Disabled"}),d=t.isBuiltin?i.jsx("span",{className:"hidden text-xs text-text-3 sm:inline",title:"Built-in skills are always available",children:"Built-in"}):i.jsx(vi,{size:"sm",checked:t.isEnabled,disabled:n,onChange:f=>o(f.target.checked),"aria-label":`Enable ${t.name}`});return i.jsxs("div",{className:"border-b border-border-soft last:border-b-0","data-testid":`installed-skill-${t.id}`,children:[i.jsx(Ts,{className:"border-b-0",primary:t.name,meta:f4e(t),onClick:s,selected:e,trailing:c,actions:[d,i.jsx(Zt,{icon:Lh,onClick:r,variant:"ghost",size:"sm","aria-label":`Edit ${t.name}`,title:"Edit"},"edit")],overflow:[{label:"Edit",icon:Lh,onClick:r},...t.isBuiltin?[]:[{label:"Delete",icon:Qs,danger:!0,separator:!0,onClick:a}]],overflowLabel:`More actions for ${t.name}`}),e&&i.jsxs("div",{className:"space-y-3 px-4 pb-4 pl-4 sm:pl-6","data-testid":`installed-skill-detail-${t.id}`,children:[i.jsx("p",{className:"text-sm text-text-2",children:t.description}),(h=t.notices)==null?void 0:h.map((f,p)=>{const x=o6[f.type]??o6.info,v=x.icon;return i.jsxs("div",{className:"flex gap-2 text-[13px]",children:[i.jsx(v,{className:`mt-0.5 h-4 w-4 shrink-0 ${x.text}`,"aria-hidden":"true"}),i.jsxs("div",{children:[i.jsx("span",{className:"block font-semibold text-text",children:f.title}),i.jsx("span",{className:"block text-text-2",children:f.message}),f.link&&i.jsxs("a",{href:f.link,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-primary-text hover:underline",children:[f.linkText||"Learn more",i.jsx(Is,{className:"h-3 w-3","aria-hidden":"true"})]})]})]},p)}),!t.isBuiltin&&i.jsx(de,{variant:"ghost",size:"xs",icon:Qs,className:"text-danger",onClick:a,children:"Delete skill"})]})]})},g4e={browse:"Browse",installed:"Installed",submissions:"Submissions"},x4e=()=>{const[t,e]=uu(RO),[n,s]=_.useState(void 0),[r,a]=_.useState(void 0);_.useEffect(()=>{let l=!1;return kK("pending").then(c=>{l||a(c.filter(d=>d.status==="pending").length)}).catch(()=>{}),()=>{l=!0}},[]);const o=l=>l==="installed"&&n!==void 0?{count:n}:l==="submissions"&&r?{count:r,attention:!0}:{};return i.jsxs("div",{className:"max-w-5xl",children:[i.jsx(_r,{title:"Marketplace",subtitle:"Browse and install skills, roles, tools and models, and manage the ones you have",tabs:i.jsx(Oc,{"aria-label":"Marketplace views",idPrefix:"marketplace",value:t,onChange:l=>e(l),tabs:RO.map(l=>({value:l,label:g4e[l],...o(l)}))})}),i.jsxs("div",{role:"tabpanel",id:`marketplace-panel-${t}`,"aria-labelledby":`marketplace-tab-${t}`,"data-testid":`marketplace-panel-${t}`,children:[t==="browse"&&i.jsx(a6,{view:"browse"}),t==="installed"&&i.jsx(p4e,{onCountChange:s}),t==="submissions"&&i.jsx(a6,{view:"submissions",onPendingCount:a})]})]})},y4e=({rule:t})=>{const e=Lc(),{search:n,hash:s}=wi();return i.jsx(LH,{to:hre(t.to(e),n,s),replace:!0})},v4e=()=>{},b4e=({onSaved:t})=>{const[e,n]=_.useState(!1),[s,r]=_.useState(""),[a,o]=_.useState(!1);_.useEffect(()=>{const c=()=>{o(!!py()),n(!0)};return window.addEventListener(PM,c),()=>window.removeEventListener(PM,c)},[]);const l=_.useCallback(c=>{c.preventDefault();const d=s.trim();d&&(U9(d),n(!1),t?t():window.location.reload())},[s,t]);return e?i.jsx("div",{className:"relative z-[100]",children:i.jsx(Pr,{isOpen:!0,onClose:v4e,closable:!1,title:"Access token required",size:"md","data-testid":"api-token-prompt",children:i.jsxs("form",{onSubmit:l,className:"space-y-4",children:[i.jsxs("p",{className:"text-sm text-text-secondary-dark leading-relaxed",children:[a?"The stored access token was rejected. Paste the current token to continue.":"This dashboard is being opened from another machine. Paste the access token to continue."," ","Run ",i.jsx("code",{className:"font-mono",children:"crewly token"})," on the server to print it (or ",i.jsx("code",{className:"font-mono",children:"crewly token --url"})," for a ready-to-open link)."]}),i.jsx(ss,{id:"api-token-input",label:"Access token",type:"password",value:s,onChange:c=>r(c.target.value),placeholder:"paste token",autoComplete:"off",autoFocus:!0,fullWidth:!0,className:"font-mono","data-testid":"api-token-input"}),i.jsx("div",{className:"flex justify-end",children:i.jsx(de,{type:"submit",icon:sy,disabled:!s.trim(),"data-testid":"api-token-submit",children:"Save and reload"})})]})})}):null};function _4e(t){if(!t.orcHarness)return!0;const e=t.harnesses.find(n=>n.id===t.orcHarness);return e?e.installed?e.loginState==="logged_out":!0:!1}function l6(t){return!Lae.some(e=>t===e||t.startsWith(`${e}/`))}function c6(){try{return window.localStorage.getItem(FM)==="1"}catch{return!1}}function S4e(t){try{t?window.localStorage.setItem(FM,"1"):window.localStorage.removeItem(FM)}catch{}}const w4e=()=>{const t=wi(),e=cs(),n=_.useRef(t.pathname);return n.current=t.pathname,_.useEffect(()=>{if(c6()||!l6(n.current))return;let s=!1;return go.getStatus().then(r=>{s||c6()||!l6(n.current)||_4e(r)&&e(FR,{replace:!0})}).catch(()=>{}),()=>{s=!0}},[]),null},E4e=({steps:t,currentStep:e})=>i.jsx("div",{className:"flex items-center justify-center gap-0","data-testid":"step-indicator",children:t.map((n,s)=>{const r=s<e,a=s===e,o=s===t.length-1;return i.jsxs(an.Fragment,{children:[i.jsxs("div",{className:"flex flex-col items-center","data-testid":`step-${s}`,children:[i.jsx("div",{className:Nr("flex items-center justify-center w-8 h-8 rounded-full text-xs font-bold transition-colors duration-200",r&&"bg-primary text-white",a&&"bg-primary/20 text-primary border-2 border-primary",!r&&!a&&"bg-surface-dark text-text-secondary-dark border border-border-dark"),"aria-current":a?"step":void 0,children:r?i.jsx(rs,{className:"w-4 h-4"}):s+1}),i.jsx("span",{className:Nr("mt-1.5 text-[10px] font-medium uppercase tracking-wide",a?"text-primary":"text-text-secondary-dark"),children:n})]}),!o&&i.jsx("div",{className:Nr("h-0.5 w-12 mx-1 mt-[-12px] transition-colors duration-200",r?"bg-primary":"bg-border-dark")})]},n)})});function d6(t){return t.status!=="running"}function C4e(t){const e={};for(const n of t)n.type==="multiselect"?e[n.id]=Array.isArray(n.default)?[...n.default]:n.default?[n.default]:[]:e[n.id]=typeof n.default=="string"?n.default:"";return e}function k4e(t,e){return t.filter(n=>{if(!n.required)return!1;const s=e[n.id];return Array.isArray(s)?s.length===0:!s||s.trim()===""}).map(n=>n.id)}const A4e=({questions:t,submitLabel:e,submitting:n=!1,error:s=null,serverProblems:r=[],onSubmit:a})=>{const[o,l]=_.useState(()=>C4e(t)),[c,d]=_.useState([]),u=new Set([...c,...r]),h=(x,v)=>{l(m=>({...m,[x]:v})),d(m=>m.filter(g=>g!==x))},f=(x,v)=>{const m=o[x],g=Array.isArray(m)?m:[];h(x,g.includes(v)?g.filter(y=>y!==v):[...g,v])},p=x=>{x.preventDefault();const v=k4e(t,o);d(v),v.length===0&&a(o)};return i.jsxs("form",{className:"space-y-4",onSubmit:p,noValidate:!0,"data-testid":"bundle-questions",children:[t.map(x=>{const v=`bundle-q-${x.id}`,m=o[x.id],g=u.has(x.id);return i.jsxs(fi,{children:[i.jsx(_t,{id:`${v}-label`,htmlFor:x.type==="multiselect"?void 0:v,required:x.required,children:x.label}),x.type==="text"&&i.jsx(Dt,{id:v,value:typeof m=="string"?m:"",placeholder:x.placeholder,error:g,onChange:y=>h(x.id,y.target.value)}),x.type==="textarea"&&i.jsx(er,{id:v,rows:3,value:typeof m=="string"?m:"",placeholder:x.placeholder,error:g,onChange:y=>h(x.id,y.target.value)}),x.type==="select"&&i.jsxs(xn,{id:v,value:typeof m=="string"?m:"",error:g,onChange:y=>h(x.id,y.target.value),children:[!x.required&&x.default===""&&i.jsx("option",{value:"",children:"—"}),x.required&&i.jsx("option",{value:"",children:"Select…"}),(x.options??[]).map(y=>i.jsx("option",{value:y.value,children:y.label??y.value},y.value))]}),x.type==="multiselect"&&i.jsx("div",{role:"group","aria-labelledby":`${v}-label`,className:"flex flex-wrap gap-2",id:v,children:(x.options??[]).map(y=>{const b=Array.isArray(m)&&m.includes(y.value);return i.jsx(de,{type:"button",size:"sm",variant:b?"primary":"secondary","aria-pressed":b,"data-testid":`bundle-option-${x.id}-${y.value}`,onClick:()=>f(x.id,y.value),children:y.label??y.value},y.value)})}),x.help&&i.jsx(Ac,{children:x.help}),g&&i.jsx("p",{className:"mt-1 text-xs text-red-400",role:"alert","data-testid":`bundle-missing-${x.id}`,children:x.type==="multiselect"?"Pick at least one":"This field is required"})]},x.id)}),s&&i.jsx(Ye,{variant:"error",size:"sm",children:s}),i.jsx(de,{type:"submit",fullWidth:!0,loading:n,"data-testid":"bundle-deploy",children:e})]})},uN={LIST:"/api/bundles",detail:t=>`/api/bundles/${encodeURIComponent(t)}`,APPLY:"/api/bundles/apply",job:t=>`/api/bundles/apply/${encodeURIComponent(t)}`},T4e=1500,N4e={queued:"Waiting",running:"In progress",done:"Done",failed:"Failed",pending:"Finishes automatically later",skipped:"Skipped"},M4e={"crewly-agent":"Crewly Agent (DeepSeek)","claude-code":"Claude Code","codex-cli":"Codex","gemini-cli":"Gemini CLI","opencode-cli":"OpenCode","antigravity-cli":"Antigravity CLI"},j4e={entry:"Entry (2 vCPU, 4 GB)",standard:"Standard (4 vCPU, 8 GB)",advanced:"Advanced (8 vCPU, 16 GB)"};class mS extends Error{constructor(e,n=null,s=[],r=[]){super(e),this.code=n,this.missing=s,this.invalid=r,this.name="BundleRequestError"}}async function hN(t,e){var s;let n;try{n=(await t()).data}catch(r){if(Dc(r)){const a=((s=r.response)==null?void 0:s.data)??{};throw new mS(a.error||r.message||e,a.code??null,a.missing??[],a.invalid??[])}throw r instanceof Error?r:new mS(e)}if(!(n!=null&&n.success)||n.data===void 0||n.data===null)throw new mS((n==null?void 0:n.error)||e);return n.data}class R4e{async getBundle(e){return hN(()=>Be.get(uN.detail(e)),"Couldn't load this bundle")}async apply(e,n,s){return(await hN(()=>Be.post(uN.APPLY,{templateId:e,answers:n,...s?{runtime:s}:{}}),"Deploy failed")).deployment}async getJob(e){return hN(()=>Be.get(uN.job(e)),"Couldn't load deploy progress")}}const j_=new R4e,I4e=({status:t})=>t==="done"?i.jsx(Ua,{className:"h-4 w-4 shrink-0 text-emerald-400","aria-hidden":!0}):t==="failed"?i.jsx(Yd,{className:"h-4 w-4 shrink-0 text-red-400","aria-hidden":!0}):t==="running"?i.jsx(qS,{className:"h-4 w-4 shrink-0 animate-spin text-primary","aria-hidden":!0}):t==="pending"?i.jsx(jr,{className:"h-4 w-4 shrink-0 text-amber-400","aria-hidden":!0}):i.jsx(sR,{className:"h-4 w-4 shrink-0 text-text-secondary-dark","aria-hidden":!0}),L4e=({templateId:t,onBack:e,onDone:n,pollIntervalMs:s=T4e})=>{const[r,a]=_.useState(null),[o,l]=_.useState(null),[c,d]=_.useState(null),[u,h]=_.useState(!1),[f,p]=_.useState(null),[x,v]=_.useState([]),m=_.useRef(null),g=_.useCallback(async()=>{l(null);try{const E=await j_.getBundle(t);a(E.bundle),E.deployment&&d(E.deployment)}catch(E){l(E instanceof Error?E.message:String(E))}},[t]);_.useEffect(()=>{g()},[g]),_.useEffect(()=>{if(!(!c||d6(c)))return m.current=setTimeout(()=>{j_.getJob(c.jobId).then(d).catch(E=>p(E instanceof Error?E.message:String(E)))},s),()=>{m.current&&clearTimeout(m.current)}},[c,s]);const y=async E=>{h(!0),p(null),v([]);try{d(await j_.apply(t,E))}catch(k){k instanceof mS&&v([...k.missing,...k.invalid].map(T=>T.id)),p(k instanceof Error?k.message:String(k))}finally{h(!1)}},b=async()=>{h(!0),p(null);try{d(await j_.apply(t,{}))}catch(E){p(E instanceof Error?E.message:String(E))}finally{h(!1)}},S=()=>{const E=(c==null?void 0:c.teams[0])??null;n({starterId:t,teamId:(E==null?void 0:E.teamId)??null,teamName:(E==null?void 0:E.name)??null,suggestions:[],bundle:!0})};if(o)return i.jsx(Ye,{variant:"error",title:"Couldn't load this bundle",children:i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{children:o}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(de,{type:"button",size:"sm",variant:"secondary",icon:$t,onClick:()=>void g(),children:"Retry"}),i.jsx(de,{type:"button",size:"sm",variant:"ghost",icon:Fa,onClick:e,children:"Choose another"})]})]})});if(!r)return i.jsx(zt,{centered:!0,text:"Loading bundle…"});if(c){const E=d6(c),k=c.steps.some(A=>A.status==="failed"),T=c.connectors.filter(A=>A.status!=="connected");return i.jsxs("div",{className:"space-y-4","data-testid":"bundle-progress",children:[i.jsx("p",{className:"text-sm text-text-secondary-dark",children:E?`"${r.label}" is deployed.`:`Deploying "${r.label}"…`}),i.jsx("ul",{className:"space-y-2",children:c.steps.map(A=>i.jsxs("li",{className:"flex items-start gap-2 text-sm","data-testid":`bundle-step-${A.id}`,children:[i.jsx(I4e,{status:A.status}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("span",{className:"text-text-primary-dark",children:A.label})," ",i.jsxs("span",{className:"text-xs text-text-secondary-dark",children:["· ",N4e[A.status]]}),(A.error??A.message)&&i.jsx("p",{className:"text-xs text-text-secondary-dark",children:A.error??A.message})]})]},A.id))}),T.length>0&&i.jsx(Ye,{variant:"info",size:"sm",title:"Connect these services too (you can do it from your phone)",children:i.jsx("ul",{className:"space-y-1","data-testid":"bundle-connect-list",children:T.map(A=>i.jsxs("li",{children:[i.jsxs("a",{className:"text-primary underline",href:A.connectPath,children:[A.id,A.products.length>0?` (${A.products.join(", ")})`:""]}),A.required?"":" (optional)",": ",A.why]},A.id))})}),f&&i.jsx(Ye,{variant:"error",size:"sm",children:f}),E&&i.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[k&&i.jsx(de,{type:"button",variant:"secondary",icon:$t,loading:u,onClick:()=>void b(),"data-testid":"bundle-retry",children:"Retry failed steps"}),i.jsx(de,{type:"button",fullWidth:!0,onClick:S,"data-testid":"bundle-finish",children:"Next"})]})]})}return i.jsxs("div",{className:"space-y-4","data-testid":"bundle-deploy-step",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx("h3",{className:"font-semibold text-text-primary-dark",children:r.label}),i.jsx(mn,{variant:"primary",children:M4e[r.recommendedRuntime]??r.recommendedRuntime}),i.jsx(mn,{children:j4e[r.serverTier]??r.serverTier})]}),i.jsx("p",{className:"mt-2 whitespace-pre-line text-sm text-text-secondary-dark",children:r.ownerSummary}),r.ownerDoes.length>0&&i.jsxs("div",{className:"mt-2 text-sm text-text-secondary-dark",children:[i.jsx("p",{className:"font-medium text-text-primary-dark",children:"What you need to do:"}),i.jsx("ul",{className:"list-disc pl-5",children:r.ownerDoes.map(E=>i.jsx("li",{children:E},E))})]}),i.jsxs("p",{className:"mt-2 text-xs text-text-secondary-dark",children:["Members: ",r.teams.flatMap(E=>E.members.map(k=>`${k.name} (${k.title})`)).join(", ")]})]}),i.jsx(A4e,{questions:r.questions,submitLabel:`Deploy "${r.label}"`,submitting:u,error:f,serverProblems:x,onSubmit:E=>void y(E)}),i.jsx(de,{type:"button",variant:"ghost",icon:Fa,onClick:e,children:"Choose another"})]})},P4e=({onDone:t})=>{const[e,n]=_.useState(null),[s,r]=_.useState(null),[a,o]=_.useState(null),[l,c]=_.useState(null),[d,u]=_.useState(!1),[h,f]=_.useState(null),p=async()=>{o(null);try{const m=await Tc.getStarters();n(m),r(g=>{var y;return g??((y=m.find(b=>b.recommended)??m[0])==null?void 0:y.id)??null})}catch(m){o(m instanceof Error?m.message:String(m))}};_.useEffect(()=>{p()},[]);const x=async()=>{var g,y;const m=e==null?void 0:e.find(b=>b.id===s);if(m){if(m.kind==="bundle"){f(m.id);return}u(!0),c(null);try{const b=await Tc.createStarterTeam(m.id);t({starterId:m.id,teamId:((g=b.team)==null?void 0:g.id)??null,teamName:((y=b.team)==null?void 0:y.name)??null,suggestions:m.suggestions})}catch(b){c(b instanceof Error?b.message:String(b))}finally{u(!1)}}};if(a)return i.jsx(Ye,{variant:"error",title:"Couldn't load team templates",children:i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{children:a}),i.jsx(de,{type:"button",size:"sm",variant:"secondary",icon:$t,onClick:()=>void p(),children:"Retry"})]})});if(!e)return i.jsx(zt,{centered:!0,text:"Loading team templates…"});if(h)return i.jsx(L4e,{templateId:h,onBack:()=>f(null),onDone:t});const v=e.find(m=>m.id===s)??null;return i.jsxs("div",{className:"space-y-3","data-testid":"starter-team-step",children:[i.jsx("div",{role:"radiogroup","aria-label":"First team",className:"space-y-3",children:e.map(m=>{const g=m.id===s;return i.jsx(tn,{role:"radio","aria-checked":g,tabIndex:0,interactive:!0,padding:"md","data-testid":`starter-${m.id}`,className:g?"border-primary ring-1 ring-primary cursor-pointer":"cursor-pointer",onClick:()=>r(m.id),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),r(m.id))},children:i.jsxs("div",{className:"flex items-start justify-between gap-3",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx("span",{className:"font-semibold text-text-primary-dark",children:m.label}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:m.name}),m.recommended&&i.jsx(mn,{variant:"primary",children:"Recommended"}),m.kind==="bundle"&&i.jsx(mn,{variant:"info",children:"Bundle"})]}),i.jsx("p",{className:"mt-1 text-sm text-text-secondary-dark",children:m.tagline}),m.members.length>0&&i.jsxs("p",{className:"mt-2 flex items-center gap-1 text-xs text-text-secondary-dark",children:[i.jsx(vr,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),m.members.map(y=>y.name).join(", ")]})]}),g&&i.jsx(rs,{className:"h-5 w-5 shrink-0 text-primary","aria-hidden":!0})]})},m.id)})}),l&&i.jsx(Ye,{variant:"error",size:"sm",children:l}),i.jsx(de,{type:"button",fullWidth:!0,loading:d,disabled:!v,onClick:()=>void x(),"data-testid":"starter-create",children:(v==null?void 0:v.members.length)===0?"Start with just the Orc":(v==null?void 0:v.kind)==="bundle"?`Next: details for "${v.label}"`:`Create "${(v==null?void 0:v.label)??""}"`})]})},D4e=4e3,O4e=({suggestions:t,teamId:e,teamName:n,onSent:s})=>{const[r,a]=_.useState(""),[o,l]=_.useState(!1),[c,d]=_.useState(null),[u,h]=_.useState(null),f=r.trim(),p=async()=>{if(f){l(!0),d(null);try{const x=await Tc.sendFirstTask(f,e);h(x),s(x)}catch(x){d(x instanceof Error?x.message:String(x))}finally{l(!1)}}};return u?i.jsx(Ye,{variant:"success",title:"Handed to the Orc","data-testid":"first-task-sent",children:u.message?"The Orc starts on it as soon as it is online.":"The Orc will get the team on it and report progress in chat and Slack."}):i.jsxs("div",{className:"space-y-3","data-testid":"first-task-step",children:[i.jsxs("p",{className:"text-sm text-text-secondary-dark",children:[n?`For "${n}"`:"For the Orc",": one sentence is enough."]}),i.jsx(er,{"aria-label":"First task",rows:4,maxLength:D4e,placeholder:"e.g. Send me a briefing every morning at 8",value:r,onChange:x=>a(x.target.value)}),t.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs text-text-secondary-dark",children:"Try one of these:"}),i.jsx("div",{className:"flex flex-col gap-2",children:t.map(x=>i.jsx(de,{type:"button",size:"sm",variant:"outline",className:"h-auto min-h-9 justify-start whitespace-normal py-2 text-left font-normal",onClick:()=>a(x),children:x},x))})]}),c&&i.jsx(Ye,{variant:"error",size:"sm",children:c}),i.jsx(de,{type:"button",fullWidth:!0,icon:nm,loading:o,disabled:!f,onClick:()=>void p(),"data-testid":"first-task-send",children:"Send it"})]})},B4e=({connected:t,tier:e,tokenPageSignInUrl:n,onConnected:s,navigateTo:r=a=>window.location.assign(a)})=>{const[a,o]=_.useState(!1),[l,c]=_.useState(""),[d,u]=_.useState(""),[h,f]=_.useState(!1),[p,x]=_.useState(null);if(t)return i.jsxs(Ye,{variant:"success",icon:Ua,title:"Connected to Crewly Cloud","data-testid":"cloud-connected",children:[e?`Plan: ${e}. `:"","You can use Crewly from your phone now."]});const v=async()=>{f(!0),x(null);try{await Tc.connectCloud(l.trim(),d.trim()||void 0),c(""),u(""),s()}catch(m){x(m instanceof Error?m.message:String(m))}finally{f(!1)}};return i.jsxs("div",{className:"space-y-4","data-testid":"cloud-connect-step",children:[i.jsxs("ul",{className:"space-y-1 text-sm text-text-secondary-dark",children:[i.jsx("li",{children:"· Check on and direct your team from your phone"}),i.jsx("li",{children:"· Automatic backups you can restore on a new computer"}),i.jsx("li",{children:"· Slack needs Cloud connected first"})]}),i.jsx(aK,{autoStart:!0,labels:TL,onConnected:()=>s()}),i.jsxs("div",{className:"space-y-1 border-t border-border-dark pt-3",children:[i.jsx(de,{type:"button",variant:"secondary",fullWidth:!0,icon:em,onClick:()=>r(Qoe(window.location.origin,KR("cloud"))),"data-testid":"cloud-sign-in",children:"Or sign in with Google in this browser"}),i.jsx("p",{className:"text-xs text-text-secondary-dark",children:"You come back to this page after signing in."})]}),a?i.jsxs("div",{className:"space-y-3 rounded-2xl border border-border-dark p-3","data-testid":"cloud-paste",children:[i.jsxs("p",{className:"text-sm text-text-secondary-dark",children:["1. Open the"," ",i.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-primary underline",children:["Crewly Cloud sign-in page ",i.jsx(Is,{className:"h-3 w-3","aria-hidden":!0})]}),". After you sign in it shows two tokens."]}),i.jsx("p",{className:"text-sm text-text-secondary-dark",children:"2. Copy each of them here:"}),i.jsxs("div",{className:"space-y-1",children:[i.jsx(_t,{htmlFor:"cloud-token",children:"Token"}),i.jsx(Dt,{id:"cloud-token",autoComplete:"off",spellCheck:!1,value:l,onChange:m=>c(m.target.value)})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx(_t,{htmlFor:"cloud-refresh-token",children:"Refresh token (keeps you signed in)"}),i.jsx(Dt,{id:"cloud-refresh-token",autoComplete:"off",spellCheck:!1,value:d,onChange:m=>u(m.target.value)})]}),!d.trim()&&l.trim()&&i.jsx("p",{className:"text-xs text-yellow-400",children:"Without a refresh token you will need to sign in again in about an hour."}),p&&i.jsx(Ye,{variant:"error",size:"sm",children:p}),i.jsx(de,{type:"button",fullWidth:!0,loading:h,disabled:!l.trim(),onClick:()=>void v(),"data-testid":"cloud-paste-save",children:"Connect"})]}):i.jsx(de,{type:"button",variant:"link",onClick:()=>o(!0),"data-testid":"cloud-show-paste",children:"Didn't come back? Use copy and paste instead"})]})},F4e="/connections?platform=slack",U4e=({connected:t,cloudConnected:e,onGoToCloud:n,onConnected:s,navigateTo:r=a=>window.location.assign(a)})=>{const[a,o]=_.useState(!1),[l,c]=_.useState(null),d=_.useRef(!1);if(_.useEffect(()=>{t||!e||d.current||(d.current=!0,Tc.refreshSlack().then(h=>{h.connected&&s()}).catch(()=>{}))},[t,e,s]),t)return i.jsx(Ye,{variant:"success",icon:Ua,title:"Slack connected","data-testid":"slack-connected",children:"DM Crewly in Slack, or @ it in a team channel."});if(!e)return i.jsxs("div",{className:"space-y-3","data-testid":"slack-needs-cloud",children:[i.jsx(Ye,{variant:"info",size:"sm",children:"Slack is installed through Crewly Cloud. Connect Crewly Cloud first."}),i.jsx(de,{type:"button",variant:"secondary",fullWidth:!0,onClick:n,children:"Connect Crewly Cloud"})]});const u=async()=>{o(!0),c(null);try{const h=await Tc.getSlackInstallUrl(`${window.location.origin}${KR("slack")}`);r(h)}catch(h){c(h instanceof Error?h.message:String(h)),o(!1)}};return i.jsxs("div",{className:"space-y-3","data-testid":"slack-connect-step",children:[i.jsx("p",{className:"text-sm text-text-secondary-dark",children:"Add Crewly to your Slack workspace to hand out work and follow progress from Slack."}),l&&i.jsx(Ye,{variant:"error",size:"sm",children:l}),i.jsx(de,{type:"button",fullWidth:!0,icon:kc,loading:a,onClick:()=>void u(),"data-testid":"slack-install",children:"Install Crewly in Slack"}),i.jsxs("a",{href:F4e,className:"inline-flex items-center gap-1 text-xs text-primary underline",children:["More Slack settings ",i.jsx(Is,{className:"h-3 w-3","aria-hidden":!0})]})]})},z4e=({harness:t,selectName:e,selected:n=!1,onSelect:s,onInstallFinished:r})=>{const{job:a,error:o,running:l,start:c}=tK(t.id,r),d=Dm[t.loginState],u=!t.installed||t.updateAvailable||(a==null?void 0:a.state)==="failed",h=(a==null?void 0:a.state)==="failed"?"Retry install":t.installed?"Update":"Install",f=i.jsx("span",{className:"font-semibold text-text-primary-dark",children:Pm(t)});return i.jsxs(tn,{padding:"md","data-testid":`harness-card-${t.id}`,className:n?"border-primary":void 0,children:[i.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[i.jsxs("div",{className:"min-w-0",children:[e?i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx("input",{type:"radio",name:e,value:t.id,checked:n,onChange:()=>s==null?void 0:s(t.id),className:"h-4 w-4 accent-[var(--crewly-primary)]"}),f]}):f,i.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[t.installed?i.jsxs(mn,{variant:"success",children:["Installed",t.version?` v${t.version}`:""]}):i.jsx(mn,{variant:"default",children:"Not installed"}),t.installed&&t.updateAvailable&&i.jsxs(mn,{variant:"info",children:["Update available",t.latestVersion?` → v${t.latestVersion}`:""]}),t.installed&&i.jsx(mn,{variant:d.variant,children:d.label}),t.installed&&t.loginSource&&i.jsx("span",{className:"text-xs text-text-secondary-dark",children:t.loginSource})]})]}),u&&i.jsx(de,{type:"button",variant:t.installed&&(a==null?void 0:a.state)!=="failed"?"secondary":"primary",size:"sm",icon:t.installed?$t:Am,loading:l,onClick:()=>void c(),className:"shrink-0 self-start",children:l?"Installing…":h})]}),o&&i.jsx(Ye,{variant:"error",size:"sm",className:"mt-3",children:o}),a&&i.jsx(sK,{log:a.log}),(a==null?void 0:a.state)==="succeeded"&&i.jsx(Ye,{variant:"success",size:"sm",className:"mt-3",title:"Installed",children:a.usedUserPrefix?"Installed to your user folder (no admin rights needed).":`${t.displayName} is ready.`}),(a==null?void 0:a.state)==="failed"&&!o&&i.jsx(Ye,{variant:"error",size:"sm",className:"mt-3",title:"Install failed",children:"Check the log above and try again."})]})},H4e="harness-choice",G4e=({harnesses:t,systemTools:e=[],selectedId:n,onSelect:s,onInstallFinished:r})=>{const a=e.filter(o=>!o.installed);return i.jsxs("div",{className:"space-y-3","data-testid":"harness-list",children:[i.jsx("div",{role:s?"radiogroup":void 0,"aria-label":s?"Choose a coding harness":void 0,className:"space-y-3",children:t.map(o=>i.jsx(z4e,{harness:o,selectName:s?H4e:void 0,selected:s?n===o.id:!1,onSelect:s,onInstallFinished:()=>r==null?void 0:r()},o.id))}),a.map(o=>i.jsxs(Ye,{variant:"warning",size:"sm",title:`Missing system tool: ${o.id}`,children:[i.jsx("span",{children:"Some skills need it. Install with:"}),i.jsx("code",{className:"ml-1 rounded bg-background-dark px-1.5 py-0.5 font-mono text-xs",children:o.installHint})]},o.id))]})},$4e=["harness","team","first_task","cloud","slack"];function W4e(t){return typeof t=="string"&&$4e.includes(t)}function gS(t,e){return t==null?void 0:t.steps.find(n=>n.id===e)}const Qn={HARNESS:0,ORC:1,LOGIN:2,TEAM:3,TASK:4,CLOUD:5,SLACK:6,DONE:7},V4e={harness:Qn.HARNESS,team:Qn.TEAM,first_task:Qn.TASK,cloud:Qn.CLOUD,slack:Qn.SLACK};function K4e(t){return W4e(t)?V4e[t]:Qn.HARNESS}function u6(t,e){var r;const n=((r=gS(t,"team"))==null?void 0:r.detail.teams[0])??null,s=(n!=null&&n.templateId?e.find(a=>a.id===n.templateId):void 0)??e.find(a=>a.members.length===0)??e[0];return{teamId:(n==null?void 0:n.id)??null,teamName:(n==null?void 0:n.name)??null,suggestions:(s==null?void 0:s.suggestions)??[]}}const yd=({title:t,subtitle:e})=>i.jsxs("div",{className:"mb-4",children:[i.jsx("h2",{className:"text-xl font-semibold text-text-primary-dark",children:t}),i.jsx("p",{className:"text-sm text-text-secondary-dark mt-1",children:e})]}),R_=({onBack:t,onNext:e,nextLabel:n,primary:s})=>i.jsxs("div",{className:"mt-6 flex justify-between gap-3",children:[i.jsx(de,{type:"button",variant:"ghost",icon:Fa,onClick:t,children:"Back"}),i.jsx(de,{type:"button",variant:s?"primary":"secondary",icon:Dp,iconPosition:"right",onClick:e,children:n})]}),q4e=()=>{const t=cs(),[e]=Pc(),{overview:n,loading:s,error:r,refresh:a,setOrcHarness:o,savingOrc:l,replaceHarness:c}=eK(),{checklist:d,loading:u,refresh:h}=f$(),[f,p]=_.useState(()=>K4e(e.get(u$))),[x,v]=_.useState(BR),[m,g]=_.useState(null),[y,b]=_.useState(null),[S,E]=_.useState(!1),k=e.get("error"),T=H9((n==null?void 0:n.harnesses)??[],n==null?void 0:n.orcHarness),A=T.some(P=>P.installed),M=T.find(P=>P.id===(n==null?void 0:n.orcHarness))??null;_.useEffect(()=>{if(f!==Qn.TASK||y||u)return;let P=!1;return Tc.getStarters().then(B=>{P||b(u6(d,B))}).catch(()=>{P||b(u6(d,[]))}),()=>{P=!0}},[f,y,d,u]);const N=()=>{S4e(!0),t(GO,{replace:!0})},L=()=>{g(KCe(T,(n==null?void 0:n.orcHarness)??null,x)),p(Qn.ORC)},I=async()=>{m&&(m!==(n==null?void 0:n.orcHarness)&&!await o(m)||p(Qn.LOGIN))},D=P=>{b({teamId:P.teamId,teamName:P.teamName,suggestions:P.suggestions,bundle:P.bundle}),h(),p(Qn.TASK)},z=_.useCallback(()=>{h()},[h]),U=()=>u?i.jsx(zt,{centered:!0}):i.jsx(Ye,{variant:"error",size:"sm",children:i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{children:"Couldn't load the setup checklist."}),i.jsx(de,{type:"button",size:"sm",variant:"secondary",icon:$t,onClick:z,children:"Retry"})]})}),G=()=>s?i.jsx(zt,{centered:!0,text:"Checking coding harnesses…"}):i.jsx(Ye,{variant:"error",title:"Couldn't load harness status",children:i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{children:r}),i.jsx(de,{type:"button",size:"sm",variant:"secondary",icon:$t,onClick:()=>void a(),children:"Retry"})]})}),K=()=>{var P;if(f<=Qn.LOGIN&&!n)return G();switch(f){case Qn.HARNESS:return i.jsxs(i.Fragment,{children:[i.jsx(yd,{title:"Pick and install a coding harness",subtitle:"Crewly's AI teammates work through a coding harness. Claude Code is recommended."}),i.jsx(G4e,{harnesses:T,systemTools:(n==null?void 0:n.systemTools)??[],selectedId:x,onSelect:v,onInstallFinished:()=>void a()}),i.jsx("div",{className:"mt-6 flex justify-end",children:i.jsx(de,{type:"button",icon:Dp,iconPosition:"right",disabled:!A,onClick:L,children:"Next"})}),!A&&i.jsx("p",{className:"mt-2 text-right text-xs text-text-secondary-dark",children:"Install at least one to continue."})]});case Qn.ORC:return i.jsxs(i.Fragment,{children:[i.jsx(yd,{title:"Which harness should the Orc use?",subtitle:"The orchestrator (Orc) coordinates your team. Choose its harness."}),i.jsx(rK,{harnesses:T,value:m,onChange:g,disabled:l}),r&&i.jsx(Ye,{variant:"error",size:"sm",className:"mt-3",children:r}),i.jsxs("div",{className:"mt-6 flex justify-between gap-3",children:[i.jsx(de,{type:"button",variant:"ghost",icon:Fa,onClick:()=>p(Qn.HARNESS),children:"Back"}),i.jsx(de,{type:"button",icon:Dp,iconPosition:"right",loading:l,disabled:!m,onClick:()=>void I(),children:"Next"})]})]});case Qn.LOGIN:{const B=(M==null?void 0:M.loginState)==="logged_in";return i.jsxs(i.Fragment,{children:[i.jsx(yd,{title:"Sign in",subtitle:"Sign in so the orchestrator can work."}),M?i.jsx(nK,{harness:M,onLoggedIn:()=>void a(),onHarnessUpdated:c}):i.jsx(Ye,{variant:"warning",size:"sm",children:"Go back one step and choose the Orc's harness first."}),i.jsxs("div",{className:"mt-6 flex justify-between gap-3",children:[i.jsx(de,{type:"button",variant:"ghost",icon:Fa,onClick:()=>p(Qn.ORC),children:"Back"}),i.jsx(de,{type:"button",variant:B?"primary":"secondary",icon:Dp,iconPosition:"right",onClick:()=>p(Qn.TEAM),children:B?"Next":"Sign in later"})]})]})}case Qn.TEAM:{const B=((P=gS(d,"team"))==null?void 0:P.detail.teams)??[];return i.jsxs(i.Fragment,{children:[i.jsx(yd,{title:"Create your first team",subtitle:"Pick a starter team. You can add more later."}),B.length>0&&i.jsxs(Ye,{variant:"success",size:"sm",className:"mb-3",children:["Existing teams: ",B.map(R=>R.name).join(", "),". You can go straight to the next step or create another."]}),i.jsx(P4e,{onDone:D}),i.jsx(R_,{onBack:()=>p(Qn.LOGIN),onNext:()=>p(Qn.TASK),nextLabel:"Skip",primary:!1})]})}case Qn.TASK:return i.jsxs(i.Fragment,{children:[i.jsx(yd,{title:"Give your team its first task",subtitle:"One sentence is enough."}),(y==null?void 0:y.bundle)&&i.jsx(Ye,{variant:"success",size:"sm",className:"mb-3","data-testid":"setup-bundle-first-week",children:"The first week of work is already planned and the team will start day by day. Want to add something else? Write it below."}),y?i.jsx(O4e,{suggestions:y.suggestions,teamId:y.teamId,teamName:y.teamName,onSent:()=>{E(!0),z()}}):i.jsx(zt,{centered:!0}),i.jsx(R_,{onBack:()=>p(Qn.TEAM),onNext:()=>p(Qn.CLOUD),nextLabel:S?"Next":"Skip",primary:S})]});case Qn.CLOUD:{const B=gS(d,"cloud");return i.jsxs(i.Fragment,{children:[i.jsx(yd,{title:"Connect Crewly Cloud",subtitle:"Manage Crewly from your phone; needed for Slack."}),k&&!(B!=null&&B.done)&&i.jsxs(Ye,{variant:"warning",size:"sm",className:"mb-3",children:["Sign-in didn't finish (",k,"). Try again, or use copy and paste instead."]}),B?i.jsx(B4e,{connected:B.done,tier:B.detail.tier,tokenPageSignInUrl:B.detail.tokenPageSignInUrl,onConnected:z}):U(),i.jsx(R_,{onBack:()=>p(Qn.TASK),onNext:()=>p(Qn.SLACK),nextLabel:B!=null&&B.done?"Next":"Skip",primary:!!(B!=null&&B.done)})]})}case Qn.SLACK:{const B=gS(d,"slack");return i.jsxs(i.Fragment,{children:[i.jsx(yd,{title:"Connect Slack",subtitle:"Talk to your team from Slack."}),B?i.jsx(U4e,{connected:B.done,cloudConnected:B.detail.cloudConnected,onGoToCloud:()=>p(Qn.CLOUD),onConnected:z}):U(),i.jsx(R_,{onBack:()=>p(Qn.CLOUD),onNext:()=>p(Qn.DONE),nextLabel:B!=null&&B.done?"Next":"Skip",primary:!!(B!=null&&B.done)})]})}default:{const B=M?Dm[M.loginState]:null;return i.jsxs("div",{className:"space-y-4","data-testid":"setup-done",children:[i.jsxs("div",{className:"text-center",children:[i.jsx(Ua,{className:"mx-auto h-12 w-12 text-emerald-400"}),i.jsx(yd,{title:"Setup complete",subtitle:"You're ready to use Crewly."})]}),M&&B&&i.jsxs("p",{className:"text-center text-sm text-text-secondary-dark",children:["The Orc uses ",i.jsx("span",{className:"font-semibold text-text-primary-dark",children:Pm(M)})," ",i.jsx(mn,{variant:B.variant,children:B.label})]}),d&&i.jsx("ul",{className:"space-y-2","data-testid":"setup-done-checklist",children:d.steps.map(R=>i.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[R.done?i.jsx(Ua,{className:"h-4 w-4 text-emerald-400","aria-label":"Done"}):i.jsx(sR,{className:"h-4 w-4 text-text-secondary-dark","aria-label":"Not done"}),i.jsx("span",{className:R.done?"text-text-primary-dark":"text-text-secondary-dark",children:$M[R.id]})]},R.id))}),i.jsx("p",{className:"text-center text-xs text-text-secondary-dark",children:'Unfinished steps stay in the "Get started" card on the dashboard. If a login expires, sign in again under Settings → Runtimes.'}),i.jsx("div",{className:"text-center",children:i.jsx(de,{type:"button",size:"default",onClick:()=>t(GO,{replace:!0}),children:"Open Crewly"})})]})}}};return i.jsx(Fre,{className:"min-h-screen px-4 py-6 sm:py-10",children:i.jsxs("div",{className:"mx-auto w-full max-w-2xl",children:[i.jsxs("header",{className:"mb-6 flex items-center justify-between gap-3",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Crewly setup"}),i.jsx("p",{className:"text-sm text-text-secondary-dark",children:"First-run setup"})]}),f!==Qn.DONE&&i.jsx(de,{type:"button",variant:"link",onClick:N,"data-testid":"setup-skip",children:"Skip for now"})]}),i.jsxs("p",{className:"mb-4 text-sm text-text-secondary-dark sm:hidden","data-testid":"setup-step-counter",children:["Step ",f+1,"/",Wk.length," · ",Wk[f]]}),i.jsx("div",{className:"mb-6 hidden overflow-x-auto sm:block",children:i.jsx(E4e,{steps:[...Wk],currentStep:f})}),i.jsx(tn,{padding:"none",className:"p-4 sm:p-6",children:K()})]})})};function X4e(){return i.jsx(qse,{children:i.jsx(Goe,{children:i.jsx(Aoe,{children:i.jsxs(Wee,{children:[i.jsx(b4e,{}),i.jsxs(eee,{children:[i.jsx(w4e,{}),i.jsxs(WQ,{children:[i.jsx(ts,{path:"/auth/callback",element:i.jsx(gBe,{})}),i.jsx(ts,{path:"/auth",element:i.jsx(yBe,{})}),i.jsx(ts,{path:"/setup",element:i.jsx(q4e,{})}),i.jsxs(ts,{path:"/",element:i.jsx(Woe,{}),children:[i.jsx(ts,{index:!0,element:i.jsx(Ele,{})}),i.jsx(ts,{path:"projects",element:i.jsx(Rle,{})}),i.jsx(ts,{path:"projects/:id",element:i.jsx(Bde,{})}),i.jsx(ts,{path:"teams",element:i.jsx(e4e,{})}),i.jsx(ts,{path:"teams/goals/:id",element:i.jsx(EX,{})}),i.jsx(ts,{path:"teams/:id",element:i.jsx(Kue,{})}),i.jsx(ts,{path:"assignments",element:i.jsx(ehe,{})}),i.jsx(ts,{path:"scheduled-checkins",element:i.jsx(ohe,{})}),i.jsx(ts,{path:"triggers",element:i.jsx(Mhe,{})}),i.jsx(ts,{path:"factory",element:i.jsx(lCe,{})}),i.jsx(ts,{path:"connections",element:i.jsx(vNe,{})}),i.jsx(ts,{path:"browser",element:i.jsx(JNe,{})}),i.jsx(ts,{path:"marketplace",element:i.jsx(x4e,{})}),i.jsx(ts,{path:"marketplace/:id",element:i.jsx(iMe,{})}),i.jsx(ts,{path:"wiki",element:i.jsx(GOe,{})}),i.jsx(ts,{path:"usage",element:i.jsx(mBe,{})}),i.jsx(ts,{path:"settings",element:i.jsx(Oke,{})}),i.jsx(ts,{path:"pricing",element:i.jsx(_Be,{})}),i.jsx(ts,{path:"tickets",element:i.jsx(DFe,{})}),i.jsx(ts,{path:"tickets/requests/:id",element:i.jsx(LX,{})}),i.jsx(ts,{path:"tickets/runs/:id",element:i.jsx(NX,{})}),i.jsx(ts,{path:"tickets/experiments/:id",element:i.jsx(FX,{})}),i.jsx(ts,{path:"tickets/traces/:traceId",element:i.jsx(UX,{})}),i.jsx(ts,{path:"team-chat",element:i.jsx(mTe,{})}),ure.map(t=>i.jsx(ts,{path:t.path,element:i.jsx(y4e,{rule:t})},t.path))]})]})]})]})})})})}const WX="/api/auth/session",nj="X-Crewly-CSRF",h6="owner_auth_required",Y4e=["POST","PUT","PATCH","DELETE"];let fN=null,fx=null,VX=null;function J4e(t){if(!t||!PR(t))return null;try{return new URL(t,window.location.origin).pathname}catch{return null}}function sj(t){const e=J4e(t);return e!==null&&e.startsWith("/api/")&&e!==WX}function rj(t){return Y4e.includes((t??"GET").toUpperCase())}function KX(t,e){if(t!==401)return!1;const n=e;return(n==null?void 0:n.error)===h6||(n==null?void 0:n.code)===h6}function Y0(t=!1){return!t&&fN?Promise.resolve(fN):fx||(fx=(VX??window.fetch.bind(window))(WX,{credentials:"same-origin",cache:"no-store"}).then(async n=>{var a;const s=await n.json().catch(()=>null),r=n.ok&&typeof((a=s==null?void 0:s.data)==null?void 0:a.csrfToken)=="string"?s.data.csrfToken:null;return fN=r,r}).catch(()=>null).finally(()=>{fx=null}),fx)}function Z4e(t=window){const e=t.fetch.bind(t);VX=e;const n=async(s,r)=>{var p,x;const a=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!sj(a))return e(s,r);const o=(r==null?void 0:r.method)??(s instanceof Request?s.method:"GET"),l=rj(o),c=s instanceof Request?s.clone():s,d=v=>{if(!l||!v)return r;const m=new Headers((r==null?void 0:r.headers)??(s instanceof Request?s.headers:void 0));return m.set(nj,v),{...r,headers:m}},u=await e(s,d(l?await Y0():null));if(DR((x=(p=u.headers)==null?void 0:p.get)==null?void 0:x.call(p,z9)),u.status!==401)return u;const h=await u.clone().json().catch(()=>null);if(!KX(u.status,h))return u;const f=await Y0(!0);return f?e(c,d(f)):u};t.fetch=n}function Q4e(t=Be){t.interceptors.request.use(async n=>{if(sj(n.url)&&rj(n.method)){const s=await Y0();s&&n.headers.set(nj,s)}return n});const e=async(n,s,r)=>{if(!n||n.__crewlyOwnerRetry||!sj(n.url)||!KX(s,r))return null;const a=await Y0(!0);return a?(n.__crewlyOwnerRetry=!0,rj(n.method)&&n.headers.set(nj,a),t.request(n)):null};t.interceptors.response.use(async n=>{var r;const s=(r=n.headers)==null?void 0:r[z9.toLowerCase()];return DR(typeof s=="string"?s:void 0),await e(n.config,n.status,n.data)??n},async n=>{const s=n==null?void 0:n.response,r=s?await e(n.config,s.status,s.data):null;return r||Promise.reject(n)})}function e5e(){Z4e(),Q4e(),Y0()}Cp(sw());_9(()=>{sw()==="system"&&Cp("system")});Eae();e5e();pN.createRoot(document.getElementById("root")).render(i.jsx(an.StrictMode,{children:i.jsx(X4e,{})}));
4955
- //# sourceMappingURL=index-b1fc60ea.js.map
4955
+ //# sourceMappingURL=index-b4db6abe.js.map