crewly 1.20.161 → 1.20.162

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 (137) hide show
  1. package/config/roles/orchestrator/prompt.md +2 -0
  2. package/config/roles/team-leader/prompt.md +12 -0
  3. package/config/roles/team-leader/tl-addon.md +12 -0
  4. package/config/skills/agent/core/project-tickets/SKILL.md +32 -1
  5. package/config/skills/agent/core/project-tickets/execute.sh +56 -2
  6. package/config/skills/agent/core/project-tickets/execute.test.sh +22 -0
  7. package/dist/backend/backend/src/constants.d.ts +84 -1
  8. package/dist/backend/backend/src/constants.d.ts.map +1 -1
  9. package/dist/backend/backend/src/constants.js +105 -16
  10. package/dist/backend/backend/src/constants.js.map +1 -1
  11. package/dist/backend/backend/src/controllers/project-tickets/project-tickets.controller.d.ts +43 -0
  12. package/dist/backend/backend/src/controllers/project-tickets/project-tickets.controller.d.ts.map +1 -1
  13. package/dist/backend/backend/src/controllers/project-tickets/project-tickets.controller.js +85 -0
  14. package/dist/backend/backend/src/controllers/project-tickets/project-tickets.controller.js.map +1 -1
  15. package/dist/backend/backend/src/controllers/project-tickets/project-tickets.routes.d.ts +12 -0
  16. package/dist/backend/backend/src/controllers/project-tickets/project-tickets.routes.d.ts.map +1 -1
  17. package/dist/backend/backend/src/controllers/project-tickets/project-tickets.routes.js +19 -1
  18. package/dist/backend/backend/src/controllers/project-tickets/project-tickets.routes.js.map +1 -1
  19. package/dist/backend/backend/src/index.d.ts.map +1 -1
  20. package/dist/backend/backend/src/index.js +30 -1
  21. package/dist/backend/backend/src/index.js.map +1 -1
  22. package/dist/backend/backend/src/models/Project.d.ts +3 -0
  23. package/dist/backend/backend/src/models/Project.d.ts.map +1 -1
  24. package/dist/backend/backend/src/models/Project.js +7 -0
  25. package/dist/backend/backend/src/models/Project.js.map +1 -1
  26. package/dist/backend/backend/src/routes/api.routes.d.ts.map +1 -1
  27. package/dist/backend/backend/src/routes/api.routes.js +3 -1
  28. package/dist/backend/backend/src/routes/api.routes.js.map +1 -1
  29. package/dist/backend/backend/src/services/agent/oauth-relogin-monitor.service.d.ts +66 -13
  30. package/dist/backend/backend/src/services/agent/oauth-relogin-monitor.service.d.ts.map +1 -1
  31. package/dist/backend/backend/src/services/agent/oauth-relogin-monitor.service.js +161 -32
  32. package/dist/backend/backend/src/services/agent/oauth-relogin-monitor.service.js.map +1 -1
  33. package/dist/backend/backend/src/services/project-tickets/project-ticket-workflow.service.d.ts +48 -0
  34. package/dist/backend/backend/src/services/project-tickets/project-ticket-workflow.service.d.ts.map +1 -1
  35. package/dist/backend/backend/src/services/project-tickets/project-ticket-workflow.service.js +77 -1
  36. package/dist/backend/backend/src/services/project-tickets/project-ticket-workflow.service.js.map +1 -1
  37. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-decision.d.ts +223 -0
  38. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-decision.d.ts.map +1 -0
  39. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-decision.js +240 -0
  40. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-decision.js.map +1 -0
  41. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-messages.d.ts +94 -0
  42. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-messages.d.ts.map +1 -0
  43. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-messages.js +195 -0
  44. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-messages.js.map +1 -0
  45. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot.service.d.ts +286 -0
  46. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot.service.d.ts.map +1 -0
  47. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot.service.js +626 -0
  48. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot.service.js.map +1 -0
  49. package/dist/backend/backend/src/services/reconciler/reconcile-rules.d.ts +37 -3
  50. package/dist/backend/backend/src/services/reconciler/reconcile-rules.d.ts.map +1 -1
  51. package/dist/backend/backend/src/services/reconciler/reconcile-rules.js +57 -6
  52. package/dist/backend/backend/src/services/reconciler/reconcile-rules.js.map +1 -1
  53. package/dist/backend/backend/src/services/reconciler/reconciler-data-provider.d.ts +21 -1
  54. package/dist/backend/backend/src/services/reconciler/reconciler-data-provider.d.ts.map +1 -1
  55. package/dist/backend/backend/src/services/reconciler/reconciler-data-provider.js +62 -4
  56. package/dist/backend/backend/src/services/reconciler/reconciler-data-provider.js.map +1 -1
  57. package/dist/backend/backend/src/services/reconciler/reconciler.service.d.ts +6 -0
  58. package/dist/backend/backend/src/services/reconciler/reconciler.service.d.ts.map +1 -1
  59. package/dist/backend/backend/src/services/reconciler/reconciler.service.js +9 -5
  60. package/dist/backend/backend/src/services/reconciler/reconciler.service.js.map +1 -1
  61. package/dist/backend/backend/src/services/task-pool/claim.service.d.ts +23 -3
  62. package/dist/backend/backend/src/services/task-pool/claim.service.d.ts.map +1 -1
  63. package/dist/backend/backend/src/services/task-pool/claim.service.js +52 -11
  64. package/dist/backend/backend/src/services/task-pool/claim.service.js.map +1 -1
  65. package/dist/backend/backend/src/services/task-pool/task-pool.service.d.ts +42 -0
  66. package/dist/backend/backend/src/services/task-pool/task-pool.service.d.ts.map +1 -1
  67. package/dist/backend/backend/src/services/task-pool/task-pool.service.js +82 -1
  68. package/dist/backend/backend/src/services/task-pool/task-pool.service.js.map +1 -1
  69. package/dist/backend/backend/src/services/task-pool/ticket-claim-policy.d.ts +19 -0
  70. package/dist/backend/backend/src/services/task-pool/ticket-claim-policy.d.ts.map +1 -1
  71. package/dist/backend/backend/src/services/task-pool/ticket-claim-policy.js +33 -0
  72. package/dist/backend/backend/src/services/task-pool/ticket-claim-policy.js.map +1 -1
  73. package/dist/backend/backend/src/services/v3/agent-auto-claim.service.d.ts +28 -0
  74. package/dist/backend/backend/src/services/v3/agent-auto-claim.service.d.ts.map +1 -1
  75. package/dist/backend/backend/src/services/v3/agent-auto-claim.service.js +74 -29
  76. package/dist/backend/backend/src/services/v3/agent-auto-claim.service.js.map +1 -1
  77. package/dist/backend/backend/src/services/v3/workitem-dispatch.subscriber.d.ts.map +1 -1
  78. package/dist/backend/backend/src/services/v3/workitem-dispatch.subscriber.js +3 -2
  79. package/dist/backend/backend/src/services/v3/workitem-dispatch.subscriber.js.map +1 -1
  80. package/dist/backend/backend/src/types/index.d.ts +6 -0
  81. package/dist/backend/backend/src/types/index.d.ts.map +1 -1
  82. package/dist/backend/backend/src/types/index.js.map +1 -1
  83. package/dist/backend/backend/src/types/ticket-autopilot.types.d.ts +73 -0
  84. package/dist/backend/backend/src/types/ticket-autopilot.types.d.ts.map +1 -0
  85. package/dist/backend/backend/src/types/ticket-autopilot.types.js +88 -0
  86. package/dist/backend/backend/src/types/ticket-autopilot.types.js.map +1 -0
  87. package/dist/backend/backend/src/types/v2/claim.types.d.ts +27 -0
  88. package/dist/backend/backend/src/types/v2/claim.types.d.ts.map +1 -1
  89. package/dist/backend/backend/src/types/v2/claim.types.js +37 -0
  90. package/dist/backend/backend/src/types/v2/claim.types.js.map +1 -1
  91. package/dist/backend/backend/src/types/v2/work-item.types.d.ts +1 -1
  92. package/dist/backend/backend/src/types/v2/work-item.types.d.ts.map +1 -1
  93. package/dist/backend/backend/src/types/v2/work-item.types.js +1 -0
  94. package/dist/backend/backend/src/types/v2/work-item.types.js.map +1 -1
  95. package/dist/backend/build-info.json +2 -2
  96. package/dist/cli/backend/src/constants.d.ts +84 -1
  97. package/dist/cli/backend/src/constants.d.ts.map +1 -1
  98. package/dist/cli/backend/src/constants.js +105 -16
  99. package/dist/cli/backend/src/constants.js.map +1 -1
  100. package/dist/cli/backend/src/models/Project.d.ts +3 -0
  101. package/dist/cli/backend/src/models/Project.d.ts.map +1 -1
  102. package/dist/cli/backend/src/models/Project.js +7 -0
  103. package/dist/cli/backend/src/models/Project.js.map +1 -1
  104. package/dist/cli/backend/src/services/agent/oauth-relogin-monitor.service.d.ts +66 -13
  105. package/dist/cli/backend/src/services/agent/oauth-relogin-monitor.service.d.ts.map +1 -1
  106. package/dist/cli/backend/src/services/agent/oauth-relogin-monitor.service.js +161 -32
  107. package/dist/cli/backend/src/services/agent/oauth-relogin-monitor.service.js.map +1 -1
  108. package/dist/cli/backend/src/services/task-pool/claim.service.d.ts +23 -3
  109. package/dist/cli/backend/src/services/task-pool/claim.service.d.ts.map +1 -1
  110. package/dist/cli/backend/src/services/task-pool/claim.service.js +52 -11
  111. package/dist/cli/backend/src/services/task-pool/claim.service.js.map +1 -1
  112. package/dist/cli/backend/src/services/task-pool/task-pool.service.d.ts +42 -0
  113. package/dist/cli/backend/src/services/task-pool/task-pool.service.d.ts.map +1 -1
  114. package/dist/cli/backend/src/services/task-pool/task-pool.service.js +82 -1
  115. package/dist/cli/backend/src/services/task-pool/task-pool.service.js.map +1 -1
  116. package/dist/cli/backend/src/services/task-pool/ticket-claim-policy.d.ts +19 -0
  117. package/dist/cli/backend/src/services/task-pool/ticket-claim-policy.d.ts.map +1 -1
  118. package/dist/cli/backend/src/services/task-pool/ticket-claim-policy.js +33 -0
  119. package/dist/cli/backend/src/services/task-pool/ticket-claim-policy.js.map +1 -1
  120. package/dist/cli/backend/src/types/index.d.ts +6 -0
  121. package/dist/cli/backend/src/types/index.d.ts.map +1 -1
  122. package/dist/cli/backend/src/types/index.js.map +1 -1
  123. package/dist/cli/backend/src/types/ticket-autopilot.types.d.ts +73 -0
  124. package/dist/cli/backend/src/types/ticket-autopilot.types.d.ts.map +1 -0
  125. package/dist/cli/backend/src/types/ticket-autopilot.types.js +88 -0
  126. package/dist/cli/backend/src/types/ticket-autopilot.types.js.map +1 -0
  127. package/dist/cli/backend/src/types/v2/claim.types.d.ts +27 -0
  128. package/dist/cli/backend/src/types/v2/claim.types.d.ts.map +1 -1
  129. package/dist/cli/backend/src/types/v2/claim.types.js +37 -0
  130. package/dist/cli/backend/src/types/v2/claim.types.js.map +1 -1
  131. package/dist/cli/backend/src/types/v2/work-item.types.d.ts +1 -1
  132. package/dist/cli/backend/src/types/v2/work-item.types.d.ts.map +1 -1
  133. package/dist/cli/backend/src/types/v2/work-item.types.js +1 -0
  134. package/dist/cli/backend/src/types/v2/work-item.types.js.map +1 -1
  135. package/frontend/dist/assets/{index-8f30aa74.js → index-64c8a616.js} +2 -2
  136. package/frontend/dist/index.html +1 -1
  137. package/package.json +1 -1
@@ -4947,5 +4947,5 @@ Describe the ${y.toLowerCase()}…`,rows:16,className:"font-mono text-xs","data-
4947
4947
  Deployed to staging
4948
4948
  95% code coverage`})]}),T&&i.jsx("div",{"data-testid":"create-mission-error",children:i.jsx(et,{variant:"error",children:T})})]})}),i.jsxs(hc,{children:[i.jsx(de,{variant:"ghost",size:"sm",onClick:e,disabled:E,children:"Cancel"}),i.jsx(de,{variant:"primary",size:"sm",onClick:z,loading:E,"data-testid":"create-mission-submit",children:E?"Creating...":"Create Mission"})]})]}):null},RV={number:"count",percentage:"%",boolean:"done",currency:"$"},d5={number:"Number",percentage:"Percentage",boolean:"Yes / No",currency:"Currency"},u5={title:"",metricType:"number",baseline:"0",target:"",unit:RV.number,measurementSource:"manual"};function iRe(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 Ag(t){if(t.trim()==="")return null;const e=Number(t);return Number.isFinite(e)?e:null}const aRe=({missionId:t,onChanged:e})=>{const[n,s]=w.useState([]),[r,a]=w.useState(!0),[o,l]=w.useState(null),[c,d]=w.useState(null),[u,h]=w.useState(!1),[f,p]=w.useState(!1),[x,y]=w.useState(u5),[m,g]=w.useState(null),[v,b]=w.useState(""),[_,k]=w.useState(""),[E,M]=w.useState(null),[T,A]=w.useState(null),[N,D]=w.useState(null),I=w.useCallback(async()=>{l(null);try{const R=await xt.getKeyResults(t);s(R)}catch(R){l(R instanceof Error?R.message:"Failed to load key results")}finally{a(!1)}},[t]);w.useEffect(()=>{a(!0),I()},[I]);const F=w.useCallback(async R=>{h(!0),d(null);try{return await R(),await I(),e==null||e(),!0}catch(L){return d(L instanceof Error?L.message:"Request failed"),!1}finally{h(!1)}},[I,e]),z=async()=>{const R=Ag(x.baseline),L=Ag(x.target);if(!x.title.trim()){d("Title is required");return}if(R===null||L===null){d("Baseline and target must be numbers");return}if(R===L){d("Baseline and target must be different");return}if(!x.unit.trim()){d("Unit is required");return}const $={title:x.title.trim(),metricType:x.metricType,baseline:R,target:L,unit:x.unit.trim(),measurementSource:x.measurementSource};await F(async()=>{await xt.createKeyResult(t,$)})&&(y(u5),p(!1))},W=R=>{d(null),M(null),g(R.id),b(String(R.current)),k("")},G=async R=>{const L=Ag(v);if(L===null){d("Measurement value must be a number");return}await F(async()=>{await xt.measureKeyResult(t,R,{value:L,source:"user",..._.trim()?{note:_.trim()}:{}})})&&g(null)},K=R=>{d(null),g(null),M(R.id),A({target:String(R.target),current:String(R.current),measurementSource:R.measurementSource})},P=async R=>{if(!T)return;const L=Ag(T.target),$=Ag(T.current);if(L===null||$===null){d("Target and current must be numbers");return}if(L===R.baseline){d("Target must differ from the baseline");return}await F(async()=>{await xt.updateKeyResult(t,R.id,{...L!==R.target?{target:L}:{},...$!==R.current?{current:$}:{},...T.measurementSource!==R.measurementSource?{measurementSource:T.measurementSource}:{}})})&&(M(null),A(null))},B=async()=>{if(!N)return;const R=N;await F(async()=>{await xt.deleteKeyResult(t,R)})&&D(null)};return i.jsxs(ot,{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(b2,{className:"h-4 w-4"}),"Key Results (",n.length,")"]}),i.jsx(de,{variant:"ghost",size:"sm",icon:f?ls:Jn,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(et,{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(xs,{"aria-label":"KR title",placeholder:"e.g. Reach $5k MRR",value:x.title,onChange:R=>y(L=>({...L,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(pn,{"aria-label":"Metric type",value:x.metricType,onChange:R=>{const L=R.target.value;y($=>({...$,metricType:L,unit:RV[L]}))},"data-testid":"kr-new-metric",children:cre.map(R=>i.jsx("option",{value:R,children:d5[R]},R))}),i.jsx(xs,{"aria-label":"Baseline",type:"number",placeholder:"Baseline",value:x.baseline,onChange:R=>y(L=>({...L,baseline:R.target.value})),"data-testid":"kr-new-baseline"}),i.jsx(xs,{"aria-label":"Target",type:"number",placeholder:"Target",value:x.target,onChange:R=>y(L=>({...L,target:R.target.value})),"data-testid":"kr-new-target"}),i.jsx(xs,{"aria-label":"Unit",placeholder:"Unit",value:x.unit,onChange:R=>y(L=>({...L,unit:R.target.value})),"data-testid":"kr-new-unit"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(pn,{"aria-label":"Measurement source",value:x.measurementSource,onChange:R=>y(L=>({...L,measurementSource:R.target.value})),"data-testid":"kr-new-source",children:cD.map(R=>i.jsx("option",{value:R,children:Pk[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(et,{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 L=uj(R),$=(ne=R.measurements)==null?void 0:ne[0],H=m===R.id,se=E===R.id&&T!==null;return i.jsxs(Mn.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:d5[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:[Zg(R.baseline,R.metricType,R.unit),i.jsx("span",{className:"text-text-secondary-dark",children:" → "}),i.jsx("span",{className:"font-semibold",children:Zg(R.current,R.metricType,R.unit)}),i.jsx("span",{className:"text-text-secondary-dark",children:" → "}),Zg(R.target,R.metricType,R.unit)]}),i.jsx("td",{className:"py-2 pr-3",children:i.jsx(Ux,{percent:L,status:R.status,"data-testid":`kr-progress-${R.id}`})}),i.jsx("td",{className:"py-2 pr-3",children:i.jsx(ct,{variant:dre[R.status],size:"sm","data-testid":`kr-status-${R.id}`,children:bM[R.status]})}),i.jsx("td",{className:"py-2 pr-3 text-xs text-text-secondary-dark",children:Pk[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:iRe($==null?void 0:$.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:PY,onClick:()=>W(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:k1,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:Vr,onClick:()=>D(R.id),disabled:u,"data-testid":`kr-delete-${R.id}`,"aria-label":"Delete key result"})]})})]}),H&&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(xs,{"aria-label":"Measurement value",type:"number",value:v,onChange:Z=>b(Z.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(xs,{"aria-label":"Measurement note",placeholder:"Note (optional)",value:_,onChange:Z=>k(Z.target.value),className:"flex-1 min-w-[160px]","data-testid":`kr-measure-note-${R.id}`}),i.jsx(de,{variant:"primary",size:"sm",icon:Sd,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"})]})})}),se&&T&&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(xs,{"aria-label":"Edit target",type:"number",value:T.target,onChange:Z=>A(U=>U&&{...U,target:Z.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(xs,{"aria-label":"Edit current",type:"number",value:T.current,onChange:Z=>A(U=>U&&{...U,current:Z.target.value}),className:"w-28","data-testid":`kr-edit-current-${R.id}`}),i.jsx(pn,{"aria-label":"Edit measurement source",value:T.measurementSource,onChange:Z=>A(U=>U&&{...U,measurementSource:Z.target.value}),"data-testid":`kr-edit-source-${R.id}`,children:cD.map(Z=>i.jsx("option",{value:Z,children:Pk[Z]},Z))}),i.jsx(de,{variant:"primary",size:"sm",icon:Sd,onClick:()=>P(R),disabled:u,"data-testid":`kr-edit-submit-${R.id}`,children:u?"Saving…":"Save"}),i.jsx(de,{variant:"ghost",size:"sm",onClick:()=>{M(null),A(null)},disabled:u,children:"Cancel"})]})})})]},R.id)})})]})}),i.jsx(V1,{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:()=>D(null),onConfirm:B})]})},oRe={continue:"Continue",adjust_strategy:"Adjust strategy",replan:"Replan",escalate:"Escalate"};function h5(t,e){return e.get(t)??t.slice(0,8)}const lRe=({missionId:t,level:e,parentMissionId:n,missionNames:s,refreshKey:r=0})=>{const a=ps(),[o,l]=w.useState(null),[c,d]=w.useState(!0),[u,h]=w.useState(null),f=w.useCallback(async()=>{d(!0),h(null);try{l(await xt.getCascadeSummary(t))}catch(p){h(p instanceof Error?p.message:"Failed to load cascade")}finally{d(!1)}},[t]);return w.useEffect(()=>{f()},[f,r]),i.jsxs(ot,{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(Sp,{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:Px,onClick:()=>a(`/missions/${n}`),className:"text-left","data-testid":"cascade-parent-link",children:h5(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(et,{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:oRe[o.recommendation]??o.recommendation})]}),i.jsx(Ux,{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(fj,{counts:vH(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(`/missions/${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(_0,{level:p.level}),i.jsx("span",{className:"text-sm text-text-primary-dark truncate",children:h5(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(Ux,{percent:p.rolledUpProgress,"data-testid":`cascade-child-progress-${p.missionId}`})]})},p.missionId))})]})]}):null]})},cRe=({parentMissionId:t,onDecided:e})=>{const n=ps(),[s,r]=w.useState([]),[a,o]=w.useState(!1),l=w.useCallback(async()=>{try{r(await xt.getProposals(t))}catch{r([])}finally{o(!0)}},[t]);w.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(ot,{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(Sh,{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(_0,{level:d.level}),i.jsx("button",{type:"button",onClick:()=>n(`/missions/${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(ct,{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((y,m)=>i.jsx("li",{children:y},m))})]}),i.jsx(tI,{missionId:d.id,onDecided:c})]})},d.id)})})]})},dRe=[{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"}],uRe=({missionId:t,refreshKey:e=0})=>{const[n,s]=w.useState(null),[r,a]=w.useState(!0),[o,l]=w.useState(null),c=w.useCallback(async()=>{a(!0),l(null);try{s(await xt.getMissionProgress(t))}catch(d){l(d instanceof Error?d.message:"Failed to load progress")}finally{a(!1)}},[t]);return w.useEffect(()=>{c()},[c,e]),i.jsxs(ot,{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(cl,{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(et,{variant:"error",children:o})}):n?i.jsxs("div",{className:"space-y-3 text-sm",children:[i.jsx(Ux,{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:dRe.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 Ef(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 hRe(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(`
4949
4949
  `),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 fRe(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(`
4950
- `).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 IV=()=>{var K,P,B,R,L;const{id:t}=vh(),e=ps(),[n,s]=w.useState(null),[r,a]=w.useState(!0),[o,l]=w.useState(null),[c,d]=w.useState(!1),[u,h]=w.useState(!1),[f,p]=w.useState(null),[x,y]=w.useState(!1),[m,g]=w.useState(null),[v,b]=w.useState(new Map),[_,k]=w.useState(new Map),[E,M]=w.useState(0),T=w.useCallback(async($=!0)=>{if(t){$?a(!0):d(!0),l(null);try{const H=await xt.getMission(t);s(H)}catch(H){const se=H instanceof Error?H.message:"Failed to load mission";l(se)}finally{a(!1),d(!1)}}},[t]);w.useEffect(()=>{T()},[T]),w.useEffect(()=>{let $=!1;return(async()=>{try{const H=await xt.getMissions();if($)return;b(new Map(H.map(se=>[se.id,se.objective]))),k(new Map(H.map(se=>[se.id,{level:se.level,parentMissionId:se.parentMissionId}])))}catch{}})(),()=>{$=!0}},[t]);const A=w.useCallback(()=>{M($=>$+1),T(!1)},[T]),N=w.useCallback($=>{s(H=>H&&H.id===$.id?{...H,...$}:H),A()},[A]),D=w.useCallback(()=>{n&&(p(hRe(n)),g(null),h(!0))},[n]),I=w.useCallback(()=>{h(!1),p(null),g(null)},[]),F=w.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}y(!0),g(null);try{const $=await xt.updateMission(t,fRe(f));s($),h(!1),p(null)}catch($){const H=$ instanceof Error?$.message:"Failed to save mission";g(H)}finally{y(!1)}}},[t,f]),z=w.useMemo(()=>($,H)=>{p(se=>se&&{...se,[$]:H})},[]);if(r)return i.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:i.jsx(Ut,{size:"xl",text:"Loading mission..."})});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:zr,onClick:()=>e("/missions"),className:"mb-6",children:"Back to Missions"}),i.jsx(ot,{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:sn,onClick:()=>T(),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:zr,onClick:()=>e("/missions"),className:"mb-6",children:"Back to Missions"}),i.jsx(ot,{variant:"default",padding:"lg",children:i.jsx(Cs,{icon:ih,title:"Mission not found.",compact:!0})})]});const W=dj(n,_),G=(K=n.approval)==null?void 0:K.state;return i.jsxs("div",{className:"p-6 max-w-[1000px] mx-auto","data-testid":"mission-detail-page",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:zr,onClick:()=>e("/missions"),className:"mb-6","data-testid":"mission-detail-back",children:"Back to Missions"}),i.jsxs("div",{className:"flex items-start justify-between gap-4 mb-6",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[u&&f?i.jsx(xs,{"aria-label":"Objective",value:f.objective,onChange:$=>z("objective",$.target.value),fullWidth:!0,"data-testid":"edit-objective"}):i.jsx("h1",{className:"text-2xl font-bold text-text-primary-dark mb-2",children:n.objective}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap mt-2",children:[i.jsx(_0,{level:W}),i.jsx(Po,{status:lj(n.status),children:Y_(n.status)}),G&&(G!=="approved"||((P=n.approval)==null?void 0:P.decidedAt))&&i.jsx(hj,{state:G}),n.priority&&i.jsx(ct,{variant:xH[n.priority],size:"sm",children:yM[n.priority]}),((B=n.period)==null?void 0:B.label)&&i.jsx(ct,{variant:"info",size:"sm",children:n.period.label}),i.jsx(ct,{variant:"default",size:"sm",children:n.id.slice(0,12)})]}),G==="pending_approval"&&!u&&i.jsxs("div",{className:"mt-3 flex items-center gap-3 flex-wrap","data-testid":"mission-pending-banner",children:[i.jsxs("span",{className:"text-xs text-yellow-400",children:["Proposed",(R=n.approval)!=null&&R.proposedBy?` by ${n.approval.proposedBy}`:""," — awaiting your decision."]}),i.jsx(tI,{missionId:n.id,onDecided:N})]}),G==="rejected"&&((L=n.approval)==null?void 0:L.rejectionReason)&&i.jsxs("p",{className:"mt-2 text-xs text-red-400","data-testid":"mission-rejection-reason",children:["Rejected: ",n.approval.rejectionReason]})]}),i.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:u?i.jsxs(i.Fragment,{children:[i.jsx(de,{variant:"primary",size:"sm",icon:Sd,onClick:F,disabled:x,"data-testid":"mission-save",children:x?"Saving…":"Save"}),i.jsx(de,{variant:"ghost",size:"sm",icon:ls,onClick:I,disabled:x,"data-testid":"mission-cancel",children:"Cancel"})]}):i.jsxs(i.Fragment,{children:[i.jsx(de,{variant:"primary",size:"sm",icon:k1,onClick:D,"data-testid":"mission-edit",children:"Edit"}),i.jsx(de,{variant:"ghost",size:"sm",icon:sn,onClick:()=>T(!1),loading:c,"aria-label":"Refresh mission",children:"Refresh"})]})})]}),m&&i.jsx("div",{"data-testid":"mission-save-error",className:"mb-4",children:i.jsx(et,{variant:"error",onClose:()=>g(null),children:m})}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[i.jsxs("div",{className:"lg:col-span-2 flex flex-col gap-4",children:[i.jsxs(ot,{variant:"default",padding:"md",className:"border border-border-dark",children:[i.jsxs("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wide mb-2 flex items-center gap-1.5",children:[i.jsx(ih,{className:"h-4 w-4"}),"Current Strategy"]}),u&&f?i.jsx(qs,{"aria-label":"Current Strategy",rows:4,value:f.currentStrategy,onChange:$=>z("currentStrategy",$.target.value),"data-testid":"edit-strategy"}):i.jsx("p",{className:"text-sm text-text-primary-dark leading-relaxed whitespace-pre-wrap",children:n.currentStrategy||"No strategy defined."})]}),i.jsxs(ot,{variant:"default",padding:"md",className:"border border-border-dark",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(ra,{className:"h-4 w-4"}),"Success Criteria (",n.successCriteria.length,")"]}),u&&f?i.jsx(qs,{"aria-label":"Success Criteria (one per line)",rows:5,placeholder:"One criterion per line",value:f.successCriteriaText,onChange:$=>z("successCriteriaText",$.target.value),"data-testid":"edit-success-criteria"}):n.successCriteria.length===0?i.jsx("p",{className:"text-sm text-text-secondary-dark",children:"No success criteria defined."}):i.jsx("ul",{className:"space-y-2",children:n.successCriteria.map(($,H)=>i.jsxs("li",{className:"flex items-start gap-2 text-sm text-text-primary-dark",children:[i.jsx("span",{className:"text-primary mt-0.5 flex-shrink-0",children:i.jsx(w2,{className:"h-4 w-4"})}),$]},H))})]}),!u&&i.jsx(aRe,{missionId:n.id,onChanged:A}),!u&&i.jsx(cRe,{parentMissionId:n.id,onDecided:N}),!u&&i.jsx(lRe,{missionId:n.id,level:W,parentMissionId:n.parentMissionId,missionNames:v,refreshKey:E}),!u&&n.learnings&&n.learnings.length>0&&i.jsxs(ot,{variant:"default",padding:"md",className:"border border-border-dark",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(d0,{className:"h-4 w-4"}),"Learnings (",n.learnings.length,")"]}),i.jsx("ul",{className:"space-y-2",children:n.learnings.map(($,H)=>i.jsx("li",{className:"text-sm text-text-primary-dark pl-4 border-l-2 border-border-dark",children:$},H))})]})]}),i.jsxs("div",{className:"flex flex-col gap-4",children:[!u&&i.jsx(uRe,{missionId:n.id,refreshKey:E}),i.jsxs(ot,{variant:"default",padding:"md",className:"border border-border-dark",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(is,{className:"h-4 w-4"}),"Team & Settings"]}),i.jsxs("div",{className:"space-y-3 text-sm",children:[i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("span",{className:"text-text-secondary-dark text-xs uppercase tracking-wide",children:"Owner Team"}),u&&f?i.jsx(xs,{"aria-label":"Owner Team",value:f.ownerTeamId,onChange:$=>z("ownerTeamId",$.target.value),fullWidth:!0,"data-testid":"edit-owner-team"}):i.jsx("span",{className:"text-text-primary-dark font-mono text-xs",children:n.ownerTeamId})]}),i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("span",{className:"text-text-secondary-dark text-xs uppercase tracking-wide",children:"Status"}),u&&f?i.jsxs(pn,{value:f.status,onChange:$=>z("status",$.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.jsx("span",{className:"text-text-primary-dark",children:Y_(n.status)})]}),i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("span",{className:"text-text-secondary-dark text-xs uppercase tracking-wide",children:"Priority"}),u&&f?i.jsxs(pn,{value:f.priority,onChange:$=>z("priority",$.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.jsx("span",{className:"text-text-primary-dark",children:yM[n.priority??"medium"]})]}),i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("span",{className:"text-text-secondary-dark text-xs uppercase tracking-wide",children:"Parent Mission"}),u&&f?i.jsx(xs,{"aria-label":"Parent Mission ID",placeholder:"(none)",value:f.parentMissionId,onChange:$=>z("parentMissionId",$.target.value),fullWidth:!0,"data-testid":"edit-parent"}):n.parentMissionId?i.jsx(de,{type:"button",variant:"link",size:"xs",onClick:()=>e(`/missions/${n.parentMissionId}`),className:"truncate max-w-full","data-testid":"mission-parent-link",children:v.get(n.parentMissionId)??n.parentMissionId}):i.jsx("span",{className:"text-text-primary-dark font-mono text-xs",children:"—"})]}),!u&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Level"}),i.jsx("span",{className:"text-text-primary-dark","data-testid":"mission-level",children:W})]}),!u&&n.projectId&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Project"}),i.jsx(de,{type:"button",variant:"link",size:"xs",onClick:()=>e(`/projects/${n.projectId}`),className:"font-mono","data-testid":"mission-project-link",children:n.projectId.slice(0,12)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Active Tasks"}),i.jsx("span",{className:"text-text-primary-dark",children:n.activeProjectTaskIds.length})]}),i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("span",{className:"text-text-secondary-dark text-xs uppercase tracking-wide",children:"Cadence (cron)"}),u&&f?i.jsx(xs,{"aria-label":"Cadence",value:f.cadence,onChange:$=>z("cadence",$.target.value),fullWidth:!0,"data-testid":"edit-cadence"}):i.jsx("span",{className:"text-text-primary-dark font-mono text-xs",children:n.cadence||"N/A"})]})]})]}),i.jsxs(ot,{variant:"default",padding:"md",className:"border border-border-dark",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(OT,{className:"h-4 w-4"}),"OKR Period"]}),u&&f?i.jsxs("div",{className:"space-y-2",children:[i.jsxs(pn,{value:f.periodType,onChange:$=>z("periodType",$.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(xs,{type:"date","aria-label":"Period start",value:f.periodStart,onChange:$=>z("periodStart",$.target.value),fullWidth:!0,"data-testid":"edit-period-start"}),i.jsx(xs,{type:"date","aria-label":"Period end",value:f.periodEnd,onChange:$=>z("periodEnd",$.target.value),fullWidth:!0,"data-testid":"edit-period-end"}),i.jsx(xs,{"aria-label":"Period label",placeholder:"Label (optional)",value:f.periodLabel,onChange:$=>z("periodLabel",$.target.value),fullWidth:!0,"data-testid":"edit-period-label"})]}):n.period?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:"Type"}),i.jsx("span",{className:"text-text-primary-dark",children:n.period.type})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Start"}),i.jsx("span",{className:"text-text-primary-dark text-xs",children:Ef(n.period.startDate)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"End"}),i.jsx("span",{className:"text-text-primary-dark text-xs",children:Ef(n.period.endDate)})]}),n.period.label&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Label"}),i.jsx("span",{className:"text-text-primary-dark text-xs",children:n.period.label})]})]}):i.jsx("p",{className:"text-sm text-text-secondary-dark",children:"No period defined."})]}),i.jsxs(ot,{variant:"default",padding:"md",className:"border border-border-dark",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(OT,{className:"h-4 w-4"}),"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 text-xs",children:Ef(n.createdAt)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Updated"}),i.jsx("span",{className:"text-text-primary-dark text-xs",children:Ef(n.updatedAt)})]}),n.lastReviewAt&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Last Review"}),i.jsx("span",{className:"text-text-primary-dark text-xs",children:Ef(n.lastReviewAt)})]}),n.nextReviewAt&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Next Review"}),i.jsx("span",{className:"text-text-primary-dark text-xs",children:Ef(n.nextReviewAt)})]})]})]}),!u&&n.activeProjectTaskIds.length>0&&i.jsxs(ot,{variant:"default",padding:"md",className:"border border-border-dark",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"}),"Active Task IDs"]}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.activeProjectTaskIds.map($=>i.jsx(ct,{variant:"default",size:"sm",children:$.slice(0,12)},$))})]})]})]})]})};IV.displayName="MissionDetail";const PV="/api/tickets",pRe=15e3,mRe=300,gRe=24*60*60*1e3,LV=["idea","todo","in_progress","blocked","to_review","done"],vN={idea:"Ideas",todo:"To do",in_progress:"In progress",blocked:"Blocked",to_review:"To review",done:"Done",cancelled:"Cancelled"},nI={issue:"Issue",feature:"Feature",idea:"Idea",question:"Question"},DV=["issue","feature","idea","question"],c_="all",xRe="All",yRe=[{value:"urgent",label:"P0"},{value:"high",label:"P1"},{value:"normal",label:"P2"},{value:"low",label:"P3"}],vRe={P0:"error",P1:"warning",P2:"primary",P3:"default"},bRe={owner:"Me",decompose:"Breakdown",reject:"Sent back",agent:"Agent"},PA={auto:"Auto",judgment:"Manual"},_Re={"slack-channel":"Slack channel","slack-dm":"Slack DM",chat:"Chat",portal:"Portal",mobile:"Mobile","bug-button":"Bug button",agent:"Agent",cron:"Scheduled task",mission:"Mission",legacy:"Legacy record"},f5={not_in_review:"This ticket is not in review, so it cannot be sent back",already_done:"This ticket is already done",open_work:"Some work items are still open, so it cannot be accepted yet",cancelled:"This ticket was cancelled",invalid:"Invalid input"},Qt={PAGE_TITLE:"Tickets",PAGE_SUBTITLE:"Everything you have asked for, in one place",SEARCH_PLACEHOLDER:"Search tickets…",KIND_FILTER_ARIA:"Filter by type",REFRESH:"Refresh",EMPTY_COLUMN:"Nothing here",EMPTY_BOARD_TITLE:"No tickets yet",EMPTY_BOARD_DESC:'Ask for something in Slack or chat ("please help me…") and a ticket is created automatically.',LOAD_FAILED:"Failed to load tickets",UNASSIGNED:"Unassigned",REJECT_BADGE:"Sent back",AUTO_ACCEPT_IN_DAYS:"Auto-accepts in",AUTO_ACCEPT_SOON:"Auto-accepts soon",ACCEPTED_BY_OWNER:"Accepted",ACCEPTED_BY_SILENCE:"Auto-accepted · not reviewed",ACCEPTED_BY_SILENCE_HINT:"Nobody objected before the deadline, so it closed as accepted; nobody checked the result",DETAIL_LOADING:"Loading…",TITLE_LABEL:"Title",SAVE:"Save",PRIORITY_LABEL:"Priority",KIND_LABEL:"Type",ORIGIN_LABEL:"Source",ASSIGNEE_LABEL:"Assignee",DESCRIPTION_LABEL:"Description",REPLY_LABEL:"Agent's answer",NO_REPLY:"No answer yet",DISCUSSION_LABEL:"Discussion",NO_DISCUSSION:"No discussion yet",ACCEPTANCE_LABEL:"Acceptance criteria",NO_ACCEPTANCE:"No acceptance criteria yet",ACCEPTANCE_ADD_PLACEHOLDER:"Add an acceptance criterion…",ACCEPTANCE_CHECK_ARIA:"How it is checked",ACCEPTANCE_ADD:"Add",ACCEPTANCE_REMOVE:"Remove",SELF_CHECK_PASS:"Self-check passed",SELF_CHECK_FAIL:"Self-check failed",VERIFY:"Verified",REJECT:"Send back",DISMISS:"Dismiss",REJECT_REASON_LABEL:"Reason for sending back",REJECT_REASON_PLACEHOLDER:"What is wrong? This becomes a new acceptance criterion",REJECT_REASON_REQUIRED:"Please give a reason for sending it back",REJECT_CONFIRM:"Confirm send back",CANCEL:"Cancel",REJECTED_TIMES:"Sent back",SUBMITTED_TIMES:"Submitted"};class sI extends Error{constructor(n,s,r){super(n);Ln(this,"status");Ln(this,"code");this.name="TicketApiError",this.status=s,this.code=r}}function SRe(t){return t instanceof sI}function wRe(t){const e={};for(const n of LV)e[n]=[];e.cancelled=[];for(const n of t)(e[n.column]??(e[n.column]=[])).push(n);return e}function CRe(t,e=Date.now()){if(!t)return null;const n=Date.parse(t);return Number.isNaN(n)?null:Math.max(0,Math.ceil((n-e)/gRe))}function OV(t,e=Date.now()){const n=CRe(t,e);return n===null?null:n<=0?Qt.AUTO_ACCEPT_SOON:`${Qt.AUTO_ACCEPT_IN_DAYS} ${n} ${n===1?"day":"days"}`}function kRe(t){if(!t)return null;const e=_Re[t.channel]??t.channel,n=t.authorName||t.author;return n?`${e} · ${n}`:e}function p5(t){if(!t)return"";const e=Date.parse(t);return Number.isNaN(e)?t:new Date(e).toLocaleString()}function m5(t){return(t??[]).map(e=>({text:e.text,...e.check?{check:e.check}:{}}))}function bN(t){return SRe(t)&&t.code&&f5[t.code]?f5[t.code]:t instanceof Error&&t.message?t.message:String(t)}const ERe=({ticket:t,onOpen:e,now:n})=>{var c;const s=t.column==="to_review",r=s?OV(t.autoAcceptAt,n):null,a=t.column==="done"?t.acceptedBy??null:null,o=t.rejectCount??0,l=d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),e(t))};return i.jsxs(ot,{padding:"sm",interactive:!0,role:"button",tabIndex:0,"aria-label":`${t.tkt??""} ${t.title}`.trim(),"data-testid":`ticket-card-${t.id}`,onClick:()=>e(t),onKeyDown:l,className:"rounded-2xl focus:outline-none focus:ring-1 focus:ring-primary",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsx("span",{className:"text-xs font-semibold text-text-secondary-dark",children:t.tkt??""}),i.jsxs("div",{className:"flex items-center gap-1",children:[o>0&&i.jsxs(ct,{variant:"error",size:"sm","data-testid":"ticket-reject-badge",children:[Qt.REJECT_BADGE," ×",o]}),i.jsx(ct,{variant:vRe[t.priorityLabel]??"default",size:"sm",children:t.priorityLabel})]})]}),i.jsx("p",{className:"mt-1 text-sm font-medium text-text-primary-dark break-words",children:t.title}),s&&((c=t.reply)==null?void 0:c.excerpt)&&i.jsx("p",{className:"mt-2 text-xs text-text-secondary-dark line-clamp-3 break-words","data-testid":"ticket-reply-excerpt",children:t.reply.excerpt}),i.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[i.jsx(ct,{size:"sm",children:nI[t.kind]??t.kind}),i.jsx("span",{className:"text-xs text-text-secondary-dark truncate",children:t.assignee||Qt.UNASSIGNED})]}),r&&i.jsx("p",{className:"mt-2 text-xs text-primary","data-testid":"ticket-auto-accept",children:r}),a&&i.jsx("div",{className:"mt-2","data-testid":"ticket-accepted-by","data-accepted-by":a,children:i.jsx(ct,{size:"sm",variant:a==="owner"?"success":"warning",title:a==="silence"?Qt.ACCEPTED_BY_SILENCE_HINT:void 0,children:a==="owner"?Qt.ACCEPTED_BY_OWNER:Qt.ACCEPTED_BY_SILENCE})})]})};async function Rh(t,e){const n=await fetch(t,e);let s={};try{s=await n.json()}catch{s={}}if(!n.ok||s.success===!1)throw new sI(s.error||s.message||`HTTP ${n.status}`,n.status,s.code);return s.data}function U0(t,e){return{method:t,headers:{"Content-Type":"application/json"},...e!==void 0?{body:JSON.stringify(e)}:{}}}function mm(t,e=""){return`${PV}/${encodeURIComponent(t)}${e}`}function ARe(t={}){var r;const e=new URLSearchParams;t.column&&e.set("column",t.column),t.kind&&e.set("kind",t.kind);const n=(r=t.q)==null?void 0:r.trim();n&&e.set("q",n),t.includeLegacy&&e.set("includeLegacy","true");const s=e.toString();return s?`?${s}`:""}async function TRe(t={}){const e=await Rh(`${PV}${ARe(t)}`);return{tickets:(e==null?void 0:e.tickets)??[],columns:(e==null?void 0:e.columns)??{}}}function MRe(t){return Rh(mm(t))}function NRe(t){return Rh(mm(t,"/verify"),U0("POST"))}function jRe(t,e){const n=e.trim();return n?Rh(mm(t,"/reject"),U0("POST",{reason:n})):Promise.reject(new sI("A reason is required",400,"invalid"))}function RRe(t){return Rh(mm(t,"/dismiss"),U0("POST"))}function IRe(t,e){return Rh(mm(t,"/acceptance"),U0("PUT",{items:e}))}function PRe(t,e){return Rh(mm(t),U0("PATCH",e))}const g5="judgment",LRe=({acceptance:t,onSave:e,disabled:n=!1})=>{const[s,r]=w.useState(""),[a,o]=w.useState(g5),[l,c]=w.useState(!1),d=n||l,u=async p=>{c(!0);try{return await e(p),!0}catch{return!1}finally{c(!1)}},h=async p=>{const x=m5(t).filter((y,m)=>m!==p);await u(x)},f=async p=>{p.preventDefault();const x=s.trim();if(!x)return;await u([...m5(t),{text:x,check:a}])&&(r(""),o(g5))};return i.jsxs("div",{"data-testid":"ticket-acceptance",children:[t.length===0?i.jsx("p",{className:"text-sm text-text-secondary-dark",children:Qt.NO_ACCEPTANCE}):i.jsx("ul",{className:"space-y-2",children:t.map((p,x)=>i.jsxs("li",{className:"flex items-start gap-2 rounded-2xl border border-border-dark bg-background-dark p-3","data-testid":"ticket-acceptance-item",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-text-primary-dark break-words",children:p.text}),i.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1",children:[i.jsx(ct,{size:"sm",variant:p.source==="reject"?"error":"default",children:bRe[p.source??"owner"]}),i.jsx(ct,{size:"sm",variant:p.check==="auto"?"info":"default",children:PA[p.check??"judgment"]}),p.selfCheck&&i.jsx(ct,{size:"sm",variant:p.selfCheck==="pass"?"success":"error",children:p.selfCheck==="pass"?Qt.SELF_CHECK_PASS:Qt.SELF_CHECK_FAIL})]}),p.evidence&&i.jsx("p",{className:"mt-1 text-xs text-text-secondary-dark break-words",children:p.evidence})]}),i.jsx(Ft,{icon:Vr,variant:"ghost","aria-label":`${Qt.ACCEPTANCE_REMOVE} ${p.text}`,disabled:d,onClick:()=>void h(x)})]},`${x}-${p.text}`))}),i.jsxs("form",{className:"mt-3 flex flex-col gap-2 sm:flex-row",onSubmit:p=>void f(p),children:[i.jsx("div",{className:"flex-1",children:i.jsx(Bt,{value:s,onChange:p=>r(p.target.value),placeholder:Qt.ACCEPTANCE_ADD_PLACEHOLDER,"aria-label":Qt.ACCEPTANCE_ADD_PLACEHOLDER,disabled:d})}),i.jsx("div",{className:"sm:w-28",children:i.jsxs(pn,{value:a,onChange:p=>o(p.target.value),"aria-label":Qt.ACCEPTANCE_CHECK_ARIA,disabled:d,children:[i.jsx("option",{value:"judgment",children:PA.judgment}),i.jsx("option",{value:"auto",children:PA.auto})]})}),i.jsx(de,{type:"submit",variant:"secondary",icon:Jn,disabled:d||!s.trim(),children:Qt.ACCEPTANCE_ADD})]})]})},DRe=new Set(["done","cancelled"]),Cb=({title:t,children:e})=>i.jsxs("section",{className:"space-y-2",children:[i.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-text-secondary-dark",children:t}),e]}),ORe=({ticketId:t,onClose:e,onChanged:n,now:s})=>{const[r,a]=w.useState(null),[o,l]=w.useState(null),[c,d]=w.useState(null),[u,h]=w.useState(null),[f,p]=w.useState(""),[x,y]=w.useState(!1),[m,g]=w.useState(""),[v,b]=w.useState(null),_=w.useCallback(async P=>{try{const B=await MRe(P);a(B),p(B.board.title),l(null)}catch(B){l(bN(B))}},[]);w.useEffect(()=>{a(null),l(null),d(null),y(!1),g(""),b(null),t&&_(t)},[t,_]);const k=async(P,B,R=!1)=>{if(!t)return!1;h(P),d(null);try{return await B(),n(),R?e():await _(t),!0}catch(L){return d(bN(L)),!1}finally{h(null)}},E=P=>{t&&k("patch",()=>PRe(t,P))},M=async P=>{if(!t)return;if(!await k("acceptance",()=>IRe(t,P)))throw new Error("acceptance save failed")},T=()=>{if(!t)return;const P=m.trim();if(!P){b(Qt.REJECT_REASON_REQUIRED);return}b(null),k("reject",()=>jRe(t,P)).then(B=>{B&&(y(!1),g(""))})},A=(r==null?void 0:r.board)??null,N=t!==null,D=A!==null&&!DRe.has(A.column),I=(A==null?void 0:A.column)==="to_review",F=A!==null&&f.trim()!==""&&f.trim()!==A.title,z=(r==null?void 0:r.ticket.discussion)??[],W=(A==null?void 0:A.description)||(r==null?void 0:r.ticket.description)||"",G=I?OV(A==null?void 0:A.autoAcceptAt,s):null,K=A&&D?x?i.jsxs("div",{className:"flex w-full flex-col gap-2","data-testid":"ticket-reject-form",children:[i.jsx("label",{htmlFor:"ticket-reject-reason",className:"text-sm text-text-secondary-dark",children:Qt.REJECT_REASON_LABEL}),i.jsx(qs,{id:"ticket-reject-reason",rows:3,value:m,error:v!==null,placeholder:Qt.REJECT_REASON_PLACEHOLDER,onChange:P=>{g(P.target.value),v&&b(null)}}),v&&i.jsx("p",{className:"text-xs text-red-400",role:"alert",children:v}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(de,{variant:"ghost",onClick:()=>y(!1),disabled:u!==null,children:Qt.CANCEL}),i.jsx(de,{variant:"warning",icon:r3,onClick:T,loading:u==="reject",children:Qt.REJECT_CONFIRM})]})]}):i.jsxs("div",{className:"flex w-full flex-wrap items-center justify-end gap-2",children:[i.jsx(de,{variant:"danger-ghost",icon:ls,onClick:()=>void k("dismiss",()=>RRe(t),!0),loading:u==="dismiss",disabled:u!==null&&u!=="dismiss",children:Qt.DISMISS}),I&&i.jsx(de,{variant:"warning",icon:r3,onClick:()=>y(!0),disabled:u!==null,children:Qt.REJECT}),i.jsx(de,{variant:"success",icon:$n,onClick:()=>void k("verify",()=>NRe(t),!0),loading:u==="verify",disabled:u!==null&&u!=="verify",children:Qt.VERIFY})]}):void 0;return i.jsxs(XJ,{isOpen:N,onClose:e,size:"lg",title:(A==null?void 0:A.tkt)??(A==null?void 0:A.title)??Qt.DETAIL_LOADING,subtitle:A?vN[A.column]??A.column:void 0,footer:K,"data-testid":"ticket-detail-drawer",children:[!A&&!o&&i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(Ut,{})}),o&&i.jsx(et,{variant:"error",size:"sm",children:o}),A&&i.jsxs("div",{className:"space-y-6",children:[c&&i.jsx(et,{variant:"error",size:"sm",onClose:()=>d(null),"data-testid":"ticket-action-error",children:c}),i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{children:[i.jsx("label",{htmlFor:"ticket-title",className:"mb-1 block text-sm text-text-secondary-dark",children:Qt.TITLE_LABEL}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Bt,{id:"ticket-title",value:f,onChange:P=>p(P.target.value)}),F&&i.jsx(de,{variant:"secondary",onClick:()=>E({title:f.trim()}),loading:u==="patch",children:Qt.SAVE})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{htmlFor:"ticket-priority",className:"mb-1 block text-sm text-text-secondary-dark",children:Qt.PRIORITY_LABEL}),i.jsx(pn,{id:"ticket-priority",value:A.priority,disabled:u!==null,onChange:P=>E({priority:P.target.value}),children:yRe.map(P=>i.jsx("option",{value:P.value,children:P.label},P.value))})]}),i.jsxs("div",{children:[i.jsx("label",{htmlFor:"ticket-kind",className:"mb-1 block text-sm text-text-secondary-dark",children:Qt.KIND_LABEL}),i.jsx(pn,{id:"ticket-kind",value:A.kind,disabled:u!==null,onChange:P=>E({kind:P.target.value}),children:DV.map(P=>i.jsx("option",{value:P,children:nI[P]},P))})]})]}),i.jsxs("dl",{className:"grid grid-cols-1 gap-2 text-sm sm:grid-cols-2",children:[i.jsxs("div",{children:[i.jsx("dt",{className:"text-text-secondary-dark",children:Qt.ORIGIN_LABEL}),i.jsx("dd",{className:"text-text-primary-dark","data-testid":"ticket-origin",children:kRe(A.origin)??"—"})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-text-secondary-dark",children:Qt.ASSIGNEE_LABEL}),i.jsx("dd",{className:"text-text-primary-dark",children:A.assignee||Qt.UNASSIGNED})]})]}),i.jsxs("div",{className:"flex flex-wrap gap-1",children:[(A.rejectCount??0)>0&&i.jsxs(ct,{variant:"error",size:"sm",children:[Qt.REJECTED_TIMES," ×",A.rejectCount]}),(A.submitCount??0)>0&&i.jsxs(ct,{size:"sm",children:[Qt.SUBMITTED_TIMES," ×",A.submitCount]}),G&&i.jsx(ct,{variant:"primary",size:"sm",children:G})]})]}),W&&i.jsx(Cb,{title:Qt.DESCRIPTION_LABEL,children:i.jsx("p",{className:"whitespace-pre-wrap break-words text-sm text-text-primary-dark",children:W})}),i.jsx(Cb,{title:Qt.REPLY_LABEL,children:A.reply?i.jsxs("div",{className:"rounded-2xl border border-border-dark bg-background-dark p-3","data-testid":"ticket-reply",children:[i.jsx("p",{className:"whitespace-pre-wrap break-words text-sm text-text-primary-dark",children:A.reply.excerpt}),i.jsxs("p",{className:"mt-1 text-xs text-text-secondary-dark",children:[A.reply.by," · ",p5(A.reply.at)]})]}):i.jsx("p",{className:"text-sm text-text-secondary-dark",children:Qt.NO_REPLY})}),i.jsx(Cb,{title:Qt.ACCEPTANCE_LABEL,children:i.jsx(LRe,{acceptance:A.acceptance??[],onSave:M,disabled:u!==null&&u!=="acceptance"})}),i.jsx(Cb,{title:Qt.DISCUSSION_LABEL,children:z.length===0?i.jsx("p",{className:"text-sm text-text-secondary-dark",children:Qt.NO_DISCUSSION}):i.jsx("ul",{className:"space-y-2","data-testid":"ticket-discussion",children:z.map((P,B)=>i.jsxs("li",{className:"rounded-2xl border border-border-dark p-3",children:[i.jsxs("p",{className:"text-xs text-text-secondary-dark",children:[P.author," · ",p5(P.at)]}),i.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words text-sm text-text-primary-dark",children:P.text})]},`${P.ref}-${B}`))})})]})]})},BRe=[{value:c_,label:xRe},...DV.map(t=>({value:t,label:nI[t]}))],FRe=({now:t})=>{const[e,n]=w.useState(""),[s,r]=w.useState(""),[a,o]=w.useState(c_),[l,c]=w.useState(null),[d,u]=w.useState(!0),[h,f]=w.useState(null),[p,x]=w.useState(null),y=w.useRef(0);w.useEffect(()=>{const k=setTimeout(()=>r(e),mRe);return()=>clearTimeout(k)},[e]);const m=w.useCallback(async()=>{const k=++y.current;try{const E=await TRe({...a!==c_?{kind:a}:{},...s.trim()?{q:s}:{}});if(k!==y.current)return;c(E),f(null)}catch(E){if(k!==y.current)return;f(bN(E))}finally{k===y.current&&u(!1)}},[a,s]);w.useEffect(()=>{m();const k=setInterval(()=>void m(),pRe);return()=>clearInterval(k)},[m]);const g=w.useMemo(()=>wRe((l==null?void 0:l.tickets)??[]),[l]),v=a!==c_||s.trim()!=="",b=l!==null&&l.tickets.length===0&&!v,_=w.useCallback(k=>x(k.id),[]);return i.jsxs("div",{className:"flex min-w-0 max-w-full flex-col gap-4","data-testid":"tickets-page",children:[i.jsxs("div",{className:"flex items-start justify-between gap-4",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("h1",{className:"text-2xl font-bold text-text-primary-dark",children:Qt.PAGE_TITLE}),i.jsx("p",{className:"mt-1 text-sm text-text-secondary-dark",children:Qt.PAGE_SUBTITLE})]}),i.jsx(Ft,{icon:sn,variant:"ghost","aria-label":Qt.REFRESH,onClick:()=>void m()})]}),i.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[i.jsx("div",{className:"w-full sm:max-w-xs",children:i.jsx(xs,{type:"search",value:e,onChange:k=>n(k.target.value),placeholder:Qt.SEARCH_PLACEHOLDER,"aria-label":Qt.SEARCH_PLACEHOLDER,fullWidth:!0})}),i.jsx("div",{className:"max-w-full overflow-x-auto",children:i.jsx(oo,{options:BRe,value:a,onChange:o,size:"sm","aria-label":Qt.KIND_FILTER_ARIA})})]}),h&&i.jsx(et,{variant:"error",size:"sm",title:Qt.LOAD_FAILED,children:h}),d&&!l?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(Ut,{})}):b?i.jsx(Cs,{icon:r6,title:Qt.EMPTY_BOARD_TITLE,description:Qt.EMPTY_BOARD_DESC}):i.jsx("div",{className:"w-full min-w-0 overflow-x-auto pb-2","data-testid":"tickets-board",children:i.jsx("div",{className:"flex gap-3 snap-x",children:LV.map(k=>{var T;const E=g[k]??[],M=((T=l==null?void 0:l.columns)==null?void 0:T[k])??E.length;return i.jsxs("section",{"aria-label":vN[k],"data-testid":`tickets-column-${k}`,className:"flex w-64 shrink-0 snap-start flex-col rounded-2xl border border-border-dark bg-surface-dark/50 p-2 sm:w-72",children:[i.jsxs("header",{className:"flex items-center justify-between px-1 pb-2",children:[i.jsx("h2",{className:"text-sm font-semibold text-text-primary-dark",children:vN[k]}),i.jsx(ct,{size:"sm",variant:k==="to_review"&&M>0?"primary":"default",children:M})]}),i.jsx("div",{className:"flex flex-col gap-2",children:E.length===0?i.jsx("p",{className:"px-1 py-4 text-center text-xs text-text-secondary-dark",children:Qt.EMPTY_COLUMN}):E.map(A=>i.jsx(ERe,{ticket:A,onOpen:_,now:t},A.id))})]},k)})})}),i.jsx(ORe,{ticketId:p,onClose:()=>x(null),onChanged:()=>void m(),now:t})]})};function rI(t){return{queued:"pending",scheduled:"paused",running:"running",blocked:"blocked",done:"completed",failed:"error",cancelled:"inactive"}[t]??"pending"}function iI(t){return{queued:"Queued",scheduled:"Scheduled",running:"Running",blocked:"Blocked",done:"Completed",failed:"Failed",cancelled:"Cancelled"}[t]??t}function aI(t){return{delegate:"primary",project_task:"info",check:"default",notify:"success",cron_run:"warning",review:"info",confirm:"warning",reconcile:"default"}[t]??"default"}function oI(t){return{delegate:"Delegate",project_task:"Project Task",check:"Check",notify:"Notify",cron_run:"Cron Run",review:"Review",confirm:"Confirm",reconcile:"Reconcile"}[t]??t}function URe(t){return{orchestrator:"Orchestrator",team_lead:"Team Lead",agent:"Agent",system:"System"}[t]??t}function Ww(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 Hg(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 BV(t){return t===0?"—":t<.01?`$${t.toFixed(4)}`:`$${t.toFixed(2)}`}function fx(t){return t===0?"—":t<1e3?t.toString():t<1e6?`${(t/1e3).toFixed(1)}K`:`${(t/1e6).toFixed(1)}M`}function FV(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 zRe(t,e){if(t==="error")return ul;if(t==="progress_update")return b2;if(t==="agent_reasoning"||t==="tool_action")return Pi;switch(e){case"queued":return vs;case"running":return Pi;case"done":return ra;case"failed":return ul;case"cancelled":return lY;case"blocked":return _d;default:return vs}}function HRe(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 GRe(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 lI=({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=zRe(e.kind,e.status),r=HRe(e.kind,e.status),a=GRe(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:Hg(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)})});lI.displayName="WorkItemTimeline";const Ga=({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})]}),UV=({item:t})=>{const e=WRe(t);return i.jsxs("div",{className:"space-y-4","data-testid":"workitem-metrics",children:[i.jsxs(ot,{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(Ga,{icon:Lx,label:"Input Tokens",value:fx(t.inputTokens)}),i.jsx(Ga,{icon:Lx,label:"Output Tokens",value:fx(t.outputTokens)}),i.jsx(Ga,{icon:S2,label:"Cost",value:BV(t.cost),valueClass:t.cost>0?"text-yellow-400":"text-text-primary-dark"})]})]}),i.jsxs(ot,{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(Ga,{icon:sn,label:"Retries",value:`${t.retryCount} / ${t.maxRetries}`}),i.jsx(Ga,{icon:vs,label:"Duration",value:e}),i.jsx(Ga,{icon:Yp,label:"Owner",value:URe(t.owner)}),t.target&&i.jsx(Ga,{icon:ih,label:"Agent",value:t.target})]})]}),(t.requestId||t.missionId||t.projectTaskId||t.triggerId)&&i.jsxs(ot,{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(Ga,{icon:Yc,label:"Request",value:Tg(t.requestId)}),t.missionId&&i.jsx(Ga,{icon:Yc,label:"Mission",value:Tg(t.missionId)}),t.projectTaskId&&i.jsx(Ga,{icon:Yc,label:"Project Task",value:Tg(t.projectTaskId)}),t.triggerId&&i.jsx(Ga,{icon:Yc,label:"Trigger",value:Tg(t.triggerId)}),t.parentWorkItemId&&i.jsx(Ga,{icon:Yc,label:"Parent Item",value:Tg(t.parentWorkItemId)})]})]}),i.jsxs(ot,{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:Hg(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:Hg(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:Hg(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:Hg(t.scheduledAt)})]})]})]})]})};UV.displayName="WorkItemMetrics";function WRe(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 Tg(t){return t.length<=12?t:`${t.slice(0,8)}...`}function VRe(t){const e={total:t.length,running:0,queued:0,done:0,failed:0,blocked:0};for(const n of t)switch(n.status){case"running":e.running++;break;case"queued":case"scheduled":e.queued++;break;case"done":e.done++;break;case"failed":e.failed++;break;case"blocked":e.blocked++;break}return e}const $Re=({stats:t})=>t?i.jsxs(j2,{variant:"horizontal",className:"grid-cols-3 md:grid-cols-6","data-testid":"workitem-summary-bar",children:[i.jsx(ii,{label:"Total",value:t.total}),i.jsx(ii,{label:"Running",children:i.jsx("span",{className:"text-blue-400",children:t.running})}),i.jsx(ii,{label:"Queued",children:i.jsx("span",{className:"text-yellow-400",children:t.queued})}),i.jsx(ii,{label:"Done",children:i.jsx("span",{className:"text-green-400",children:t.done})}),i.jsx(ii,{label:"Failed",children:i.jsx("span",{className:"text-red-400",children:t.failed})}),i.jsx(ii,{label:"Blocked",children:i.jsx("span",{className:"text-orange-400",children:t.blocked})})]}):null,zV=()=>{const t=ps(),[e,n]=w.useState([]),[s,r]=w.useState(!0),[a,o]=w.useState(null),[l,c]=w.useState("all"),[d,u]=w.useState(""),[h,f]=w.useState(""),p=w.useRef(),x=w.useCallback(k=>{f(k),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{u(k)},300)},[]);w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const y=w.useCallback(async()=>{r(!0),o(null);try{const k=await xt.getWorkItems();if(!Array.isArray(k)){console.warn("[WorkItems] getWorkItems returned non-array:",typeof k,k),n([]);return}n(k)}catch(k){console.warn("[WorkItems] loadItems error:",k),o(k instanceof Error?k.message:"Failed to load work items")}finally{r(!1)}},[]);w.useEffect(()=>{y()},[y]);const m=w.useMemo(()=>{let k=e;if(l!=="all"&&(k=k.filter(M=>M.status===l)),d.trim()){const M=d.toLowerCase();k=k.filter(T=>{var A;return T.title.toLowerCase().includes(M)||T.id.toLowerCase().includes(M)||((A=T.target)==null?void 0:A.toLowerCase().includes(M))||T.type.toLowerCase().includes(M)})}const E={running:0,blocked:1,failed:2,done:3,completed:3,cancelled:4,queued:5,scheduled:5};return k.sort((M,T)=>{const A=E[M.status]??5,N=E[T.status]??5;return A!==N?A-N:new Date(T.createdAt).getTime()-new Date(M.createdAt).getTime()})},[e,l,d]),g=w.useMemo(()=>{const k={all:e.length};for(const E of e)k[E.status]=(k[E.status]||0)+1;return k},[e]),v=w.useMemo(()=>e.length>0?VRe(e):null,[e]),b=[{key:"all",label:"All"},{key:"running",label:"Running"},{key:"queued",label:"Queued"},{key:"done",label:"Completed"},{key:"failed",label:"Failed"},{key:"blocked",label:"Blocked"},{key:"cancelled",label:"Cancelled"}],_=w.useCallback((k,E)=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),t(`/workitems/${E}`))},[t]);return i.jsxs("div",{className:"p-6 max-w-7xl mx-auto","data-testid":"workitems-page",children:[i.jsxs("div",{className:"mb-6",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("h1",{className:"text-2xl font-bold text-text-primary-dark",children:"Work Items"}),i.jsx(de,{variant:"secondary",size:"sm",icon:sn,onClick:y,loading:s,"data-testid":"workitems-refresh",children:"Refresh"})]}),i.jsx("p",{className:"text-sm text-text-secondary-dark",children:"Execution-level view of all system tasks in the task pool."})]}),!s&&i.jsx($Re,{stats:v}),i.jsx(Od,{tabs:b.map(k=>({value:k.key,label:k.label,count:g[k.key]})),activeTab:l,onTabChange:k=>c(k),searchPlaceholder:"Search by title, ID, agent...",searchValue:h,onSearchChange:x}),s&&i.jsx("div",{"data-testid":"workitems-loading",children:i.jsx(N1,{count:4})}),a&&!s&&i.jsxs(et,{variant:"error",title:"Failed to load work items",onClose:()=>o(null),"data-testid":"workitems-error",children:[a,i.jsx(de,{variant:"ghost",size:"sm",onClick:y,className:"mt-2",children:"Retry"})]}),!s&&!a&&m.length===0&&i.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-16 text-text-secondary-dark","data-testid":"workitems-empty",children:[i.jsx(Sh,{className:"h-10 w-10 opacity-40"}),i.jsx("span",{className:"text-sm",children:e.length===0?"No work items in the pool yet.":"No work items match the current filters."})]}),!s&&!a&&m.length>0&&i.jsx("div",{className:"flex flex-col gap-2","data-testid":"workitems-list",children:m.map(k=>i.jsx(ot,{variant:"default",padding:"md",interactive:!0,className:"hover:border-primary/40",role:"button",tabIndex:0,onClick:()=>t(`/workitems/${k.id}`),onKeyDown:E=>_(E,k.id),"data-testid":`workitem-row-${k.id}`,children:i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"flex items-center gap-2 mb-1",children:i.jsx("span",{className:"text-base font-medium text-text-primary-dark truncate",children:k.title})}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx(Po,{status:rI(k.status),children:iI(k.status)}),i.jsx(ct,{variant:aI(k.type),size:"sm",children:oI(k.type)}),k.target&&i.jsx(ct,{variant:"default",size:"sm",children:k.target}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:Ww(k.createdAt)})]})]}),i.jsx("span",{className:"text-xs text-text-secondary-dark font-mono flex-shrink-0",children:k.id.slice(0,8)})]})},k.id))})]})};zV.displayName="WorkItems";const HV=()=>{const{id:t}=vh(),e=ps(),[n,s]=w.useState(null),[r,a]=w.useState(!0),[o,l]=w.useState(null),[c,d]=w.useState(!1),u=w.useCallback(async(x=!0)=>{if(t){x?a(!0):d(!0),l(null);try{const y=await xt.getWorkItem(t);s(y)}catch(y){const m=y instanceof Error?y.message:"Failed to load WorkItem";l(m)}finally{a(!1),d(!1)}}},[t]);w.useEffect(()=>{u(!0)},[u]),w.useEffect(()=>{if(!n||n.status!=="running")return;const x=setInterval(()=>{u(!1)},1e4);return()=>clearInterval(x)},[n==null?void 0:n.status,u]);const h=()=>{e("/workitems")},f=()=>{u(!1)};if(r)return i.jsx("div",{className:"flex items-center justify-center h-64","data-testid":"workitem-detail-loading",children:i.jsx(Ut,{})});if(o)return i.jsxs("div",{className:"p-6","data-testid":"workitem-detail-error",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:zr,onClick:h,className:"mb-6",children:"Back to WorkItems"}),i.jsx(ot,{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 text-lg font-medium mb-2",children:"Failed to load WorkItem"}),i.jsx("p",{className:"text-text-secondary-dark text-sm mb-4",children:o}),i.jsx(de,{variant:"secondary",size:"sm",icon:sn,onClick:()=>u(!0),children:"Retry"})]})})]});if(!n)return i.jsxs("div",{className:"p-6","data-testid":"workitem-detail-not-found",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:zr,onClick:h,className:"mb-6",children:"Back to WorkItems"}),i.jsx(ot,{variant:"default",padding:"lg",children:i.jsx(Cs,{icon:xY,title:"WorkItem not found.",compact:!0})})]});const p=FV(n);return i.jsxs("div",{className:"p-6 max-w-[1400px] mx-auto","data-testid":"workitem-detail",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:zr,onClick:h,className:"mb-4","data-testid":"workitem-detail-back",children:"Back to WorkItems"}),i.jsxs("div",{className:"mb-6","data-testid":"workitem-detail-header",children:[i.jsxs("div",{className:"flex items-start justify-between gap-4 mb-3",children:[i.jsx("div",{className:"flex-1 min-w-0",children:i.jsxs("h1",{className:"text-xl font-bold text-text-primary-dark truncate",children:["WorkItem: ",LA(n.id)," — ",n.title]})}),i.jsx(de,{variant:"secondary",size:"sm",icon:sn,onClick:f,loading:c,"data-testid":"workitem-detail-refresh",children:"Refresh"})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx(Po,{status:rI(n.status),children:iI(n.status)}),i.jsx(ct,{variant:aI(n.type),children:oI(n.type)}),i.jsxs(ct,{variant:"default",children:["Retry ",n.retryCount,"/",n.maxRetries]}),n.requestId&&i.jsx(ct,{variant:"info",children:i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(ws,{className:"h-3 w-3"}),"Request: ",LA(n.requestId)]})}),n.missionId&&i.jsx(ct,{variant:"info",children:i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(ws,{className:"h-3 w-3"}),"Mission: ",LA(n.missionId)]})}),i.jsxs("span",{className:"text-xs text-text-secondary-dark ml-2",children:["Created ",Ww(n.createdAt)]}),n.target&&i.jsxs(ct,{variant:"primary",children:["Agent: ",n.target]})]}),n.description&&i.jsx("p",{className:"mt-3 text-sm text-text-secondary-dark leading-relaxed",children:n.description})]}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[i.jsx("div",{className:"lg:col-span-2",children:i.jsxs(ot,{variant:"default",padding:"md",children:[i.jsx("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wider mb-4",children:"Activity Timeline"}),i.jsx(lI,{events:p})]})}),i.jsx("div",{className:"lg:col-span-1",children:i.jsx(UV,{item:n})})]})]})};HV.displayName="WorkItemDetail";function LA(t){return t.length<=12?t:t.slice(0,8)}const KRe=({stats:t})=>t?i.jsxs(j2,{variant:"horizontal",className:"grid-cols-2 md:grid-cols-6","data-testid":"request-summary-bar",children:[i.jsx(ii,{label:"Total Incoming",value:t.total}),i.jsx(ii,{label:"Active",value:t.active}),i.jsx(ii,{label:"Blocked",children:i.jsx("span",{className:"text-red-400",children:t.blocked})}),i.jsx(ii,{label:"Waiting",children:i.jsx("span",{className:"text-yellow-400",children:t.waitingConfirmation})}),i.jsx(ii,{label:"Done",children:i.jsx("span",{className:"text-blue-400",children:t.done})}),i.jsx(ii,{label:"Total Cost",children:i.jsx("span",{className:"text-emerald-400",children:t.totalCost>0?`$${t.totalCost.toFixed(2)}`:"$0.00"})})]}):null;function qRe(t){return{active:"Active",blocked:"Blocked",waiting_confirmation:"Waiting Confirmation",done:"Done"}[t]??t}function XRe(t){return{critical:"error",high:"warning",medium:"info",low:"default"}[t]??"default"}function YRe(t){return{critical:"Critical",high:"High",medium:"Medium",low:"Low"}[t]??t}function JRe(t){return t.charAt(0).toUpperCase()+t.slice(1)}function ZRe(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 QRe(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)}}const eIe={active:"bg-amber-500/10 text-amber-400 border-amber-500/20",blocked:"bg-red-500/10 text-red-400 border-red-500/20",waiting_confirmation:"bg-primary/10 text-primary border-primary/20",done:"bg-green-500/10 text-green-400 border-green-500/20"},tIe={active:"bg-amber-400",blocked:"bg-red-400",waiting_confirmation:"bg-primary",done:"bg-green-400"},nIe=({status:t,label:e,className:n=""})=>{const s=eIe[t],r=tIe[t],a=e??qRe(t),o=t==="active";return i.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded-full border ${s} ${n}`.trim(),"data-status":t,"data-testid":`request-status-pill-${t}`,children:[i.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${r} ${o?"animate-pulse":""}`.trim(),"aria-hidden":"true"}),a]})},sIe={slack:Xp,email:Yz,chat:Jz,api:E1,manual:Zz},rIe=({item:t})=>{const e=t.status==="done"?"active":t.status==="in_progress"?"connecting":"inactive";return i.jsxs("div",{className:"flex items-center gap-2.5 py-1.5 border-b border-border-dark last:border-b-0","data-testid":`request-child-${t.id}`,children:[i.jsx(Mo,{status:e,size:"sm",pulse:!1}),i.jsx("span",{className:"flex-1 text-xs text-text-secondary-dark",children:t.label}),t.tag&&i.jsx(ct,{variant:"error",size:"sm",children:t.tag}),t.progress!==void 0&&i.jsx("div",{className:"w-20 h-1.5 bg-background-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full bg-primary rounded-full transition-all duration-300",style:{width:`${t.progress}%`}})}),t.assignee&&i.jsx("span",{className:"text-xs text-text-secondary-dark/60",children:t.assignee}),t.dueDate&&i.jsx("span",{className:"text-xs text-text-secondary-dark/60 whitespace-nowrap",children:t.dueDate})]})},iIe=({request:t})=>{const[e,n]=w.useState(!1),s=ps(),r=!!(t.childItems&&t.childItems.length>0),a=w.useCallback(()=>{s(`/tasks/${t.id}`)},[s,t.id]),o=w.useCallback(f=>{f.stopPropagation(),r&&n(p=>!p)},[r]),l=w.useCallback(f=>{f.key==="Enter"?(f.preventDefault(),a()):f.key===" "&&(f.preventDefault(),r&&n(p=>!p))},[a,r]),c=sIe[t.source]??Sh,d=XRe(t.priority),u=JRe(t.source),h=ZRe(t.updatedAt);return i.jsx("li",{className:"list-none",children:i.jsxs(ot,{variant:"default",padding:"none",className:"overflow-hidden hover:border-border-light transition-colors","data-testid":`request-row-${t.id}`,children:[i.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 cursor-pointer hover:bg-background-dark/30 transition-colors",role:"button",tabIndex:0,"aria-label":`Open request: ${t.title}`,onClick:a,onKeyDown:l,children:[i.jsx(c,{className:"h-5 w-5 text-text-secondary-dark flex-shrink-0","aria-label":u}),i.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-1",children:[i.jsxs("div",{className:"flex items-start gap-2","data-testid":"request-tier-top",children:[i.jsx("span",{className:"text-[15px] font-semibold leading-5 text-text-primary-dark line-clamp-2 flex-1 min-w-0",children:t.title}),i.jsx(nIe,{status:t.status,className:"flex-shrink-0"})]}),i.jsxs("div",{className:"flex items-center gap-3 text-xs text-text-secondary-dark/70 flex-wrap","data-testid":"request-tier-bottom",children:[i.jsx(ct,{variant:d,size:"sm",children:YRe(t.priority)}),t.category&&i.jsx("span",{"data-testid":"request-meta-category",className:"text-text-secondary-dark",children:t.category}),t.missionLink&&i.jsxs("span",{"data-testid":"request-meta-mission",className:"whitespace-nowrap",children:["Mission: ",i.jsx("span",{className:"text-primary",children:t.missionLink})]}),i.jsxs("span",{"data-testid":"request-meta-workitems",className:"inline-flex items-center gap-1 whitespace-nowrap",title:`${t.workItemCount} work item${t.workItemCount===1?"":"s"}`,children:[i.jsx(Dx,{className:"h-3 w-3","aria-hidden":"true"}),t.workItemCount,i.jsxs("span",{className:"sr-only",children:[" ","work item",t.workItemCount===1?"":"s"]})]}),i.jsx("span",{"data-testid":"request-meta-updated",className:"ml-auto whitespace-nowrap",children:h})]})]}),r&&i.jsx(Ft,{icon:e?$r:Wr,size:"xs",onClick:o,className:"flex-shrink-0","aria-label":e?"Collapse work items":"Expand work items"})]}),e&&i.jsxs("div",{className:"border-t border-border-dark px-4 py-2 space-y-1.5","data-testid":"request-children",children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-secondary-dark/60",children:[i.jsx("span",{className:"uppercase tracking-wide",children:"Source"}),i.jsx(ct,{variant:"default",size:"sm",children:u}),t.ownerAgent&&i.jsxs("span",{className:"text-text-secondary-dark",children:["via ",t.ownerAgent]})]}),r&&i.jsx("div",{children:t.childItems.map(f=>i.jsx(rIe,{item:f},f.id))})]})]})})};function aIe(t){switch(t){case"open":case"ready":case"running":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 oIe(t){switch(t){case"high":return"high";case"low":return"low";default:return"medium"}}function lIe(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:aIe(e.status||""),priority:oIe(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}}).sort((e,n)=>new Date(n.updatedAt).getTime()-new Date(e.updatedAt).getTime())}const cIe=new Set(["critical","high"]),dIe=({activeFilter:t,secondaryFilters:e,searchQuery:n,onStatsLoaded:s})=>{const[r,a]=w.useState([]),[o,l]=w.useState(!0),[c,d]=w.useState(null),u=w.useCallback(async()=>{l(!0),d(null);try{const p=await xt.getRequests();if(!Array.isArray(p)){console.warn("[RequestList] getRequests returned non-array:",typeof p,p),a([]);return}const x=lIe(p);a(x)}catch(p){console.warn("[RequestList] loadRequests error:",p),d(p instanceof Error?p.message:"Failed to load requests"),a([])}finally{l(!1)}},[]);w.useEffect(()=>{u()},[u]);const h=w.useMemo(()=>QRe(r),[r]);w.useEffect(()=>{s(h)},[h,s]);const f=w.useMemo(()=>{let p=r;if(t!=="all"&&(p=p.filter(x=>x.status===t)),e&&e.size>0&&(e.has("urgent")&&(p=p.filter(x=>cIe.has(x.priority))),e.has("assigned_to_me")&&(p=p.filter(x=>x.requester==="user"))),n.trim()){const x=n.toLowerCase();p=p.filter(y=>{var m;return y.title.toLowerCase().includes(x)||y.requester.toLowerCase().includes(x)||((m=y.missionLink)==null?void 0:m.toLowerCase().includes(x))})}return p},[r,t,e,n]);return o?i.jsx("div",{"data-testid":"request-list-loading",children:i.jsx(N1,{count:4})}):c?i.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-16 text-text-secondary-dark","data-testid":"request-list-error",children:[i.jsx("span",{className:"text-sm text-red-400",children:c}),i.jsx(de,{variant:"link",onClick:u,children:"Retry"})]}):f.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-16 text-text-secondary-dark","data-testid":"request-list-empty",children:[i.jsx(Sh,{className:"h-10 w-10 opacity-40"}),i.jsx("span",{className:"text-sm",children:r.length===0?"No requests found. Requests will appear here when user messages are processed.":"No requests match the current filters."})]}):i.jsx("div",{className:"flex flex-col gap-2","data-testid":"request-list",children:f.map(p=>i.jsx(iIe,{request:p},p.id))})},uIe=()=>{const[t,e]=w.useState(null),[n,s]=w.useState("active"),[r,a]=w.useState(new Set),[o,l]=w.useState(""),c=w.useCallback(f=>{e(f)},[]),d=w.useCallback(f=>{a(p=>{const x=new Set(p);return x.has(f)?x.delete(f):x.add(f),x})},[]),u=w.useMemo(()=>[{value:"all",label:"All",count:t==null?void 0:t.total},{value:"active",label:"Active",count:t==null?void 0:t.active},{value:"blocked",label:"Blocked",count:t==null?void 0:t.blocked},{value:"waiting_confirmation",label:"Waiting",count:t==null?void 0:t.waitingConfirmation},{value:"done",label:"Done",count:t==null?void 0:t.done}],[t]),h=w.useMemo(()=>[{value:"assigned_to_me",label:"Assigned to Me"},{value:"urgent",label:"Urgent"}],[]);return i.jsxs("div",{className:"p-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[i.jsxs("div",{className:"mb-6","data-testid":"requests-page-header",children:[i.jsx("h1",{className:"text-2xl font-bold text-text-primary-dark",children:"Requests"}),i.jsx("p",{className:"text-sm text-text-secondary-dark",children:"Monitor and triage incoming work from all channels."})]}),i.jsx(KRe,{stats:t}),i.jsx(Od,{tabs:u,activeTab:n,onTabChange:f=>s(f),searchPlaceholder:"Search requests...",searchValue:o,onSearchChange:l,secondaryFilters:h,activeSecondaryFilters:r,onSecondaryFilterToggle:f=>d(f)}),i.jsx(dIe,{activeFilter:n,secondaryFilters:r,searchQuery:o,onStatsLoaded:c})]})},x5={open:"text-blue-400",in_progress:"text-amber-400",blocked:"text-red-400",waiting_confirmation:"text-primary",done:"text-green-400",cancelled:"text-text-secondary-dark"};function _N(t){return{open:"Open",in_progress:"In Progress",blocked:"Blocked",waiting_confirmation:"Waiting Confirmation",done:"Completed",cancelled:"Cancelled"}[t]??t}function hIe(t){return{open:"active",in_progress:"running",blocked:"blocked",waiting_confirmation:"paused",done:"completed",cancelled:"inactive"}[t]??"pending"}const y5=["open","in_progress","done"],fIe=({currentStatus:t})=>{const e=y5.indexOf(t),n=t==="cancelled",s=t==="blocked";return i.jsxs("div",{className:"flex items-center gap-1","data-testid":"request-progress-rail",children:[y5.map((r,a)=>{const o=e>=0&&a<=e,l=r===t;return i.jsxs(Mn.Fragment,{children:[a>0&&i.jsx("div",{className:`flex-1 h-0.5 ${o?"bg-green-500":"bg-border-dark"}`}),i.jsxs("div",{className:`flex items-center gap-1.5 px-2 py-1 rounded text-xs font-medium ${l?`${x5[r]||"text-blue-400"} bg-surface-dark border border-primary/30`:o?"text-green-400 bg-green-500/10":"text-text-secondary-dark bg-surface-dark"}`,children:[o&&!l&&i.jsx(ra,{className:"h-3 w-3"}),_N(r)]})]},r)}),(n||s)&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"flex-1 h-0.5 bg-border-dark"}),i.jsx("div",{className:`flex items-center gap-1.5 px-2 py-1 rounded text-xs font-medium ${x5[t]||"text-text-secondary-dark"} bg-surface-dark border border-red-500/30`,children:_N(t)})]})]})},pIe=({workItems:t,onItemClick:e})=>{const[n,s]=w.useState(null);return t.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-text-secondary-dark","data-testid":"request-workitems-empty",children:[i.jsx(Sh,{className:"h-8 w-8 opacity-40"}),i.jsx("span",{className:"text-sm",children:"No work items associated with this request yet."})]}):i.jsx("div",{className:"flex flex-col gap-2","data-testid":"request-workitems-list",children:t.map(r=>{const a=n===r.id,o=a?FV(r):[];return i.jsxs(ot,{variant:"default",padding:"none",className:"overflow-hidden hover:border-primary/40 transition-colors","data-testid":`request-workitem-${r.id}`,children:[i.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-background-dark/30 transition-colors",role:"button",tabIndex:0,onClick:()=>s(a?null:r.id),onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),s(a?null:r.id))},children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"flex items-center gap-2 mb-1",children:i.jsx("span",{className:"text-sm font-medium text-text-primary-dark truncate",children:r.title})}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx(Po,{status:rI(r.status),children:iI(r.status)}),i.jsx(ct,{variant:aI(r.type),size:"sm",children:oI(r.type)}),r.target&&i.jsx(ct,{variant:"default",size:"sm",children:r.target}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:Ww(r.createdAt)})]})]}),i.jsx(de,{variant:"link",size:"xs",onClick:l=>{l.stopPropagation(),e(r.id)},className:"flex-shrink-0","data-testid":`request-workitem-detail-link-${r.id}`,children:"Details"})]}),a&&i.jsx("div",{className:"border-t border-border-dark px-4 py-3","data-testid":`request-workitem-timeline-${r.id}`,children:i.jsx(lI,{events:o})})]},r.id)})})},GV=()=>{const{id:t}=vh(),e=ps(),[n,s]=w.useState(null),[r,a]=w.useState([]),[o,l]=w.useState(!0),[c,d]=w.useState(null),[u,h]=w.useState(!1),f=w.useCallback(async(b=!0)=>{if(t){b?l(!0):h(!0),d(null);try{const[_,k]=await Promise.all([xt.getRequest(t),xt.getWorkItemsByRequest(t)]);s(_),a(k.sort((E,M)=>new Date(M.createdAt).getTime()-new Date(E.createdAt).getTime()))}catch(_){const k=_ instanceof Error?_.message:"Failed to load request";d(k)}finally{l(!1),h(!1)}}},[t]);w.useEffect(()=>{f(!0)},[f]),w.useEffect(()=>{if(!n||n.status==="done"||n.status==="cancelled")return;const b=setInterval(()=>{f(!1)},15e3);return()=>clearInterval(b)},[n==null?void 0:n.status,f]);const p=w.useCallback(()=>{e("/tasks")},[e]),x=w.useCallback(b=>{e(`/workitems/${b}`)},[e]),y=w.useCallback(()=>{f(!1)},[f]),m=w.useCallback(async b=>{if(t)try{const _=b==="confirmed"?"done":"cancelled";await xt.updateRequest(t,{status:_}),f(!1)}catch(_){const k=_ instanceof Error?_.message:"Failed to update request";d(k)}},[t,f]),g=w.useMemo(()=>n?n.totalInputTokens+n.totalOutputTokens:0,[n]),v=w.useMemo(()=>{if(!n)return"";const b=new Date(n.createdAt).getTime(),k=(n.completedAt?new Date(n.completedAt).getTime():Date.now())-b,E=Math.floor(k/6e4),M=Math.floor(E/60);return E<1?"< 1m":M<1?`${E}m`:`${M}h ${E%60}m`},[n]);return o?i.jsx("div",{className:"flex items-center justify-center h-64","data-testid":"request-detail-loading",children:i.jsx(Ut,{})}):c?i.jsxs("div",{className:"p-6","data-testid":"request-detail-error",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:zr,onClick:p,className:"mb-6",children:"Back to Requests"}),i.jsx(ot,{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 text-lg font-medium mb-2",children:"Failed to load Request"}),i.jsx("p",{className:"text-text-secondary-dark text-sm mb-4",children:c}),i.jsx(de,{variant:"secondary",size:"sm",icon:sn,onClick:()=>f(!0),children:"Retry"})]})})]}):n?i.jsxs("div",{className:"p-6 max-w-[1200px] mx-auto","data-testid":"request-detail",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:zr,onClick:p,className:"mb-4","data-testid":"request-detail-back",children:"Back to Requests"}),i.jsxs("div",{className:"mb-6","data-testid":"request-detail-header",children:[i.jsxs("div",{className:"flex items-start justify-between gap-4 mb-3",children:[i.jsx("div",{className:"flex-1 min-w-0",children:i.jsx("h1",{className:"text-xl font-bold text-text-primary-dark",children:n.title})}),i.jsx(de,{variant:"secondary",size:"sm",icon:sn,onClick:y,loading:u,"data-testid":"request-detail-refresh",children:"Refresh"})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-4",children:[i.jsx(Po,{status:hIe(n.status),children:_N(n.status)}),n.priority&&n.priority!=="normal"&&i.jsx(ct,{variant:n.priority==="high"?"warning":"default",size:"sm",children:n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}),n.intentCategory&&i.jsx(ct,{variant:"info",size:"sm",children:i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(s6,{className:"h-3 w-3"}),n.intentCategory.replace(/_/g," ")]})}),n.intentLevel&&i.jsx(ct,{variant:"default",size:"sm",children:n.intentLevel}),n.requiresConfirmation&&i.jsx(ct,{variant:"warning",size:"sm",children:"Requires Confirmation"}),i.jsxs("span",{className:"text-xs text-text-secondary-dark ml-2",children:["Created ",Ww(n.createdAt)]})]}),i.jsx(fIe,{currentStatus:n.status})]}),n.requiresConfirmation&&n.status==="waiting_confirmation"&&i.jsxs(ot,{padding:"md",className:"flex gap-3 mt-4","data-testid":"request-action-area",children:[i.jsx("span",{className:"text-sm text-text-secondary-dark mr-auto flex items-center",children:"This request requires your confirmation before completing"}),i.jsx(de,{variant:"secondary",size:"sm",onClick:()=>m("rejected"),children:"Reject"}),i.jsx(de,{variant:"primary",size:"sm",onClick:()=>m("confirmed"),children:"Approve"})]}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6",children:[i.jsx("div",{className:"lg:col-span-2",children:i.jsxs(ot,{variant:"default",padding:"md",children:[i.jsx("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(Za,{className:"h-4 w-4"}),"Original Message"]})}),n.description?i.jsx("p",{className:"text-sm text-text-primary-dark leading-relaxed whitespace-pre-wrap",children:n.description}):i.jsx("p",{className:"text-sm text-text-secondary-dark italic",children:"No description provided."}),n.sourceConversationItemId&&i.jsx("div",{className:"mt-4 pt-4 border-t border-border-dark",children:i.jsxs("span",{className:"text-xs text-text-secondary-dark",children:["Source: ",i.jsx("span",{className:"font-mono",children:n.sourceConversationItemId})]})}),n.tags.length>0&&i.jsx("div",{className:"mt-4 pt-4 border-t border-border-dark flex items-center gap-2 flex-wrap",children:n.tags.map(b=>i.jsx(ct,{variant:"default",size:"sm",children:b},b))})]})}),i.jsx("div",{className:"lg:col-span-1",children:i.jsxs(ot,{variant:"default",padding:"md",children:[i.jsx("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:"Statistics"}),i.jsxs("div",{className:"flex flex-col gap-3",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-text-secondary-dark",children:[i.jsx(Lx,{className:"h-3.5 w-3.5"}),"Total Tokens"]}),i.jsx("span",{className:"text-sm font-medium text-text-primary-dark",children:fx(g)})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"flex items-center gap-1.5 text-xs text-text-secondary-dark pl-5",children:"Input"}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:fx(n.totalInputTokens)})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"flex items-center gap-1.5 text-xs text-text-secondary-dark pl-5",children:"Output"}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:fx(n.totalOutputTokens)})]}),i.jsx("div",{className:"border-t border-border-dark"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-text-secondary-dark",children:[i.jsx(S2,{className:"h-3.5 w-3.5"}),"Total Cost"]}),i.jsx("span",{className:"text-sm font-medium text-text-primary-dark",children:BV(n.totalCost)})]}),i.jsx("div",{className:"border-t border-border-dark"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-text-secondary-dark",children:[i.jsx(vs,{className:"h-3.5 w-3.5"}),"Elapsed Time"]}),i.jsx("span",{className:"text-sm font-medium text-text-primary-dark",children:v})]}),i.jsx("div",{className:"border-t border-border-dark"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-text-secondary-dark",children:[i.jsx(Dx,{className:"h-3.5 w-3.5"}),"Work Items"]}),i.jsx("span",{className:"text-sm font-medium text-text-primary-dark",children:r.length})]})]})]})})]}),i.jsxs("div",{"data-testid":"request-detail-workitems",children:[i.jsx("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(Dx,{className:"h-4 w-4"}),"Execution Timeline (",r.length," work items)"]})}),i.jsx(pIe,{workItems:r,onItemClick:x})]})]}):i.jsxs("div",{className:"p-6","data-testid":"request-detail-not-found",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:zr,onClick:p,className:"mb-6",children:"Back to Requests"}),i.jsx(ot,{variant:"default",padding:"lg",children:i.jsx(Cs,{icon:Za,title:"Request not found.",compact:!0})})]})};GV.displayName="RequestDetail";const mIe=()=>{},gIe=({onSaved:t})=>{const[e,n]=w.useState(!1),[s,r]=w.useState(""),[a,o]=w.useState(!1);w.useEffect(()=>{const c=()=>{o(!!b0()),n(!0)};return window.addEventListener(aM,c),()=>window.removeEventListener(aM,c)},[]);const l=w.useCallback(c=>{c.preventDefault();const d=s.trim();d&&(T8(d),n(!1),t?t():window.location.reload())},[s,t]);return e?i.jsx("div",{className:"relative z-[100]",children:i.jsx(Kr,{isOpen:!0,onClose:mIe,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(xs,{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:C1,disabled:!s.trim(),"data-testid":"api-token-submit",children:"Save and reload"})})]})})}):null};function xIe(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 v5(t){return!Ste.some(e=>t===e||t.startsWith(`${e}/`))}function b5(){try{return window.localStorage.getItem(cM)==="1"}catch{return!1}}function yIe(t){try{t?window.localStorage.setItem(cM,"1"):window.localStorage.removeItem(cM)}catch{}}const vIe=()=>{const t=uo(),e=ps(),n=w.useRef(t.pathname);return n.current=t.pathname,w.useEffect(()=>{if(b5()||!v5(n.current))return;let s=!1;return eo.getStatus().then(r=>{s||b5()||!v5(n.current)||xIe(r)&&e(J2,{replace:!0})}).catch(()=>{}),()=>{s=!0}},[]),null},bIe=({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(Mn.Fragment,{children:[i.jsxs("div",{className:"flex flex-col items-center","data-testid":`step-${s}`,children:[i.jsx("div",{className:na("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($n,{className:"w-4 h-4"}):s+1}),i.jsx("span",{className:na("mt-1.5 text-[10px] font-medium uppercase tracking-wide",a?"text-primary":"text-text-secondary-dark"),children:n})]}),!o&&i.jsx("div",{className:na("h-0.5 w-12 mx-1 mt-[-12px] transition-colors duration-200",r?"bg-primary":"bg-border-dark")})]},n)})});function _5(t){return t.status!=="running"}function _Ie(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 SIe(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 wIe=({questions:t,submitLabel:e,submitting:n=!1,error:s=null,serverProblems:r=[],onSubmit:a})=>{const[o,l]=w.useState(()=>_Ie(t)),[c,d]=w.useState([]),u=new Set([...c,...r]),h=(x,y)=>{l(m=>({...m,[x]:y})),d(m=>m.filter(g=>g!==x))},f=(x,y)=>{const m=o[x],g=Array.isArray(m)?m:[];h(x,g.includes(y)?g.filter(v=>v!==y):[...g,y])},p=x=>{x.preventDefault();const y=SIe(t,o);d(y),y.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 y=`bundle-q-${x.id}`,m=o[x.id],g=u.has(x.id);return i.jsxs(Ei,{children:[i.jsx(gt,{id:`${y}-label`,htmlFor:x.type==="multiselect"?void 0:y,required:x.required,children:x.label}),x.type==="text"&&i.jsx(Bt,{id:y,value:typeof m=="string"?m:"",placeholder:x.placeholder,error:g,onChange:v=>h(x.id,v.target.value)}),x.type==="textarea"&&i.jsx(qs,{id:y,rows:3,value:typeof m=="string"?m:"",placeholder:x.placeholder,error:g,onChange:v=>h(x.id,v.target.value)}),x.type==="select"&&i.jsxs(pn,{id:y,value:typeof m=="string"?m:"",error:g,onChange:v=>h(x.id,v.target.value),children:[!x.required&&x.default===""&&i.jsx("option",{value:"",children:"—"}),x.required&&i.jsx("option",{value:"",children:"Select…"}),(x.options??[]).map(v=>i.jsx("option",{value:v.value,children:v.label??v.value},v.value))]}),x.type==="multiselect"&&i.jsx("div",{role:"group","aria-labelledby":`${y}-label`,className:"flex flex-wrap gap-2",id:y,children:(x.options??[]).map(v=>{const b=Array.isArray(m)&&m.includes(v.value);return i.jsx(de,{type:"button",size:"sm",variant:b?"primary":"secondary","aria-pressed":b,"data-testid":`bundle-option-${x.id}-${v.value}`,onClick:()=>f(x.id,v.value),children:v.label??v.value},v.value)})}),x.help&&i.jsx(Ql,{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(et,{variant:"error",size:"sm",children:s}),i.jsx(de,{type:"submit",fullWidth:!0,loading:n,"data-testid":"bundle-deploy",children:e})]})},DA={LIST:"/api/bundles",detail:t=>`/api/bundles/${encodeURIComponent(t)}`,APPLY:"/api/bundles/apply",job:t=>`/api/bundles/apply/${encodeURIComponent(t)}`},CIe=1500,kIe={queued:"Waiting",running:"In progress",done:"Done",failed:"Failed",pending:"Finishes automatically later",skipped:"Skipped"},EIe={"crewly-agent":"Crewly Agent (DeepSeek)","claude-code":"Claude Code","codex-cli":"Codex","gemini-cli":"Gemini CLI","opencode-cli":"OpenCode","antigravity-cli":"Antigravity CLI"},AIe={entry:"Entry (2 vCPU, 4 GB)",standard:"Standard (4 vCPU, 8 GB)",advanced:"Advanced (8 vCPU, 16 GB)"};class d_ extends Error{constructor(e,n=null,s=[],r=[]){super(e),this.code=n,this.missing=s,this.invalid=r,this.name="BundleRequestError"}}async function OA(t,e){var s;let n;try{n=(await t()).data}catch(r){if(F1(r)){const a=((s=r.response)==null?void 0:s.data)??{};throw new d_(a.error||r.message||e,a.code??null,a.missing??[],a.invalid??[])}throw r instanceof Error?r:new d_(e)}if(!(n!=null&&n.success)||n.data===void 0||n.data===null)throw new d_((n==null?void 0:n.error)||e);return n.data}class TIe{async getBundle(e){return OA(()=>We.get(DA.detail(e)),"Couldn't load this bundle")}async apply(e,n,s){return(await OA(()=>We.post(DA.APPLY,{templateId:e,answers:n,...s?{runtime:s}:{}}),"Deploy failed")).deployment}async getJob(e){return OA(()=>We.get(DA.job(e)),"Couldn't load deploy progress")}}const kb=new TIe,MIe=({status:t})=>t==="done"?i.jsx(ra,{className:"h-4 w-4 shrink-0 text-emerald-400","aria-hidden":!0}):t==="failed"?i.jsx(ul,{className:"h-4 w-4 shrink-0 text-red-400","aria-hidden":!0}):t==="running"?i.jsx(HT,{className:"h-4 w-4 shrink-0 animate-spin text-primary","aria-hidden":!0}):t==="pending"?i.jsx(vs,{className:"h-4 w-4 shrink-0 text-amber-400","aria-hidden":!0}):i.jsx(_2,{className:"h-4 w-4 shrink-0 text-text-secondary-dark","aria-hidden":!0}),NIe=({templateId:t,onBack:e,onDone:n,pollIntervalMs:s=CIe})=>{const[r,a]=w.useState(null),[o,l]=w.useState(null),[c,d]=w.useState(null),[u,h]=w.useState(!1),[f,p]=w.useState(null),[x,y]=w.useState([]),m=w.useRef(null),g=w.useCallback(async()=>{l(null);try{const k=await kb.getBundle(t);a(k.bundle),k.deployment&&d(k.deployment)}catch(k){l(k instanceof Error?k.message:String(k))}},[t]);w.useEffect(()=>{g()},[g]),w.useEffect(()=>{if(!(!c||_5(c)))return m.current=setTimeout(()=>{kb.getJob(c.jobId).then(d).catch(k=>p(k instanceof Error?k.message:String(k)))},s),()=>{m.current&&clearTimeout(m.current)}},[c,s]);const v=async k=>{h(!0),p(null),y([]);try{d(await kb.apply(t,k))}catch(E){E instanceof d_&&y([...E.missing,...E.invalid].map(M=>M.id)),p(E instanceof Error?E.message:String(E))}finally{h(!1)}},b=async()=>{h(!0),p(null);try{d(await kb.apply(t,{}))}catch(k){p(k instanceof Error?k.message:String(k))}finally{h(!1)}},_=()=>{const k=(c==null?void 0:c.teams[0])??null;n({starterId:t,teamId:(k==null?void 0:k.teamId)??null,teamName:(k==null?void 0:k.name)??null,suggestions:[],bundle:!0})};if(o)return i.jsx(et,{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:sn,onClick:()=>void g(),children:"Retry"}),i.jsx(de,{type:"button",size:"sm",variant:"ghost",icon:zr,onClick:e,children:"Choose another"})]})]})});if(!r)return i.jsx(Ut,{centered:!0,text:"Loading bundle…"});if(c){const k=_5(c),E=c.steps.some(T=>T.status==="failed"),M=c.connectors.filter(T=>T.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:k?`"${r.label}" is deployed.`:`Deploying "${r.label}"…`}),i.jsx("ul",{className:"space-y-2",children:c.steps.map(T=>i.jsxs("li",{className:"flex items-start gap-2 text-sm","data-testid":`bundle-step-${T.id}`,children:[i.jsx(MIe,{status:T.status}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("span",{className:"text-text-primary-dark",children:T.label})," ",i.jsxs("span",{className:"text-xs text-text-secondary-dark",children:["· ",kIe[T.status]]}),(T.error??T.message)&&i.jsx("p",{className:"text-xs text-text-secondary-dark",children:T.error??T.message})]})]},T.id))}),M.length>0&&i.jsx(et,{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:M.map(T=>i.jsxs("li",{children:[i.jsxs("a",{className:"text-primary underline",href:T.connectPath,children:[T.id,T.products.length>0?` (${T.products.join(", ")})`:""]}),T.required?"":" (optional)",": ",T.why]},T.id))})}),f&&i.jsx(et,{variant:"error",size:"sm",children:f}),k&&i.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[E&&i.jsx(de,{type:"button",variant:"secondary",icon:sn,loading:u,onClick:()=>void b(),"data-testid":"bundle-retry",children:"Retry failed steps"}),i.jsx(de,{type:"button",fullWidth:!0,onClick:_,"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(ct,{variant:"primary",children:EIe[r.recommendedRuntime]??r.recommendedRuntime}),i.jsx(ct,{children:AIe[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(k=>i.jsx("li",{children:k},k))})]}),i.jsxs("p",{className:"mt-2 text-xs text-text-secondary-dark",children:["Members: ",r.teams.flatMap(k=>k.members.map(E=>`${E.name} (${E.title})`)).join(", ")]})]}),i.jsx(wIe,{questions:r.questions,submitLabel:`Deploy "${r.label}"`,submitting:u,error:f,serverProblems:x,onSubmit:k=>void v(k)}),i.jsx(de,{type:"button",variant:"ghost",icon:zr,onClick:e,children:"Choose another"})]})},jIe=({onDone:t})=>{const[e,n]=w.useState(null),[s,r]=w.useState(null),[a,o]=w.useState(null),[l,c]=w.useState(null),[d,u]=w.useState(!1),[h,f]=w.useState(null),p=async()=>{o(null);try{const m=await oc.getStarters();n(m),r(g=>{var v;return g??((v=m.find(b=>b.recommended)??m[0])==null?void 0:v.id)??null})}catch(m){o(m instanceof Error?m.message:String(m))}};w.useEffect(()=>{p()},[]);const x=async()=>{var g,v;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 oc.createStarterTeam(m.id);t({starterId:m.id,teamId:((g=b.team)==null?void 0:g.id)??null,teamName:((v=b.team)==null?void 0:v.name)??null,suggestions:m.suggestions})}catch(b){c(b instanceof Error?b.message:String(b))}finally{u(!1)}}};if(a)return i.jsx(et,{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:sn,onClick:()=>void p(),children:"Retry"})]})});if(!e)return i.jsx(Ut,{centered:!0,text:"Loading team templates…"});if(h)return i.jsx(NIe,{templateId:h,onBack:()=>f(null),onDone:t});const y=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(ot,{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:v=>{(v.key==="Enter"||v.key===" ")&&(v.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(ct,{variant:"primary",children:"Recommended"}),m.kind==="bundle"&&i.jsx(ct,{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(is,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),m.members.map(v=>v.name).join(", ")]})]}),g&&i.jsx($n,{className:"h-5 w-5 shrink-0 text-primary","aria-hidden":!0})]})},m.id)})}),l&&i.jsx(et,{variant:"error",size:"sm",children:l}),i.jsx(de,{type:"button",fullWidth:!0,loading:d,disabled:!y,onClick:()=>void x(),"data-testid":"starter-create",children:(y==null?void 0:y.members.length)===0?"Start with just the Orc":(y==null?void 0:y.kind)==="bundle"?`Next: details for "${y.label}"`:`Create "${(y==null?void 0:y.label)??""}"`})]})},RIe=4e3,IIe=({suggestions:t,teamId:e,teamName:n,onSent:s})=>{const[r,a]=w.useState(""),[o,l]=w.useState(!1),[c,d]=w.useState(null),[u,h]=w.useState(null),f=r.trim(),p=async()=>{if(f){l(!0),d(null);try{const x=await oc.sendFirstTask(f,e);h(x),s(x)}catch(x){d(x instanceof Error?x.message:String(x))}finally{l(!1)}}};return u?i.jsx(et,{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(qs,{"aria-label":"First task",rows:4,maxLength:RIe,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(et,{variant:"error",size:"sm",children:c}),i.jsx(de,{type:"button",fullWidth:!0,icon:f0,loading:o,disabled:!f,onClick:()=>void p(),"data-testid":"first-task-send",children:"Send it"})]})};async function BA(t,e){var s;let n;try{n=(await t()).data}catch(r){if(F1(r)){const a=(s=r.response)==null?void 0:s.data;throw new Error((a==null?void 0:a.error)||(a==null?void 0:a.message)||r.message||e)}throw r instanceof Error?r:new Error(e)}if(!(n!=null&&n.success)||!n.data)throw new Error((n==null?void 0:n.error)||(n==null?void 0:n.message)||e);return n.data}class PIe{async start(e){return BA(()=>We.post(Ek.START,e?{deviceName:e}:{}),"Could not reach Crewly Cloud")}async status(){return BA(()=>We.get(Ek.STATUS),"Could not read pairing status")}async cancel(){return BA(()=>We.post(Ek.CANCEL),"Could not cancel")}}const FA=new PIe,WV={start:"Connect with your phone",intro:"No need to be at this machine: scan the code or open the link on your phone, sign in and tap Approve. This machine connects by itself.",scan:"Scan with your phone, or open:",code:"Check the code matches",waiting:"Waiting for you to approve on your phone…",cancel:"Cancel",connected:t=>`Connected to Crewly Cloud${t?` (${t})`:""}`,expired:"The link expired. Get a new one.",denied:"The request was denied on crewlyai.com.",cancelled:"Cancelled.",retry:"Get a new link"},LIe=({labels:t=WV,autoStart:e=!1,onConnected:n})=>{const[s,r]=w.useState(null),[a,o]=w.useState(null),[l,c]=w.useState(!1),d=w.useRef(!1),u=w.useCallback(async()=>{c(!0),o(null);try{r(await FA.start())}catch(y){o(y instanceof Error?y.message:String(y))}finally{c(!1)}},[]);w.useEffect(()=>{e&&u()},[e,u]);const h=(s==null?void 0:s.state)==="pending";w.useEffect(()=>{if(!h)return;const y=setInterval(()=>{FA.status().then(r).catch(()=>{})},cne);return()=>clearInterval(y)},[h]),w.useEffect(()=>{(s==null?void 0:s.state)==="connected"&&!d.current&&(d.current=!0,n==null||n(s.tier))},[s,n]);const f=async()=>{try{r(await FA.cancel())}catch(y){o(y instanceof Error?y.message:String(y))}};if((s==null?void 0:s.state)==="connected")return i.jsx(et,{variant:"success",icon:ra,title:t.connected(s.tier),"data-testid":"cloud-pairing-connected",children:s.email??""});if((s==null?void 0:s.state)==="pending"&&s.verificationUrl)return i.jsxs("div",{className:"space-y-4","data-testid":"cloud-pairing-pending",children:[i.jsx("p",{className:"text-sm text-text-secondary-dark",children:t.intro}),i.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-2xl border border-border-dark p-4",children:[i.jsx("div",{className:"rounded-xl bg-white p-2","data-testid":"cloud-pairing-qr",children:i.jsx(R1,{value:s.verificationUrl,size:dne,level:"M"})}),i.jsx("p",{className:"text-xs text-text-secondary-dark",children:t.scan}),i.jsxs("a",{href:s.verificationUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex max-w-full items-center gap-1 break-all text-sm text-primary underline","data-testid":"cloud-pairing-link",children:[s.verificationUrl," ",i.jsx(ws,{className:"h-3 w-3 shrink-0","aria-hidden":!0})]}),i.jsx("p",{className:"text-xs text-text-secondary-dark",children:t.code}),i.jsx("p",{className:"font-mono text-2xl font-bold tracking-widest text-text-primary-dark select-all cursor-text break-all","data-testid":"cloud-pairing-code",onClick:y=>U1(y.currentTarget),children:s.userCode})]}),i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-secondary-dark","data-testid":"cloud-pairing-waiting",children:[i.jsx(Ut,{size:"xs",centered:!1}),t.waiting]}),i.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>void f(),"data-testid":"cloud-pairing-cancel",children:t.cancel})]})]});const p={expired:t.expired,denied:t.denied,cancelled:t.cancelled},x=s?p[s.state]??(s.state==="error"?s.error:void 0):void 0;return i.jsxs("div",{className:"space-y-3","data-testid":"cloud-pairing-idle",children:[(a||x)&&i.jsx(et,{variant:a||(s==null?void 0:s.state)==="error"||(s==null?void 0:s.state)==="denied"?"error":"warning",size:"sm",children:a??x}),i.jsx(de,{type:"button",fullWidth:!0,icon:n6,loading:l,onClick:()=>void u(),"data-testid":"cloud-pairing-start",children:s||a?t.retry:t.start})]})},DIe=({connected:t,tier:e,tokenPageSignInUrl:n,onConnected:s,navigateTo:r=a=>window.location.assign(a)})=>{const[a,o]=w.useState(!1),[l,c]=w.useState(""),[d,u]=w.useState(""),[h,f]=w.useState(!1),[p,x]=w.useState(null);if(t)return i.jsxs(et,{variant:"success",icon:ra,title:"Connected to Crewly Cloud","data-testid":"cloud-connected",children:[e?`Plan: ${e}. `:"","You can use Crewly from your phone now."]});const y=async()=>{f(!0),x(null);try{await oc.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(LIe,{autoStart:!0,labels:WV,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:sh,onClick:()=>r(mne(window.location.origin,tj("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(ws,{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(gt,{htmlFor:"cloud-token",children:"Token"}),i.jsx(Bt,{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(gt,{htmlFor:"cloud-refresh-token",children:"Refresh token (keeps you signed in)"}),i.jsx(Bt,{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(et,{variant:"error",size:"sm",children:p}),i.jsx(de,{type:"button",fullWidth:!0,loading:h,disabled:!l.trim(),onClick:()=>void y(),"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"})]})},OIe="/connections?platform=slack",BIe=({connected:t,cloudConnected:e,onGoToCloud:n,onConnected:s,navigateTo:r=a=>window.location.assign(a)})=>{const[a,o]=w.useState(!1),[l,c]=w.useState(null),d=w.useRef(!1);if(w.useEffect(()=>{t||!e||d.current||(d.current=!0,oc.refreshSlack().then(h=>{h.connected&&s()}).catch(()=>{}))},[t,e,s]),t)return i.jsx(et,{variant:"success",icon:ra,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(et,{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 oc.getSlackInstallUrl(`${window.location.origin}${tj("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(et,{variant:"error",size:"sm",children:l}),i.jsx(de,{type:"button",fullWidth:!0,icon:Xp,loading:a,onClick:()=>void u(),"data-testid":"slack-install",children:"Install Crewly in Slack"}),i.jsxs("a",{href:OIe,className:"inline-flex items-center gap-1 text-xs text-primary underline",children:["More Slack settings ",i.jsx(ws,{className:"h-3 w-3","aria-hidden":!0})]})]})},FIe=["harness","team","first_task","cloud","slack"];function UIe(t){return typeof t=="string"&&FIe.includes(t)}function u_(t,e){return t==null?void 0:t.steps.find(n=>n.id===e)}const Yn={HARNESS:0,ORC:1,LOGIN:2,TEAM:3,TASK:4,CLOUD:5,SLACK:6,DONE:7},zIe={harness:Yn.HARNESS,team:Yn.TEAM,first_task:Yn.TASK,cloud:Yn.CLOUD,slack:Yn.SLACK};function HIe(t){return UIe(t)?zIe[t]:Yn.HARNESS}function S5(t,e){var r;const n=((r=u_(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 Wc=({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})]}),Eb=({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:zr,onClick:t,children:"Back"}),i.jsx(de,{type:"button",variant:s?"primary":"secondary",icon:ip,iconPosition:"right",onClick:e,children:n})]}),GIe=()=>{const t=ps(),[e]=bh(),{overview:n,loading:s,error:r,refresh:a,setOrcHarness:o,savingOrc:l,replaceHarness:c}=m7(),{checklist:d,loading:u,refresh:h}=q8(),[f,p]=w.useState(()=>HIe(e.get($8))),[x,y]=w.useState(Y2),[m,g]=w.useState(null),[v,b]=w.useState(null),[_,k]=w.useState(!1),E=e.get("error"),M=N8((n==null?void 0:n.harnesses)??[],n==null?void 0:n.orcHarness),T=M.some(P=>P.installed),A=M.find(P=>P.id===(n==null?void 0:n.orcHarness))??null;w.useEffect(()=>{if(f!==Yn.TASK||v||u)return;let P=!1;return oc.getStarters().then(B=>{P||b(S5(d,B))}).catch(()=>{P||b(S5(d,[]))}),()=>{P=!0}},[f,v,d,u]);const N=()=>{yIe(!0),t(P3,{replace:!0})},D=()=>{g(Eve(M,(n==null?void 0:n.orcHarness)??null,x)),p(Yn.ORC)},I=async()=>{m&&(m!==(n==null?void 0:n.orcHarness)&&!await o(m)||p(Yn.LOGIN))},F=P=>{b({teamId:P.teamId,teamName:P.teamName,suggestions:P.suggestions,bundle:P.bundle}),h(),p(Yn.TASK)},z=w.useCallback(()=>{h()},[h]),W=()=>u?i.jsx(Ut,{centered:!0}):i.jsx(et,{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:sn,onClick:z,children:"Retry"})]})}),G=()=>s?i.jsx(Ut,{centered:!0,text:"Checking coding harnesses…"}):i.jsx(et,{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:sn,onClick:()=>void a(),children:"Retry"})]})}),K=()=>{var P;if(f<=Yn.LOGIN&&!n)return G();switch(f){case Yn.HARNESS:return i.jsxs(i.Fragment,{children:[i.jsx(Wc,{title:"Pick and install a coding harness",subtitle:"Crewly's AI teammates work through a coding harness. Claude Code is recommended."}),i.jsx(g7,{harnesses:M,systemTools:(n==null?void 0:n.systemTools)??[],selectedId:x,onSelect:y,onInstallFinished:()=>void a()}),i.jsx("div",{className:"mt-6 flex justify-end",children:i.jsx(de,{type:"button",icon:ip,iconPosition:"right",disabled:!T,onClick:D,children:"Next"})}),!T&&i.jsx("p",{className:"mt-2 text-right text-xs text-text-secondary-dark",children:"Install at least one to continue."})]});case Yn.ORC:return i.jsxs(i.Fragment,{children:[i.jsx(Wc,{title:"Which harness should the Orc use?",subtitle:"The orchestrator (Orc) coordinates your team. Choose its harness."}),i.jsx(x7,{harnesses:M,value:m,onChange:g,disabled:l}),r&&i.jsx(et,{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:zr,onClick:()=>p(Yn.HARNESS),children:"Back"}),i.jsx(de,{type:"button",icon:ip,iconPosition:"right",loading:l,disabled:!m,onClick:()=>void I(),children:"Next"})]})]});case Yn.LOGIN:{const B=(A==null?void 0:A.loginState)==="logged_in";return i.jsxs(i.Fragment,{children:[i.jsx(Wc,{title:"Sign in",subtitle:"Sign in so the orchestrator can work."}),A?i.jsx(v7,{harness:A,onLoggedIn:()=>void a(),onHarnessUpdated:c}):i.jsx(et,{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:zr,onClick:()=>p(Yn.ORC),children:"Back"}),i.jsx(de,{type:"button",variant:B?"primary":"secondary",icon:ip,iconPosition:"right",onClick:()=>p(Yn.TEAM),children:B?"Next":"Sign in later"})]})]})}case Yn.TEAM:{const B=((P=u_(d,"team"))==null?void 0:P.detail.teams)??[];return i.jsxs(i.Fragment,{children:[i.jsx(Wc,{title:"Create your first team",subtitle:"Pick a starter team. You can add more later."}),B.length>0&&i.jsxs(et,{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(jIe,{onDone:F}),i.jsx(Eb,{onBack:()=>p(Yn.LOGIN),onNext:()=>p(Yn.TASK),nextLabel:"Skip",primary:!1})]})}case Yn.TASK:return i.jsxs(i.Fragment,{children:[i.jsx(Wc,{title:"Give your team its first task",subtitle:"One sentence is enough."}),(v==null?void 0:v.bundle)&&i.jsx(et,{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."}),v?i.jsx(IIe,{suggestions:v.suggestions,teamId:v.teamId,teamName:v.teamName,onSent:()=>{k(!0),z()}}):i.jsx(Ut,{centered:!0}),i.jsx(Eb,{onBack:()=>p(Yn.TEAM),onNext:()=>p(Yn.CLOUD),nextLabel:_?"Next":"Skip",primary:_})]});case Yn.CLOUD:{const B=u_(d,"cloud");return i.jsxs(i.Fragment,{children:[i.jsx(Wc,{title:"Connect Crewly Cloud",subtitle:"Manage Crewly from your phone; needed for Slack."}),E&&!(B!=null&&B.done)&&i.jsxs(et,{variant:"warning",size:"sm",className:"mb-3",children:["Sign-in didn't finish (",E,"). Try again, or use copy and paste instead."]}),B?i.jsx(DIe,{connected:B.done,tier:B.detail.tier,tokenPageSignInUrl:B.detail.tokenPageSignInUrl,onConnected:z}):W(),i.jsx(Eb,{onBack:()=>p(Yn.TASK),onNext:()=>p(Yn.SLACK),nextLabel:B!=null&&B.done?"Next":"Skip",primary:!!(B!=null&&B.done)})]})}case Yn.SLACK:{const B=u_(d,"slack");return i.jsxs(i.Fragment,{children:[i.jsx(Wc,{title:"Connect Slack",subtitle:"Talk to your team from Slack."}),B?i.jsx(BIe,{connected:B.done,cloudConnected:B.detail.cloudConnected,onGoToCloud:()=>p(Yn.CLOUD),onConnected:z}):W(),i.jsx(Eb,{onBack:()=>p(Yn.CLOUD),onNext:()=>p(Yn.DONE),nextLabel:B!=null&&B.done?"Next":"Skip",primary:!!(B!=null&&B.done)})]})}default:{const B=A?W1[A.loginState]:null;return i.jsxs("div",{className:"space-y-4","data-testid":"setup-done",children:[i.jsxs("div",{className:"text-center",children:[i.jsx(ra,{className:"mx-auto h-12 w-12 text-emerald-400"}),i.jsx(Wc,{title:"Setup complete",subtitle:"You're ready to use Crewly."})]}),A&&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:G1(A)})," ",i.jsx(ct,{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(ra,{className:"h-4 w-4 text-emerald-400","aria-label":"Done"}):i.jsx(_2,{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:fM[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 → Harness.'}),i.jsx("div",{className:"text-center",children:i.jsx(de,{type:"button",size:"default",onClick:()=>t(P3,{replace:!0}),children:"Open Crewly"})})]})}}};return i.jsx(HY,{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!==Yn.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,"/",Ak.length," · ",Ak[f]]}),i.jsx("div",{className:"mb-6 hidden overflow-x-auto sm:block",children:i.jsx(bIe,{steps:[...Ak],currentStep:f})}),i.jsx(ot,{padding:"none",className:"p-4 sm:p-6",children:K()})]})})};function WIe(){const{id:t}=vh();return i.jsx(Fb,{to:`/tasks/${t??""}`,replace:!0})}function VIe(){return i.jsx(XQ,{children:i.jsx(nne,{children:i.jsx(oee,{children:i.jsxs(zY,{children:[i.jsx(gIe,{}),i.jsxs(JX,{children:[i.jsx(vIe,{}),i.jsxs(HX,{children:[i.jsx(An,{path:"/auth/callback",element:i.jsx(Eje,{})}),i.jsx(An,{path:"/auth",element:i.jsx(Tje,{})}),i.jsx(An,{path:"/setup",element:i.jsx(GIe,{})}),i.jsxs(An,{path:"/",element:i.jsx(rne,{}),children:[i.jsx(An,{index:!0,element:i.jsx(vne,{})}),i.jsx(An,{path:"projects",element:i.jsx(Sne,{})}),i.jsx(An,{path:"projects/:id",element:i.jsx(Ese,{})}),i.jsx(An,{path:"teams",element:i.jsx(Yse,{})}),i.jsx(An,{path:"teams/:id",element:i.jsx(Pre,{})}),i.jsx(An,{path:"assignments",element:i.jsx(zre,{})}),i.jsx(An,{path:"scheduled-checkins",element:i.jsx(qre,{})}),i.jsx(An,{path:"triggers",element:i.jsx(aie,{})}),i.jsx(An,{path:"factory",element:i.jsx(Bye,{})}),i.jsx(An,{path:"connections",element:i.jsx(hSe,{})}),i.jsx(An,{path:"browser",element:i.jsx(MSe,{})}),i.jsx(An,{path:"marketplace",element:i.jsx(HSe,{})}),i.jsx(An,{path:"marketplace/:id",element:i.jsx(VSe,{})}),i.jsx(An,{path:"wiki",element:i.jsx(j2e,{})}),i.jsx(An,{path:"security",element:i.jsx(TV,{})}),i.jsx(An,{path:"monitoring/costs",element:i.jsx(l5,{})}),i.jsx(An,{path:"usage",element:i.jsx(l5,{})}),i.jsx(An,{path:"settings",element:i.jsx(Bve,{})}),i.jsx(An,{path:"pricing",element:i.jsx(jje,{})}),i.jsx(An,{path:"cloud",element:i.jsx(Xje,{})}),i.jsx(An,{path:"tasks",element:i.jsx(uIe,{})}),i.jsx(An,{path:"tasks/:id",element:i.jsx(GV,{})}),i.jsx(An,{path:"requests",element:i.jsx(Fb,{to:"/tasks",replace:!0})}),i.jsx(An,{path:"requests/:id",element:i.jsx(WIe,{})}),i.jsx(An,{path:"missions",element:i.jsx(jV,{})}),i.jsx(An,{path:"missions/:id",element:i.jsx(IV,{})}),i.jsx(An,{path:"tickets",element:i.jsx(FRe,{})}),i.jsx(An,{path:"workitems",element:i.jsx(zV,{})}),i.jsx(An,{path:"workitems/:id",element:i.jsx(HV,{})}),i.jsx(An,{path:"team-chat",element:i.jsx(f_e,{})}),i.jsx(An,{path:"chat",element:i.jsx(Fb,{to:"/team-chat",replace:!0})}),i.jsx(An,{path:"agents",element:i.jsx(Fb,{to:"/team-chat",replace:!0})})]})]})]})]})})})})}fte();UA.createRoot(document.getElementById("root")).render(i.jsx(Mn.StrictMode,{children:i.jsx(VIe,{})}));
4951
- //# sourceMappingURL=index-8f30aa74.js.map
4950
+ `).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 IV=()=>{var K,P,B,R,L;const{id:t}=vh(),e=ps(),[n,s]=w.useState(null),[r,a]=w.useState(!0),[o,l]=w.useState(null),[c,d]=w.useState(!1),[u,h]=w.useState(!1),[f,p]=w.useState(null),[x,y]=w.useState(!1),[m,g]=w.useState(null),[v,b]=w.useState(new Map),[_,k]=w.useState(new Map),[E,M]=w.useState(0),T=w.useCallback(async($=!0)=>{if(t){$?a(!0):d(!0),l(null);try{const H=await xt.getMission(t);s(H)}catch(H){const se=H instanceof Error?H.message:"Failed to load mission";l(se)}finally{a(!1),d(!1)}}},[t]);w.useEffect(()=>{T()},[T]),w.useEffect(()=>{let $=!1;return(async()=>{try{const H=await xt.getMissions();if($)return;b(new Map(H.map(se=>[se.id,se.objective]))),k(new Map(H.map(se=>[se.id,{level:se.level,parentMissionId:se.parentMissionId}])))}catch{}})(),()=>{$=!0}},[t]);const A=w.useCallback(()=>{M($=>$+1),T(!1)},[T]),N=w.useCallback($=>{s(H=>H&&H.id===$.id?{...H,...$}:H),A()},[A]),D=w.useCallback(()=>{n&&(p(hRe(n)),g(null),h(!0))},[n]),I=w.useCallback(()=>{h(!1),p(null),g(null)},[]),F=w.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}y(!0),g(null);try{const $=await xt.updateMission(t,fRe(f));s($),h(!1),p(null)}catch($){const H=$ instanceof Error?$.message:"Failed to save mission";g(H)}finally{y(!1)}}},[t,f]),z=w.useMemo(()=>($,H)=>{p(se=>se&&{...se,[$]:H})},[]);if(r)return i.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:i.jsx(Ut,{size:"xl",text:"Loading mission..."})});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:zr,onClick:()=>e("/missions"),className:"mb-6",children:"Back to Missions"}),i.jsx(ot,{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:sn,onClick:()=>T(),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:zr,onClick:()=>e("/missions"),className:"mb-6",children:"Back to Missions"}),i.jsx(ot,{variant:"default",padding:"lg",children:i.jsx(Cs,{icon:ih,title:"Mission not found.",compact:!0})})]});const W=dj(n,_),G=(K=n.approval)==null?void 0:K.state;return i.jsxs("div",{className:"p-6 max-w-[1000px] mx-auto","data-testid":"mission-detail-page",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:zr,onClick:()=>e("/missions"),className:"mb-6","data-testid":"mission-detail-back",children:"Back to Missions"}),i.jsxs("div",{className:"flex items-start justify-between gap-4 mb-6",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[u&&f?i.jsx(xs,{"aria-label":"Objective",value:f.objective,onChange:$=>z("objective",$.target.value),fullWidth:!0,"data-testid":"edit-objective"}):i.jsx("h1",{className:"text-2xl font-bold text-text-primary-dark mb-2",children:n.objective}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap mt-2",children:[i.jsx(_0,{level:W}),i.jsx(Po,{status:lj(n.status),children:Y_(n.status)}),G&&(G!=="approved"||((P=n.approval)==null?void 0:P.decidedAt))&&i.jsx(hj,{state:G}),n.priority&&i.jsx(ct,{variant:xH[n.priority],size:"sm",children:yM[n.priority]}),((B=n.period)==null?void 0:B.label)&&i.jsx(ct,{variant:"info",size:"sm",children:n.period.label}),i.jsx(ct,{variant:"default",size:"sm",children:n.id.slice(0,12)})]}),G==="pending_approval"&&!u&&i.jsxs("div",{className:"mt-3 flex items-center gap-3 flex-wrap","data-testid":"mission-pending-banner",children:[i.jsxs("span",{className:"text-xs text-yellow-400",children:["Proposed",(R=n.approval)!=null&&R.proposedBy?` by ${n.approval.proposedBy}`:""," — awaiting your decision."]}),i.jsx(tI,{missionId:n.id,onDecided:N})]}),G==="rejected"&&((L=n.approval)==null?void 0:L.rejectionReason)&&i.jsxs("p",{className:"mt-2 text-xs text-red-400","data-testid":"mission-rejection-reason",children:["Rejected: ",n.approval.rejectionReason]})]}),i.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:u?i.jsxs(i.Fragment,{children:[i.jsx(de,{variant:"primary",size:"sm",icon:Sd,onClick:F,disabled:x,"data-testid":"mission-save",children:x?"Saving…":"Save"}),i.jsx(de,{variant:"ghost",size:"sm",icon:ls,onClick:I,disabled:x,"data-testid":"mission-cancel",children:"Cancel"})]}):i.jsxs(i.Fragment,{children:[i.jsx(de,{variant:"primary",size:"sm",icon:k1,onClick:D,"data-testid":"mission-edit",children:"Edit"}),i.jsx(de,{variant:"ghost",size:"sm",icon:sn,onClick:()=>T(!1),loading:c,"aria-label":"Refresh mission",children:"Refresh"})]})})]}),m&&i.jsx("div",{"data-testid":"mission-save-error",className:"mb-4",children:i.jsx(et,{variant:"error",onClose:()=>g(null),children:m})}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[i.jsxs("div",{className:"lg:col-span-2 flex flex-col gap-4",children:[i.jsxs(ot,{variant:"default",padding:"md",className:"border border-border-dark",children:[i.jsxs("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wide mb-2 flex items-center gap-1.5",children:[i.jsx(ih,{className:"h-4 w-4"}),"Current Strategy"]}),u&&f?i.jsx(qs,{"aria-label":"Current Strategy",rows:4,value:f.currentStrategy,onChange:$=>z("currentStrategy",$.target.value),"data-testid":"edit-strategy"}):i.jsx("p",{className:"text-sm text-text-primary-dark leading-relaxed whitespace-pre-wrap",children:n.currentStrategy||"No strategy defined."})]}),i.jsxs(ot,{variant:"default",padding:"md",className:"border border-border-dark",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(ra,{className:"h-4 w-4"}),"Success Criteria (",n.successCriteria.length,")"]}),u&&f?i.jsx(qs,{"aria-label":"Success Criteria (one per line)",rows:5,placeholder:"One criterion per line",value:f.successCriteriaText,onChange:$=>z("successCriteriaText",$.target.value),"data-testid":"edit-success-criteria"}):n.successCriteria.length===0?i.jsx("p",{className:"text-sm text-text-secondary-dark",children:"No success criteria defined."}):i.jsx("ul",{className:"space-y-2",children:n.successCriteria.map(($,H)=>i.jsxs("li",{className:"flex items-start gap-2 text-sm text-text-primary-dark",children:[i.jsx("span",{className:"text-primary mt-0.5 flex-shrink-0",children:i.jsx(w2,{className:"h-4 w-4"})}),$]},H))})]}),!u&&i.jsx(aRe,{missionId:n.id,onChanged:A}),!u&&i.jsx(cRe,{parentMissionId:n.id,onDecided:N}),!u&&i.jsx(lRe,{missionId:n.id,level:W,parentMissionId:n.parentMissionId,missionNames:v,refreshKey:E}),!u&&n.learnings&&n.learnings.length>0&&i.jsxs(ot,{variant:"default",padding:"md",className:"border border-border-dark",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(d0,{className:"h-4 w-4"}),"Learnings (",n.learnings.length,")"]}),i.jsx("ul",{className:"space-y-2",children:n.learnings.map(($,H)=>i.jsx("li",{className:"text-sm text-text-primary-dark pl-4 border-l-2 border-border-dark",children:$},H))})]})]}),i.jsxs("div",{className:"flex flex-col gap-4",children:[!u&&i.jsx(uRe,{missionId:n.id,refreshKey:E}),i.jsxs(ot,{variant:"default",padding:"md",className:"border border-border-dark",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(is,{className:"h-4 w-4"}),"Team & Settings"]}),i.jsxs("div",{className:"space-y-3 text-sm",children:[i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("span",{className:"text-text-secondary-dark text-xs uppercase tracking-wide",children:"Owner Team"}),u&&f?i.jsx(xs,{"aria-label":"Owner Team",value:f.ownerTeamId,onChange:$=>z("ownerTeamId",$.target.value),fullWidth:!0,"data-testid":"edit-owner-team"}):i.jsx("span",{className:"text-text-primary-dark font-mono text-xs",children:n.ownerTeamId})]}),i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("span",{className:"text-text-secondary-dark text-xs uppercase tracking-wide",children:"Status"}),u&&f?i.jsxs(pn,{value:f.status,onChange:$=>z("status",$.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.jsx("span",{className:"text-text-primary-dark",children:Y_(n.status)})]}),i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("span",{className:"text-text-secondary-dark text-xs uppercase tracking-wide",children:"Priority"}),u&&f?i.jsxs(pn,{value:f.priority,onChange:$=>z("priority",$.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.jsx("span",{className:"text-text-primary-dark",children:yM[n.priority??"medium"]})]}),i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("span",{className:"text-text-secondary-dark text-xs uppercase tracking-wide",children:"Parent Mission"}),u&&f?i.jsx(xs,{"aria-label":"Parent Mission ID",placeholder:"(none)",value:f.parentMissionId,onChange:$=>z("parentMissionId",$.target.value),fullWidth:!0,"data-testid":"edit-parent"}):n.parentMissionId?i.jsx(de,{type:"button",variant:"link",size:"xs",onClick:()=>e(`/missions/${n.parentMissionId}`),className:"truncate max-w-full","data-testid":"mission-parent-link",children:v.get(n.parentMissionId)??n.parentMissionId}):i.jsx("span",{className:"text-text-primary-dark font-mono text-xs",children:"—"})]}),!u&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Level"}),i.jsx("span",{className:"text-text-primary-dark","data-testid":"mission-level",children:W})]}),!u&&n.projectId&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Project"}),i.jsx(de,{type:"button",variant:"link",size:"xs",onClick:()=>e(`/projects/${n.projectId}`),className:"font-mono","data-testid":"mission-project-link",children:n.projectId.slice(0,12)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Active Tasks"}),i.jsx("span",{className:"text-text-primary-dark",children:n.activeProjectTaskIds.length})]}),i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("span",{className:"text-text-secondary-dark text-xs uppercase tracking-wide",children:"Cadence (cron)"}),u&&f?i.jsx(xs,{"aria-label":"Cadence",value:f.cadence,onChange:$=>z("cadence",$.target.value),fullWidth:!0,"data-testid":"edit-cadence"}):i.jsx("span",{className:"text-text-primary-dark font-mono text-xs",children:n.cadence||"N/A"})]})]})]}),i.jsxs(ot,{variant:"default",padding:"md",className:"border border-border-dark",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(OT,{className:"h-4 w-4"}),"OKR Period"]}),u&&f?i.jsxs("div",{className:"space-y-2",children:[i.jsxs(pn,{value:f.periodType,onChange:$=>z("periodType",$.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(xs,{type:"date","aria-label":"Period start",value:f.periodStart,onChange:$=>z("periodStart",$.target.value),fullWidth:!0,"data-testid":"edit-period-start"}),i.jsx(xs,{type:"date","aria-label":"Period end",value:f.periodEnd,onChange:$=>z("periodEnd",$.target.value),fullWidth:!0,"data-testid":"edit-period-end"}),i.jsx(xs,{"aria-label":"Period label",placeholder:"Label (optional)",value:f.periodLabel,onChange:$=>z("periodLabel",$.target.value),fullWidth:!0,"data-testid":"edit-period-label"})]}):n.period?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:"Type"}),i.jsx("span",{className:"text-text-primary-dark",children:n.period.type})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Start"}),i.jsx("span",{className:"text-text-primary-dark text-xs",children:Ef(n.period.startDate)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"End"}),i.jsx("span",{className:"text-text-primary-dark text-xs",children:Ef(n.period.endDate)})]}),n.period.label&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Label"}),i.jsx("span",{className:"text-text-primary-dark text-xs",children:n.period.label})]})]}):i.jsx("p",{className:"text-sm text-text-secondary-dark",children:"No period defined."})]}),i.jsxs(ot,{variant:"default",padding:"md",className:"border border-border-dark",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(OT,{className:"h-4 w-4"}),"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 text-xs",children:Ef(n.createdAt)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Updated"}),i.jsx("span",{className:"text-text-primary-dark text-xs",children:Ef(n.updatedAt)})]}),n.lastReviewAt&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Last Review"}),i.jsx("span",{className:"text-text-primary-dark text-xs",children:Ef(n.lastReviewAt)})]}),n.nextReviewAt&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Next Review"}),i.jsx("span",{className:"text-text-primary-dark text-xs",children:Ef(n.nextReviewAt)})]})]})]}),!u&&n.activeProjectTaskIds.length>0&&i.jsxs(ot,{variant:"default",padding:"md",className:"border border-border-dark",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"}),"Active Task IDs"]}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.activeProjectTaskIds.map($=>i.jsx(ct,{variant:"default",size:"sm",children:$.slice(0,12)},$))})]})]})]})]})};IV.displayName="MissionDetail";const PV="/api/tickets",pRe=15e3,mRe=300,gRe=24*60*60*1e3,LV=["idea","todo","in_progress","blocked","to_review","done"],vN={idea:"Ideas",todo:"To do",in_progress:"In progress",blocked:"Blocked",to_review:"To review",done:"Done",cancelled:"Cancelled"},nI={issue:"Issue",feature:"Feature",idea:"Idea",question:"Question"},DV=["issue","feature","idea","question"],c_="all",xRe="All",yRe=[{value:"urgent",label:"P0"},{value:"high",label:"P1"},{value:"normal",label:"P2"},{value:"low",label:"P3"}],vRe={P0:"error",P1:"warning",P2:"primary",P3:"default"},bRe={owner:"Me",decompose:"Breakdown",reject:"Sent back",agent:"Agent"},PA={auto:"Auto",judgment:"Manual"},_Re={"slack-channel":"Slack channel","slack-dm":"Slack DM",chat:"Chat",portal:"Portal",mobile:"Mobile","bug-button":"Bug button",agent:"Agent",cron:"Scheduled task",mission:"Mission",legacy:"Legacy record"},f5={not_in_review:"This ticket is not in review, so it cannot be sent back",already_done:"This ticket is already done",open_work:"Some work items are still open, so it cannot be accepted yet",cancelled:"This ticket was cancelled",invalid:"Invalid input"},Qt={PAGE_TITLE:"Tickets",PAGE_SUBTITLE:"Everything you have asked for, in one place",SEARCH_PLACEHOLDER:"Search tickets…",KIND_FILTER_ARIA:"Filter by type",REFRESH:"Refresh",EMPTY_COLUMN:"Nothing here",EMPTY_BOARD_TITLE:"No tickets yet",EMPTY_BOARD_DESC:'Ask for something in Slack or chat ("please help me…") and a ticket is created automatically.',LOAD_FAILED:"Failed to load tickets",UNASSIGNED:"Unassigned",REJECT_BADGE:"Sent back",AUTO_ACCEPT_IN_DAYS:"Auto-accepts in",AUTO_ACCEPT_SOON:"Auto-accepts soon",ACCEPTED_BY_OWNER:"Accepted",ACCEPTED_BY_SILENCE:"Auto-accepted · not reviewed",ACCEPTED_BY_SILENCE_HINT:"Nobody objected before the deadline, so it closed as accepted; nobody checked the result",DETAIL_LOADING:"Loading…",TITLE_LABEL:"Title",SAVE:"Save",PRIORITY_LABEL:"Priority",KIND_LABEL:"Type",ORIGIN_LABEL:"Source",ASSIGNEE_LABEL:"Assignee",DESCRIPTION_LABEL:"Description",REPLY_LABEL:"Agent's answer",NO_REPLY:"No answer yet",DISCUSSION_LABEL:"Discussion",NO_DISCUSSION:"No discussion yet",ACCEPTANCE_LABEL:"Acceptance criteria",NO_ACCEPTANCE:"No acceptance criteria yet",ACCEPTANCE_ADD_PLACEHOLDER:"Add an acceptance criterion…",ACCEPTANCE_CHECK_ARIA:"How it is checked",ACCEPTANCE_ADD:"Add",ACCEPTANCE_REMOVE:"Remove",SELF_CHECK_PASS:"Self-check passed",SELF_CHECK_FAIL:"Self-check failed",VERIFY:"Verified",REJECT:"Send back",DISMISS:"Dismiss",REJECT_REASON_LABEL:"Reason for sending back",REJECT_REASON_PLACEHOLDER:"What is wrong? This becomes a new acceptance criterion",REJECT_REASON_REQUIRED:"Please give a reason for sending it back",REJECT_CONFIRM:"Confirm send back",CANCEL:"Cancel",REJECTED_TIMES:"Sent back",SUBMITTED_TIMES:"Submitted"};class sI extends Error{constructor(n,s,r){super(n);Ln(this,"status");Ln(this,"code");this.name="TicketApiError",this.status=s,this.code=r}}function SRe(t){return t instanceof sI}function wRe(t){const e={};for(const n of LV)e[n]=[];e.cancelled=[];for(const n of t)(e[n.column]??(e[n.column]=[])).push(n);return e}function CRe(t,e=Date.now()){if(!t)return null;const n=Date.parse(t);return Number.isNaN(n)?null:Math.max(0,Math.ceil((n-e)/gRe))}function OV(t,e=Date.now()){const n=CRe(t,e);return n===null?null:n<=0?Qt.AUTO_ACCEPT_SOON:`${Qt.AUTO_ACCEPT_IN_DAYS} ${n} ${n===1?"day":"days"}`}function kRe(t){if(!t)return null;const e=_Re[t.channel]??t.channel,n=t.authorName||t.author;return n?`${e} · ${n}`:e}function p5(t){if(!t)return"";const e=Date.parse(t);return Number.isNaN(e)?t:new Date(e).toLocaleString()}function m5(t){return(t??[]).map(e=>({text:e.text,...e.check?{check:e.check}:{}}))}function bN(t){return SRe(t)&&t.code&&f5[t.code]?f5[t.code]:t instanceof Error&&t.message?t.message:String(t)}const ERe=({ticket:t,onOpen:e,now:n})=>{var c;const s=t.column==="to_review",r=s?OV(t.autoAcceptAt,n):null,a=t.column==="done"?t.acceptedBy??null:null,o=t.rejectCount??0,l=d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),e(t))};return i.jsxs(ot,{padding:"sm",interactive:!0,role:"button",tabIndex:0,"aria-label":`${t.tkt??""} ${t.title}`.trim(),"data-testid":`ticket-card-${t.id}`,onClick:()=>e(t),onKeyDown:l,className:"rounded-2xl focus:outline-none focus:ring-1 focus:ring-primary",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsx("span",{className:"text-xs font-semibold text-text-secondary-dark",children:t.tkt??""}),i.jsxs("div",{className:"flex items-center gap-1",children:[o>0&&i.jsxs(ct,{variant:"error",size:"sm","data-testid":"ticket-reject-badge",children:[Qt.REJECT_BADGE," ×",o]}),i.jsx(ct,{variant:vRe[t.priorityLabel]??"default",size:"sm",children:t.priorityLabel})]})]}),i.jsx("p",{className:"mt-1 text-sm font-medium text-text-primary-dark break-words",children:t.title}),s&&((c=t.reply)==null?void 0:c.excerpt)&&i.jsx("p",{className:"mt-2 text-xs text-text-secondary-dark line-clamp-3 break-words","data-testid":"ticket-reply-excerpt",children:t.reply.excerpt}),i.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[i.jsx(ct,{size:"sm",children:nI[t.kind]??t.kind}),i.jsx("span",{className:"text-xs text-text-secondary-dark truncate",children:t.assignee||Qt.UNASSIGNED})]}),r&&i.jsx("p",{className:"mt-2 text-xs text-primary","data-testid":"ticket-auto-accept",children:r}),a&&i.jsx("div",{className:"mt-2","data-testid":"ticket-accepted-by","data-accepted-by":a,children:i.jsx(ct,{size:"sm",variant:a==="owner"?"success":"warning",title:a==="silence"?Qt.ACCEPTED_BY_SILENCE_HINT:void 0,children:a==="owner"?Qt.ACCEPTED_BY_OWNER:Qt.ACCEPTED_BY_SILENCE})})]})};async function Rh(t,e){const n=await fetch(t,e);let s={};try{s=await n.json()}catch{s={}}if(!n.ok||s.success===!1)throw new sI(s.error||s.message||`HTTP ${n.status}`,n.status,s.code);return s.data}function U0(t,e){return{method:t,headers:{"Content-Type":"application/json"},...e!==void 0?{body:JSON.stringify(e)}:{}}}function mm(t,e=""){return`${PV}/${encodeURIComponent(t)}${e}`}function ARe(t={}){var r;const e=new URLSearchParams;t.column&&e.set("column",t.column),t.kind&&e.set("kind",t.kind);const n=(r=t.q)==null?void 0:r.trim();n&&e.set("q",n),t.includeLegacy&&e.set("includeLegacy","true");const s=e.toString();return s?`?${s}`:""}async function TRe(t={}){const e=await Rh(`${PV}${ARe(t)}`);return{tickets:(e==null?void 0:e.tickets)??[],columns:(e==null?void 0:e.columns)??{}}}function MRe(t){return Rh(mm(t))}function NRe(t){return Rh(mm(t,"/verify"),U0("POST"))}function jRe(t,e){const n=e.trim();return n?Rh(mm(t,"/reject"),U0("POST",{reason:n})):Promise.reject(new sI("A reason is required",400,"invalid"))}function RRe(t){return Rh(mm(t,"/dismiss"),U0("POST"))}function IRe(t,e){return Rh(mm(t,"/acceptance"),U0("PUT",{items:e}))}function PRe(t,e){return Rh(mm(t),U0("PATCH",e))}const g5="judgment",LRe=({acceptance:t,onSave:e,disabled:n=!1})=>{const[s,r]=w.useState(""),[a,o]=w.useState(g5),[l,c]=w.useState(!1),d=n||l,u=async p=>{c(!0);try{return await e(p),!0}catch{return!1}finally{c(!1)}},h=async p=>{const x=m5(t).filter((y,m)=>m!==p);await u(x)},f=async p=>{p.preventDefault();const x=s.trim();if(!x)return;await u([...m5(t),{text:x,check:a}])&&(r(""),o(g5))};return i.jsxs("div",{"data-testid":"ticket-acceptance",children:[t.length===0?i.jsx("p",{className:"text-sm text-text-secondary-dark",children:Qt.NO_ACCEPTANCE}):i.jsx("ul",{className:"space-y-2",children:t.map((p,x)=>i.jsxs("li",{className:"flex items-start gap-2 rounded-2xl border border-border-dark bg-background-dark p-3","data-testid":"ticket-acceptance-item",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-text-primary-dark break-words",children:p.text}),i.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1",children:[i.jsx(ct,{size:"sm",variant:p.source==="reject"?"error":"default",children:bRe[p.source??"owner"]}),i.jsx(ct,{size:"sm",variant:p.check==="auto"?"info":"default",children:PA[p.check??"judgment"]}),p.selfCheck&&i.jsx(ct,{size:"sm",variant:p.selfCheck==="pass"?"success":"error",children:p.selfCheck==="pass"?Qt.SELF_CHECK_PASS:Qt.SELF_CHECK_FAIL})]}),p.evidence&&i.jsx("p",{className:"mt-1 text-xs text-text-secondary-dark break-words",children:p.evidence})]}),i.jsx(Ft,{icon:Vr,variant:"ghost","aria-label":`${Qt.ACCEPTANCE_REMOVE} ${p.text}`,disabled:d,onClick:()=>void h(x)})]},`${x}-${p.text}`))}),i.jsxs("form",{className:"mt-3 flex flex-col gap-2 sm:flex-row",onSubmit:p=>void f(p),children:[i.jsx("div",{className:"flex-1",children:i.jsx(Bt,{value:s,onChange:p=>r(p.target.value),placeholder:Qt.ACCEPTANCE_ADD_PLACEHOLDER,"aria-label":Qt.ACCEPTANCE_ADD_PLACEHOLDER,disabled:d})}),i.jsx("div",{className:"sm:w-28",children:i.jsxs(pn,{value:a,onChange:p=>o(p.target.value),"aria-label":Qt.ACCEPTANCE_CHECK_ARIA,disabled:d,children:[i.jsx("option",{value:"judgment",children:PA.judgment}),i.jsx("option",{value:"auto",children:PA.auto})]})}),i.jsx(de,{type:"submit",variant:"secondary",icon:Jn,disabled:d||!s.trim(),children:Qt.ACCEPTANCE_ADD})]})]})},DRe=new Set(["done","cancelled"]),Cb=({title:t,children:e})=>i.jsxs("section",{className:"space-y-2",children:[i.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-text-secondary-dark",children:t}),e]}),ORe=({ticketId:t,onClose:e,onChanged:n,now:s})=>{const[r,a]=w.useState(null),[o,l]=w.useState(null),[c,d]=w.useState(null),[u,h]=w.useState(null),[f,p]=w.useState(""),[x,y]=w.useState(!1),[m,g]=w.useState(""),[v,b]=w.useState(null),_=w.useCallback(async P=>{try{const B=await MRe(P);a(B),p(B.board.title),l(null)}catch(B){l(bN(B))}},[]);w.useEffect(()=>{a(null),l(null),d(null),y(!1),g(""),b(null),t&&_(t)},[t,_]);const k=async(P,B,R=!1)=>{if(!t)return!1;h(P),d(null);try{return await B(),n(),R?e():await _(t),!0}catch(L){return d(bN(L)),!1}finally{h(null)}},E=P=>{t&&k("patch",()=>PRe(t,P))},M=async P=>{if(!t)return;if(!await k("acceptance",()=>IRe(t,P)))throw new Error("acceptance save failed")},T=()=>{if(!t)return;const P=m.trim();if(!P){b(Qt.REJECT_REASON_REQUIRED);return}b(null),k("reject",()=>jRe(t,P)).then(B=>{B&&(y(!1),g(""))})},A=(r==null?void 0:r.board)??null,N=t!==null,D=A!==null&&!DRe.has(A.column),I=(A==null?void 0:A.column)==="to_review",F=A!==null&&f.trim()!==""&&f.trim()!==A.title,z=(r==null?void 0:r.ticket.discussion)??[],W=(A==null?void 0:A.description)||(r==null?void 0:r.ticket.description)||"",G=I?OV(A==null?void 0:A.autoAcceptAt,s):null,K=A&&D?x?i.jsxs("div",{className:"flex w-full flex-col gap-2","data-testid":"ticket-reject-form",children:[i.jsx("label",{htmlFor:"ticket-reject-reason",className:"text-sm text-text-secondary-dark",children:Qt.REJECT_REASON_LABEL}),i.jsx(qs,{id:"ticket-reject-reason",rows:3,value:m,error:v!==null,placeholder:Qt.REJECT_REASON_PLACEHOLDER,onChange:P=>{g(P.target.value),v&&b(null)}}),v&&i.jsx("p",{className:"text-xs text-red-400",role:"alert",children:v}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(de,{variant:"ghost",onClick:()=>y(!1),disabled:u!==null,children:Qt.CANCEL}),i.jsx(de,{variant:"warning",icon:r3,onClick:T,loading:u==="reject",children:Qt.REJECT_CONFIRM})]})]}):i.jsxs("div",{className:"flex w-full flex-wrap items-center justify-end gap-2",children:[i.jsx(de,{variant:"danger-ghost",icon:ls,onClick:()=>void k("dismiss",()=>RRe(t),!0),loading:u==="dismiss",disabled:u!==null&&u!=="dismiss",children:Qt.DISMISS}),I&&i.jsx(de,{variant:"warning",icon:r3,onClick:()=>y(!0),disabled:u!==null,children:Qt.REJECT}),i.jsx(de,{variant:"success",icon:$n,onClick:()=>void k("verify",()=>NRe(t),!0),loading:u==="verify",disabled:u!==null&&u!=="verify",children:Qt.VERIFY})]}):void 0;return i.jsxs(XJ,{isOpen:N,onClose:e,size:"lg",title:(A==null?void 0:A.tkt)??(A==null?void 0:A.title)??Qt.DETAIL_LOADING,subtitle:A?vN[A.column]??A.column:void 0,footer:K,"data-testid":"ticket-detail-drawer",children:[!A&&!o&&i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(Ut,{})}),o&&i.jsx(et,{variant:"error",size:"sm",children:o}),A&&i.jsxs("div",{className:"space-y-6",children:[c&&i.jsx(et,{variant:"error",size:"sm",onClose:()=>d(null),"data-testid":"ticket-action-error",children:c}),i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{children:[i.jsx("label",{htmlFor:"ticket-title",className:"mb-1 block text-sm text-text-secondary-dark",children:Qt.TITLE_LABEL}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Bt,{id:"ticket-title",value:f,onChange:P=>p(P.target.value)}),F&&i.jsx(de,{variant:"secondary",onClick:()=>E({title:f.trim()}),loading:u==="patch",children:Qt.SAVE})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{htmlFor:"ticket-priority",className:"mb-1 block text-sm text-text-secondary-dark",children:Qt.PRIORITY_LABEL}),i.jsx(pn,{id:"ticket-priority",value:A.priority,disabled:u!==null,onChange:P=>E({priority:P.target.value}),children:yRe.map(P=>i.jsx("option",{value:P.value,children:P.label},P.value))})]}),i.jsxs("div",{children:[i.jsx("label",{htmlFor:"ticket-kind",className:"mb-1 block text-sm text-text-secondary-dark",children:Qt.KIND_LABEL}),i.jsx(pn,{id:"ticket-kind",value:A.kind,disabled:u!==null,onChange:P=>E({kind:P.target.value}),children:DV.map(P=>i.jsx("option",{value:P,children:nI[P]},P))})]})]}),i.jsxs("dl",{className:"grid grid-cols-1 gap-2 text-sm sm:grid-cols-2",children:[i.jsxs("div",{children:[i.jsx("dt",{className:"text-text-secondary-dark",children:Qt.ORIGIN_LABEL}),i.jsx("dd",{className:"text-text-primary-dark","data-testid":"ticket-origin",children:kRe(A.origin)??"—"})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-text-secondary-dark",children:Qt.ASSIGNEE_LABEL}),i.jsx("dd",{className:"text-text-primary-dark",children:A.assignee||Qt.UNASSIGNED})]})]}),i.jsxs("div",{className:"flex flex-wrap gap-1",children:[(A.rejectCount??0)>0&&i.jsxs(ct,{variant:"error",size:"sm",children:[Qt.REJECTED_TIMES," ×",A.rejectCount]}),(A.submitCount??0)>0&&i.jsxs(ct,{size:"sm",children:[Qt.SUBMITTED_TIMES," ×",A.submitCount]}),G&&i.jsx(ct,{variant:"primary",size:"sm",children:G})]})]}),W&&i.jsx(Cb,{title:Qt.DESCRIPTION_LABEL,children:i.jsx("p",{className:"whitespace-pre-wrap break-words text-sm text-text-primary-dark",children:W})}),i.jsx(Cb,{title:Qt.REPLY_LABEL,children:A.reply?i.jsxs("div",{className:"rounded-2xl border border-border-dark bg-background-dark p-3","data-testid":"ticket-reply",children:[i.jsx("p",{className:"whitespace-pre-wrap break-words text-sm text-text-primary-dark",children:A.reply.excerpt}),i.jsxs("p",{className:"mt-1 text-xs text-text-secondary-dark",children:[A.reply.by," · ",p5(A.reply.at)]})]}):i.jsx("p",{className:"text-sm text-text-secondary-dark",children:Qt.NO_REPLY})}),i.jsx(Cb,{title:Qt.ACCEPTANCE_LABEL,children:i.jsx(LRe,{acceptance:A.acceptance??[],onSave:M,disabled:u!==null&&u!=="acceptance"})}),i.jsx(Cb,{title:Qt.DISCUSSION_LABEL,children:z.length===0?i.jsx("p",{className:"text-sm text-text-secondary-dark",children:Qt.NO_DISCUSSION}):i.jsx("ul",{className:"space-y-2","data-testid":"ticket-discussion",children:z.map((P,B)=>i.jsxs("li",{className:"rounded-2xl border border-border-dark p-3",children:[i.jsxs("p",{className:"text-xs text-text-secondary-dark",children:[P.author," · ",p5(P.at)]}),i.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words text-sm text-text-primary-dark",children:P.text})]},`${P.ref}-${B}`))})})]})]})},BRe=[{value:c_,label:xRe},...DV.map(t=>({value:t,label:nI[t]}))],FRe=({now:t})=>{const[e,n]=w.useState(""),[s,r]=w.useState(""),[a,o]=w.useState(c_),[l,c]=w.useState(null),[d,u]=w.useState(!0),[h,f]=w.useState(null),[p,x]=w.useState(null),y=w.useRef(0);w.useEffect(()=>{const k=setTimeout(()=>r(e),mRe);return()=>clearTimeout(k)},[e]);const m=w.useCallback(async()=>{const k=++y.current;try{const E=await TRe({...a!==c_?{kind:a}:{},...s.trim()?{q:s}:{}});if(k!==y.current)return;c(E),f(null)}catch(E){if(k!==y.current)return;f(bN(E))}finally{k===y.current&&u(!1)}},[a,s]);w.useEffect(()=>{m();const k=setInterval(()=>void m(),pRe);return()=>clearInterval(k)},[m]);const g=w.useMemo(()=>wRe((l==null?void 0:l.tickets)??[]),[l]),v=a!==c_||s.trim()!=="",b=l!==null&&l.tickets.length===0&&!v,_=w.useCallback(k=>x(k.id),[]);return i.jsxs("div",{className:"flex min-w-0 max-w-full flex-col gap-4","data-testid":"tickets-page",children:[i.jsxs("div",{className:"flex items-start justify-between gap-4",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("h1",{className:"text-2xl font-bold text-text-primary-dark",children:Qt.PAGE_TITLE}),i.jsx("p",{className:"mt-1 text-sm text-text-secondary-dark",children:Qt.PAGE_SUBTITLE})]}),i.jsx(Ft,{icon:sn,variant:"ghost","aria-label":Qt.REFRESH,onClick:()=>void m()})]}),i.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[i.jsx("div",{className:"w-full sm:max-w-xs",children:i.jsx(xs,{type:"search",value:e,onChange:k=>n(k.target.value),placeholder:Qt.SEARCH_PLACEHOLDER,"aria-label":Qt.SEARCH_PLACEHOLDER,fullWidth:!0})}),i.jsx("div",{className:"max-w-full overflow-x-auto",children:i.jsx(oo,{options:BRe,value:a,onChange:o,size:"sm","aria-label":Qt.KIND_FILTER_ARIA})})]}),h&&i.jsx(et,{variant:"error",size:"sm",title:Qt.LOAD_FAILED,children:h}),d&&!l?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(Ut,{})}):b?i.jsx(Cs,{icon:r6,title:Qt.EMPTY_BOARD_TITLE,description:Qt.EMPTY_BOARD_DESC}):i.jsx("div",{className:"w-full min-w-0 overflow-x-auto pb-2","data-testid":"tickets-board",children:i.jsx("div",{className:"flex gap-3 snap-x",children:LV.map(k=>{var T;const E=g[k]??[],M=((T=l==null?void 0:l.columns)==null?void 0:T[k])??E.length;return i.jsxs("section",{"aria-label":vN[k],"data-testid":`tickets-column-${k}`,className:"flex w-64 shrink-0 snap-start flex-col rounded-2xl border border-border-dark bg-surface-dark/50 p-2 sm:w-72",children:[i.jsxs("header",{className:"flex items-center justify-between px-1 pb-2",children:[i.jsx("h2",{className:"text-sm font-semibold text-text-primary-dark",children:vN[k]}),i.jsx(ct,{size:"sm",variant:k==="to_review"&&M>0?"primary":"default",children:M})]}),i.jsx("div",{className:"flex flex-col gap-2",children:E.length===0?i.jsx("p",{className:"px-1 py-4 text-center text-xs text-text-secondary-dark",children:Qt.EMPTY_COLUMN}):E.map(A=>i.jsx(ERe,{ticket:A,onOpen:_,now:t},A.id))})]},k)})})}),i.jsx(ORe,{ticketId:p,onClose:()=>x(null),onChanged:()=>void m(),now:t})]})};function rI(t){return{queued:"pending",scheduled:"paused",running:"running",blocked:"blocked",done:"completed",failed:"error",cancelled:"inactive"}[t]??"pending"}function iI(t){return{queued:"Queued",scheduled:"Scheduled",running:"Running",blocked:"Blocked",done:"Completed",failed:"Failed",cancelled:"Cancelled"}[t]??t}function aI(t){return{delegate:"primary",project_task:"info",check:"default",notify:"success",cron_run:"warning",review:"info",confirm:"warning",reconcile:"default",ticket_triage:"info"}[t]??"default"}function oI(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"}[t]??t}function URe(t){return{orchestrator:"Orchestrator",team_lead:"Team Lead",agent:"Agent",system:"System"}[t]??t}function Ww(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 Hg(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 BV(t){return t===0?"—":t<.01?`$${t.toFixed(4)}`:`$${t.toFixed(2)}`}function fx(t){return t===0?"—":t<1e3?t.toString():t<1e6?`${(t/1e3).toFixed(1)}K`:`${(t/1e6).toFixed(1)}M`}function FV(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 zRe(t,e){if(t==="error")return ul;if(t==="progress_update")return b2;if(t==="agent_reasoning"||t==="tool_action")return Pi;switch(e){case"queued":return vs;case"running":return Pi;case"done":return ra;case"failed":return ul;case"cancelled":return lY;case"blocked":return _d;default:return vs}}function HRe(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 GRe(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 lI=({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=zRe(e.kind,e.status),r=HRe(e.kind,e.status),a=GRe(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:Hg(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)})});lI.displayName="WorkItemTimeline";const Ga=({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})]}),UV=({item:t})=>{const e=WRe(t);return i.jsxs("div",{className:"space-y-4","data-testid":"workitem-metrics",children:[i.jsxs(ot,{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(Ga,{icon:Lx,label:"Input Tokens",value:fx(t.inputTokens)}),i.jsx(Ga,{icon:Lx,label:"Output Tokens",value:fx(t.outputTokens)}),i.jsx(Ga,{icon:S2,label:"Cost",value:BV(t.cost),valueClass:t.cost>0?"text-yellow-400":"text-text-primary-dark"})]})]}),i.jsxs(ot,{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(Ga,{icon:sn,label:"Retries",value:`${t.retryCount} / ${t.maxRetries}`}),i.jsx(Ga,{icon:vs,label:"Duration",value:e}),i.jsx(Ga,{icon:Yp,label:"Owner",value:URe(t.owner)}),t.target&&i.jsx(Ga,{icon:ih,label:"Agent",value:t.target})]})]}),(t.requestId||t.missionId||t.projectTaskId||t.triggerId)&&i.jsxs(ot,{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(Ga,{icon:Yc,label:"Request",value:Tg(t.requestId)}),t.missionId&&i.jsx(Ga,{icon:Yc,label:"Mission",value:Tg(t.missionId)}),t.projectTaskId&&i.jsx(Ga,{icon:Yc,label:"Project Task",value:Tg(t.projectTaskId)}),t.triggerId&&i.jsx(Ga,{icon:Yc,label:"Trigger",value:Tg(t.triggerId)}),t.parentWorkItemId&&i.jsx(Ga,{icon:Yc,label:"Parent Item",value:Tg(t.parentWorkItemId)})]})]}),i.jsxs(ot,{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:Hg(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:Hg(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:Hg(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:Hg(t.scheduledAt)})]})]})]})]})};UV.displayName="WorkItemMetrics";function WRe(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 Tg(t){return t.length<=12?t:`${t.slice(0,8)}...`}function VRe(t){const e={total:t.length,running:0,queued:0,done:0,failed:0,blocked:0};for(const n of t)switch(n.status){case"running":e.running++;break;case"queued":case"scheduled":e.queued++;break;case"done":e.done++;break;case"failed":e.failed++;break;case"blocked":e.blocked++;break}return e}const $Re=({stats:t})=>t?i.jsxs(j2,{variant:"horizontal",className:"grid-cols-3 md:grid-cols-6","data-testid":"workitem-summary-bar",children:[i.jsx(ii,{label:"Total",value:t.total}),i.jsx(ii,{label:"Running",children:i.jsx("span",{className:"text-blue-400",children:t.running})}),i.jsx(ii,{label:"Queued",children:i.jsx("span",{className:"text-yellow-400",children:t.queued})}),i.jsx(ii,{label:"Done",children:i.jsx("span",{className:"text-green-400",children:t.done})}),i.jsx(ii,{label:"Failed",children:i.jsx("span",{className:"text-red-400",children:t.failed})}),i.jsx(ii,{label:"Blocked",children:i.jsx("span",{className:"text-orange-400",children:t.blocked})})]}):null,zV=()=>{const t=ps(),[e,n]=w.useState([]),[s,r]=w.useState(!0),[a,o]=w.useState(null),[l,c]=w.useState("all"),[d,u]=w.useState(""),[h,f]=w.useState(""),p=w.useRef(),x=w.useCallback(k=>{f(k),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{u(k)},300)},[]);w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const y=w.useCallback(async()=>{r(!0),o(null);try{const k=await xt.getWorkItems();if(!Array.isArray(k)){console.warn("[WorkItems] getWorkItems returned non-array:",typeof k,k),n([]);return}n(k)}catch(k){console.warn("[WorkItems] loadItems error:",k),o(k instanceof Error?k.message:"Failed to load work items")}finally{r(!1)}},[]);w.useEffect(()=>{y()},[y]);const m=w.useMemo(()=>{let k=e;if(l!=="all"&&(k=k.filter(M=>M.status===l)),d.trim()){const M=d.toLowerCase();k=k.filter(T=>{var A;return T.title.toLowerCase().includes(M)||T.id.toLowerCase().includes(M)||((A=T.target)==null?void 0:A.toLowerCase().includes(M))||T.type.toLowerCase().includes(M)})}const E={running:0,blocked:1,failed:2,done:3,completed:3,cancelled:4,queued:5,scheduled:5};return k.sort((M,T)=>{const A=E[M.status]??5,N=E[T.status]??5;return A!==N?A-N:new Date(T.createdAt).getTime()-new Date(M.createdAt).getTime()})},[e,l,d]),g=w.useMemo(()=>{const k={all:e.length};for(const E of e)k[E.status]=(k[E.status]||0)+1;return k},[e]),v=w.useMemo(()=>e.length>0?VRe(e):null,[e]),b=[{key:"all",label:"All"},{key:"running",label:"Running"},{key:"queued",label:"Queued"},{key:"done",label:"Completed"},{key:"failed",label:"Failed"},{key:"blocked",label:"Blocked"},{key:"cancelled",label:"Cancelled"}],_=w.useCallback((k,E)=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),t(`/workitems/${E}`))},[t]);return i.jsxs("div",{className:"p-6 max-w-7xl mx-auto","data-testid":"workitems-page",children:[i.jsxs("div",{className:"mb-6",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("h1",{className:"text-2xl font-bold text-text-primary-dark",children:"Work Items"}),i.jsx(de,{variant:"secondary",size:"sm",icon:sn,onClick:y,loading:s,"data-testid":"workitems-refresh",children:"Refresh"})]}),i.jsx("p",{className:"text-sm text-text-secondary-dark",children:"Execution-level view of all system tasks in the task pool."})]}),!s&&i.jsx($Re,{stats:v}),i.jsx(Od,{tabs:b.map(k=>({value:k.key,label:k.label,count:g[k.key]})),activeTab:l,onTabChange:k=>c(k),searchPlaceholder:"Search by title, ID, agent...",searchValue:h,onSearchChange:x}),s&&i.jsx("div",{"data-testid":"workitems-loading",children:i.jsx(N1,{count:4})}),a&&!s&&i.jsxs(et,{variant:"error",title:"Failed to load work items",onClose:()=>o(null),"data-testid":"workitems-error",children:[a,i.jsx(de,{variant:"ghost",size:"sm",onClick:y,className:"mt-2",children:"Retry"})]}),!s&&!a&&m.length===0&&i.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-16 text-text-secondary-dark","data-testid":"workitems-empty",children:[i.jsx(Sh,{className:"h-10 w-10 opacity-40"}),i.jsx("span",{className:"text-sm",children:e.length===0?"No work items in the pool yet.":"No work items match the current filters."})]}),!s&&!a&&m.length>0&&i.jsx("div",{className:"flex flex-col gap-2","data-testid":"workitems-list",children:m.map(k=>i.jsx(ot,{variant:"default",padding:"md",interactive:!0,className:"hover:border-primary/40",role:"button",tabIndex:0,onClick:()=>t(`/workitems/${k.id}`),onKeyDown:E=>_(E,k.id),"data-testid":`workitem-row-${k.id}`,children:i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"flex items-center gap-2 mb-1",children:i.jsx("span",{className:"text-base font-medium text-text-primary-dark truncate",children:k.title})}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx(Po,{status:rI(k.status),children:iI(k.status)}),i.jsx(ct,{variant:aI(k.type),size:"sm",children:oI(k.type)}),k.target&&i.jsx(ct,{variant:"default",size:"sm",children:k.target}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:Ww(k.createdAt)})]})]}),i.jsx("span",{className:"text-xs text-text-secondary-dark font-mono flex-shrink-0",children:k.id.slice(0,8)})]})},k.id))})]})};zV.displayName="WorkItems";const HV=()=>{const{id:t}=vh(),e=ps(),[n,s]=w.useState(null),[r,a]=w.useState(!0),[o,l]=w.useState(null),[c,d]=w.useState(!1),u=w.useCallback(async(x=!0)=>{if(t){x?a(!0):d(!0),l(null);try{const y=await xt.getWorkItem(t);s(y)}catch(y){const m=y instanceof Error?y.message:"Failed to load WorkItem";l(m)}finally{a(!1),d(!1)}}},[t]);w.useEffect(()=>{u(!0)},[u]),w.useEffect(()=>{if(!n||n.status!=="running")return;const x=setInterval(()=>{u(!1)},1e4);return()=>clearInterval(x)},[n==null?void 0:n.status,u]);const h=()=>{e("/workitems")},f=()=>{u(!1)};if(r)return i.jsx("div",{className:"flex items-center justify-center h-64","data-testid":"workitem-detail-loading",children:i.jsx(Ut,{})});if(o)return i.jsxs("div",{className:"p-6","data-testid":"workitem-detail-error",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:zr,onClick:h,className:"mb-6",children:"Back to WorkItems"}),i.jsx(ot,{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 text-lg font-medium mb-2",children:"Failed to load WorkItem"}),i.jsx("p",{className:"text-text-secondary-dark text-sm mb-4",children:o}),i.jsx(de,{variant:"secondary",size:"sm",icon:sn,onClick:()=>u(!0),children:"Retry"})]})})]});if(!n)return i.jsxs("div",{className:"p-6","data-testid":"workitem-detail-not-found",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:zr,onClick:h,className:"mb-6",children:"Back to WorkItems"}),i.jsx(ot,{variant:"default",padding:"lg",children:i.jsx(Cs,{icon:xY,title:"WorkItem not found.",compact:!0})})]});const p=FV(n);return i.jsxs("div",{className:"p-6 max-w-[1400px] mx-auto","data-testid":"workitem-detail",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:zr,onClick:h,className:"mb-4","data-testid":"workitem-detail-back",children:"Back to WorkItems"}),i.jsxs("div",{className:"mb-6","data-testid":"workitem-detail-header",children:[i.jsxs("div",{className:"flex items-start justify-between gap-4 mb-3",children:[i.jsx("div",{className:"flex-1 min-w-0",children:i.jsxs("h1",{className:"text-xl font-bold text-text-primary-dark truncate",children:["WorkItem: ",LA(n.id)," — ",n.title]})}),i.jsx(de,{variant:"secondary",size:"sm",icon:sn,onClick:f,loading:c,"data-testid":"workitem-detail-refresh",children:"Refresh"})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx(Po,{status:rI(n.status),children:iI(n.status)}),i.jsx(ct,{variant:aI(n.type),children:oI(n.type)}),i.jsxs(ct,{variant:"default",children:["Retry ",n.retryCount,"/",n.maxRetries]}),n.requestId&&i.jsx(ct,{variant:"info",children:i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(ws,{className:"h-3 w-3"}),"Request: ",LA(n.requestId)]})}),n.missionId&&i.jsx(ct,{variant:"info",children:i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(ws,{className:"h-3 w-3"}),"Mission: ",LA(n.missionId)]})}),i.jsxs("span",{className:"text-xs text-text-secondary-dark ml-2",children:["Created ",Ww(n.createdAt)]}),n.target&&i.jsxs(ct,{variant:"primary",children:["Agent: ",n.target]})]}),n.description&&i.jsx("p",{className:"mt-3 text-sm text-text-secondary-dark leading-relaxed",children:n.description})]}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[i.jsx("div",{className:"lg:col-span-2",children:i.jsxs(ot,{variant:"default",padding:"md",children:[i.jsx("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wider mb-4",children:"Activity Timeline"}),i.jsx(lI,{events:p})]})}),i.jsx("div",{className:"lg:col-span-1",children:i.jsx(UV,{item:n})})]})]})};HV.displayName="WorkItemDetail";function LA(t){return t.length<=12?t:t.slice(0,8)}const KRe=({stats:t})=>t?i.jsxs(j2,{variant:"horizontal",className:"grid-cols-2 md:grid-cols-6","data-testid":"request-summary-bar",children:[i.jsx(ii,{label:"Total Incoming",value:t.total}),i.jsx(ii,{label:"Active",value:t.active}),i.jsx(ii,{label:"Blocked",children:i.jsx("span",{className:"text-red-400",children:t.blocked})}),i.jsx(ii,{label:"Waiting",children:i.jsx("span",{className:"text-yellow-400",children:t.waitingConfirmation})}),i.jsx(ii,{label:"Done",children:i.jsx("span",{className:"text-blue-400",children:t.done})}),i.jsx(ii,{label:"Total Cost",children:i.jsx("span",{className:"text-emerald-400",children:t.totalCost>0?`$${t.totalCost.toFixed(2)}`:"$0.00"})})]}):null;function qRe(t){return{active:"Active",blocked:"Blocked",waiting_confirmation:"Waiting Confirmation",done:"Done"}[t]??t}function XRe(t){return{critical:"error",high:"warning",medium:"info",low:"default"}[t]??"default"}function YRe(t){return{critical:"Critical",high:"High",medium:"Medium",low:"Low"}[t]??t}function JRe(t){return t.charAt(0).toUpperCase()+t.slice(1)}function ZRe(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 QRe(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)}}const eIe={active:"bg-amber-500/10 text-amber-400 border-amber-500/20",blocked:"bg-red-500/10 text-red-400 border-red-500/20",waiting_confirmation:"bg-primary/10 text-primary border-primary/20",done:"bg-green-500/10 text-green-400 border-green-500/20"},tIe={active:"bg-amber-400",blocked:"bg-red-400",waiting_confirmation:"bg-primary",done:"bg-green-400"},nIe=({status:t,label:e,className:n=""})=>{const s=eIe[t],r=tIe[t],a=e??qRe(t),o=t==="active";return i.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded-full border ${s} ${n}`.trim(),"data-status":t,"data-testid":`request-status-pill-${t}`,children:[i.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${r} ${o?"animate-pulse":""}`.trim(),"aria-hidden":"true"}),a]})},sIe={slack:Xp,email:Yz,chat:Jz,api:E1,manual:Zz},rIe=({item:t})=>{const e=t.status==="done"?"active":t.status==="in_progress"?"connecting":"inactive";return i.jsxs("div",{className:"flex items-center gap-2.5 py-1.5 border-b border-border-dark last:border-b-0","data-testid":`request-child-${t.id}`,children:[i.jsx(Mo,{status:e,size:"sm",pulse:!1}),i.jsx("span",{className:"flex-1 text-xs text-text-secondary-dark",children:t.label}),t.tag&&i.jsx(ct,{variant:"error",size:"sm",children:t.tag}),t.progress!==void 0&&i.jsx("div",{className:"w-20 h-1.5 bg-background-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full bg-primary rounded-full transition-all duration-300",style:{width:`${t.progress}%`}})}),t.assignee&&i.jsx("span",{className:"text-xs text-text-secondary-dark/60",children:t.assignee}),t.dueDate&&i.jsx("span",{className:"text-xs text-text-secondary-dark/60 whitespace-nowrap",children:t.dueDate})]})},iIe=({request:t})=>{const[e,n]=w.useState(!1),s=ps(),r=!!(t.childItems&&t.childItems.length>0),a=w.useCallback(()=>{s(`/tasks/${t.id}`)},[s,t.id]),o=w.useCallback(f=>{f.stopPropagation(),r&&n(p=>!p)},[r]),l=w.useCallback(f=>{f.key==="Enter"?(f.preventDefault(),a()):f.key===" "&&(f.preventDefault(),r&&n(p=>!p))},[a,r]),c=sIe[t.source]??Sh,d=XRe(t.priority),u=JRe(t.source),h=ZRe(t.updatedAt);return i.jsx("li",{className:"list-none",children:i.jsxs(ot,{variant:"default",padding:"none",className:"overflow-hidden hover:border-border-light transition-colors","data-testid":`request-row-${t.id}`,children:[i.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 cursor-pointer hover:bg-background-dark/30 transition-colors",role:"button",tabIndex:0,"aria-label":`Open request: ${t.title}`,onClick:a,onKeyDown:l,children:[i.jsx(c,{className:"h-5 w-5 text-text-secondary-dark flex-shrink-0","aria-label":u}),i.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-1",children:[i.jsxs("div",{className:"flex items-start gap-2","data-testid":"request-tier-top",children:[i.jsx("span",{className:"text-[15px] font-semibold leading-5 text-text-primary-dark line-clamp-2 flex-1 min-w-0",children:t.title}),i.jsx(nIe,{status:t.status,className:"flex-shrink-0"})]}),i.jsxs("div",{className:"flex items-center gap-3 text-xs text-text-secondary-dark/70 flex-wrap","data-testid":"request-tier-bottom",children:[i.jsx(ct,{variant:d,size:"sm",children:YRe(t.priority)}),t.category&&i.jsx("span",{"data-testid":"request-meta-category",className:"text-text-secondary-dark",children:t.category}),t.missionLink&&i.jsxs("span",{"data-testid":"request-meta-mission",className:"whitespace-nowrap",children:["Mission: ",i.jsx("span",{className:"text-primary",children:t.missionLink})]}),i.jsxs("span",{"data-testid":"request-meta-workitems",className:"inline-flex items-center gap-1 whitespace-nowrap",title:`${t.workItemCount} work item${t.workItemCount===1?"":"s"}`,children:[i.jsx(Dx,{className:"h-3 w-3","aria-hidden":"true"}),t.workItemCount,i.jsxs("span",{className:"sr-only",children:[" ","work item",t.workItemCount===1?"":"s"]})]}),i.jsx("span",{"data-testid":"request-meta-updated",className:"ml-auto whitespace-nowrap",children:h})]})]}),r&&i.jsx(Ft,{icon:e?$r:Wr,size:"xs",onClick:o,className:"flex-shrink-0","aria-label":e?"Collapse work items":"Expand work items"})]}),e&&i.jsxs("div",{className:"border-t border-border-dark px-4 py-2 space-y-1.5","data-testid":"request-children",children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-secondary-dark/60",children:[i.jsx("span",{className:"uppercase tracking-wide",children:"Source"}),i.jsx(ct,{variant:"default",size:"sm",children:u}),t.ownerAgent&&i.jsxs("span",{className:"text-text-secondary-dark",children:["via ",t.ownerAgent]})]}),r&&i.jsx("div",{children:t.childItems.map(f=>i.jsx(rIe,{item:f},f.id))})]})]})})};function aIe(t){switch(t){case"open":case"ready":case"running":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 oIe(t){switch(t){case"high":return"high";case"low":return"low";default:return"medium"}}function lIe(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:aIe(e.status||""),priority:oIe(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}}).sort((e,n)=>new Date(n.updatedAt).getTime()-new Date(e.updatedAt).getTime())}const cIe=new Set(["critical","high"]),dIe=({activeFilter:t,secondaryFilters:e,searchQuery:n,onStatsLoaded:s})=>{const[r,a]=w.useState([]),[o,l]=w.useState(!0),[c,d]=w.useState(null),u=w.useCallback(async()=>{l(!0),d(null);try{const p=await xt.getRequests();if(!Array.isArray(p)){console.warn("[RequestList] getRequests returned non-array:",typeof p,p),a([]);return}const x=lIe(p);a(x)}catch(p){console.warn("[RequestList] loadRequests error:",p),d(p instanceof Error?p.message:"Failed to load requests"),a([])}finally{l(!1)}},[]);w.useEffect(()=>{u()},[u]);const h=w.useMemo(()=>QRe(r),[r]);w.useEffect(()=>{s(h)},[h,s]);const f=w.useMemo(()=>{let p=r;if(t!=="all"&&(p=p.filter(x=>x.status===t)),e&&e.size>0&&(e.has("urgent")&&(p=p.filter(x=>cIe.has(x.priority))),e.has("assigned_to_me")&&(p=p.filter(x=>x.requester==="user"))),n.trim()){const x=n.toLowerCase();p=p.filter(y=>{var m;return y.title.toLowerCase().includes(x)||y.requester.toLowerCase().includes(x)||((m=y.missionLink)==null?void 0:m.toLowerCase().includes(x))})}return p},[r,t,e,n]);return o?i.jsx("div",{"data-testid":"request-list-loading",children:i.jsx(N1,{count:4})}):c?i.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-16 text-text-secondary-dark","data-testid":"request-list-error",children:[i.jsx("span",{className:"text-sm text-red-400",children:c}),i.jsx(de,{variant:"link",onClick:u,children:"Retry"})]}):f.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-16 text-text-secondary-dark","data-testid":"request-list-empty",children:[i.jsx(Sh,{className:"h-10 w-10 opacity-40"}),i.jsx("span",{className:"text-sm",children:r.length===0?"No requests found. Requests will appear here when user messages are processed.":"No requests match the current filters."})]}):i.jsx("div",{className:"flex flex-col gap-2","data-testid":"request-list",children:f.map(p=>i.jsx(iIe,{request:p},p.id))})},uIe=()=>{const[t,e]=w.useState(null),[n,s]=w.useState("active"),[r,a]=w.useState(new Set),[o,l]=w.useState(""),c=w.useCallback(f=>{e(f)},[]),d=w.useCallback(f=>{a(p=>{const x=new Set(p);return x.has(f)?x.delete(f):x.add(f),x})},[]),u=w.useMemo(()=>[{value:"all",label:"All",count:t==null?void 0:t.total},{value:"active",label:"Active",count:t==null?void 0:t.active},{value:"blocked",label:"Blocked",count:t==null?void 0:t.blocked},{value:"waiting_confirmation",label:"Waiting",count:t==null?void 0:t.waitingConfirmation},{value:"done",label:"Done",count:t==null?void 0:t.done}],[t]),h=w.useMemo(()=>[{value:"assigned_to_me",label:"Assigned to Me"},{value:"urgent",label:"Urgent"}],[]);return i.jsxs("div",{className:"p-6 max-w-7xl mx-auto","data-testid":"requests-page",children:[i.jsxs("div",{className:"mb-6","data-testid":"requests-page-header",children:[i.jsx("h1",{className:"text-2xl font-bold text-text-primary-dark",children:"Requests"}),i.jsx("p",{className:"text-sm text-text-secondary-dark",children:"Monitor and triage incoming work from all channels."})]}),i.jsx(KRe,{stats:t}),i.jsx(Od,{tabs:u,activeTab:n,onTabChange:f=>s(f),searchPlaceholder:"Search requests...",searchValue:o,onSearchChange:l,secondaryFilters:h,activeSecondaryFilters:r,onSecondaryFilterToggle:f=>d(f)}),i.jsx(dIe,{activeFilter:n,secondaryFilters:r,searchQuery:o,onStatsLoaded:c})]})},x5={open:"text-blue-400",in_progress:"text-amber-400",blocked:"text-red-400",waiting_confirmation:"text-primary",done:"text-green-400",cancelled:"text-text-secondary-dark"};function _N(t){return{open:"Open",in_progress:"In Progress",blocked:"Blocked",waiting_confirmation:"Waiting Confirmation",done:"Completed",cancelled:"Cancelled"}[t]??t}function hIe(t){return{open:"active",in_progress:"running",blocked:"blocked",waiting_confirmation:"paused",done:"completed",cancelled:"inactive"}[t]??"pending"}const y5=["open","in_progress","done"],fIe=({currentStatus:t})=>{const e=y5.indexOf(t),n=t==="cancelled",s=t==="blocked";return i.jsxs("div",{className:"flex items-center gap-1","data-testid":"request-progress-rail",children:[y5.map((r,a)=>{const o=e>=0&&a<=e,l=r===t;return i.jsxs(Mn.Fragment,{children:[a>0&&i.jsx("div",{className:`flex-1 h-0.5 ${o?"bg-green-500":"bg-border-dark"}`}),i.jsxs("div",{className:`flex items-center gap-1.5 px-2 py-1 rounded text-xs font-medium ${l?`${x5[r]||"text-blue-400"} bg-surface-dark border border-primary/30`:o?"text-green-400 bg-green-500/10":"text-text-secondary-dark bg-surface-dark"}`,children:[o&&!l&&i.jsx(ra,{className:"h-3 w-3"}),_N(r)]})]},r)}),(n||s)&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"flex-1 h-0.5 bg-border-dark"}),i.jsx("div",{className:`flex items-center gap-1.5 px-2 py-1 rounded text-xs font-medium ${x5[t]||"text-text-secondary-dark"} bg-surface-dark border border-red-500/30`,children:_N(t)})]})]})},pIe=({workItems:t,onItemClick:e})=>{const[n,s]=w.useState(null);return t.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-text-secondary-dark","data-testid":"request-workitems-empty",children:[i.jsx(Sh,{className:"h-8 w-8 opacity-40"}),i.jsx("span",{className:"text-sm",children:"No work items associated with this request yet."})]}):i.jsx("div",{className:"flex flex-col gap-2","data-testid":"request-workitems-list",children:t.map(r=>{const a=n===r.id,o=a?FV(r):[];return i.jsxs(ot,{variant:"default",padding:"none",className:"overflow-hidden hover:border-primary/40 transition-colors","data-testid":`request-workitem-${r.id}`,children:[i.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-background-dark/30 transition-colors",role:"button",tabIndex:0,onClick:()=>s(a?null:r.id),onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),s(a?null:r.id))},children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"flex items-center gap-2 mb-1",children:i.jsx("span",{className:"text-sm font-medium text-text-primary-dark truncate",children:r.title})}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx(Po,{status:rI(r.status),children:iI(r.status)}),i.jsx(ct,{variant:aI(r.type),size:"sm",children:oI(r.type)}),r.target&&i.jsx(ct,{variant:"default",size:"sm",children:r.target}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:Ww(r.createdAt)})]})]}),i.jsx(de,{variant:"link",size:"xs",onClick:l=>{l.stopPropagation(),e(r.id)},className:"flex-shrink-0","data-testid":`request-workitem-detail-link-${r.id}`,children:"Details"})]}),a&&i.jsx("div",{className:"border-t border-border-dark px-4 py-3","data-testid":`request-workitem-timeline-${r.id}`,children:i.jsx(lI,{events:o})})]},r.id)})})},GV=()=>{const{id:t}=vh(),e=ps(),[n,s]=w.useState(null),[r,a]=w.useState([]),[o,l]=w.useState(!0),[c,d]=w.useState(null),[u,h]=w.useState(!1),f=w.useCallback(async(b=!0)=>{if(t){b?l(!0):h(!0),d(null);try{const[_,k]=await Promise.all([xt.getRequest(t),xt.getWorkItemsByRequest(t)]);s(_),a(k.sort((E,M)=>new Date(M.createdAt).getTime()-new Date(E.createdAt).getTime()))}catch(_){const k=_ instanceof Error?_.message:"Failed to load request";d(k)}finally{l(!1),h(!1)}}},[t]);w.useEffect(()=>{f(!0)},[f]),w.useEffect(()=>{if(!n||n.status==="done"||n.status==="cancelled")return;const b=setInterval(()=>{f(!1)},15e3);return()=>clearInterval(b)},[n==null?void 0:n.status,f]);const p=w.useCallback(()=>{e("/tasks")},[e]),x=w.useCallback(b=>{e(`/workitems/${b}`)},[e]),y=w.useCallback(()=>{f(!1)},[f]),m=w.useCallback(async b=>{if(t)try{const _=b==="confirmed"?"done":"cancelled";await xt.updateRequest(t,{status:_}),f(!1)}catch(_){const k=_ instanceof Error?_.message:"Failed to update request";d(k)}},[t,f]),g=w.useMemo(()=>n?n.totalInputTokens+n.totalOutputTokens:0,[n]),v=w.useMemo(()=>{if(!n)return"";const b=new Date(n.createdAt).getTime(),k=(n.completedAt?new Date(n.completedAt).getTime():Date.now())-b,E=Math.floor(k/6e4),M=Math.floor(E/60);return E<1?"< 1m":M<1?`${E}m`:`${M}h ${E%60}m`},[n]);return o?i.jsx("div",{className:"flex items-center justify-center h-64","data-testid":"request-detail-loading",children:i.jsx(Ut,{})}):c?i.jsxs("div",{className:"p-6","data-testid":"request-detail-error",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:zr,onClick:p,className:"mb-6",children:"Back to Requests"}),i.jsx(ot,{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 text-lg font-medium mb-2",children:"Failed to load Request"}),i.jsx("p",{className:"text-text-secondary-dark text-sm mb-4",children:c}),i.jsx(de,{variant:"secondary",size:"sm",icon:sn,onClick:()=>f(!0),children:"Retry"})]})})]}):n?i.jsxs("div",{className:"p-6 max-w-[1200px] mx-auto","data-testid":"request-detail",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:zr,onClick:p,className:"mb-4","data-testid":"request-detail-back",children:"Back to Requests"}),i.jsxs("div",{className:"mb-6","data-testid":"request-detail-header",children:[i.jsxs("div",{className:"flex items-start justify-between gap-4 mb-3",children:[i.jsx("div",{className:"flex-1 min-w-0",children:i.jsx("h1",{className:"text-xl font-bold text-text-primary-dark",children:n.title})}),i.jsx(de,{variant:"secondary",size:"sm",icon:sn,onClick:y,loading:u,"data-testid":"request-detail-refresh",children:"Refresh"})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-4",children:[i.jsx(Po,{status:hIe(n.status),children:_N(n.status)}),n.priority&&n.priority!=="normal"&&i.jsx(ct,{variant:n.priority==="high"?"warning":"default",size:"sm",children:n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}),n.intentCategory&&i.jsx(ct,{variant:"info",size:"sm",children:i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(s6,{className:"h-3 w-3"}),n.intentCategory.replace(/_/g," ")]})}),n.intentLevel&&i.jsx(ct,{variant:"default",size:"sm",children:n.intentLevel}),n.requiresConfirmation&&i.jsx(ct,{variant:"warning",size:"sm",children:"Requires Confirmation"}),i.jsxs("span",{className:"text-xs text-text-secondary-dark ml-2",children:["Created ",Ww(n.createdAt)]})]}),i.jsx(fIe,{currentStatus:n.status})]}),n.requiresConfirmation&&n.status==="waiting_confirmation"&&i.jsxs(ot,{padding:"md",className:"flex gap-3 mt-4","data-testid":"request-action-area",children:[i.jsx("span",{className:"text-sm text-text-secondary-dark mr-auto flex items-center",children:"This request requires your confirmation before completing"}),i.jsx(de,{variant:"secondary",size:"sm",onClick:()=>m("rejected"),children:"Reject"}),i.jsx(de,{variant:"primary",size:"sm",onClick:()=>m("confirmed"),children:"Approve"})]}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6",children:[i.jsx("div",{className:"lg:col-span-2",children:i.jsxs(ot,{variant:"default",padding:"md",children:[i.jsx("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(Za,{className:"h-4 w-4"}),"Original Message"]})}),n.description?i.jsx("p",{className:"text-sm text-text-primary-dark leading-relaxed whitespace-pre-wrap",children:n.description}):i.jsx("p",{className:"text-sm text-text-secondary-dark italic",children:"No description provided."}),n.sourceConversationItemId&&i.jsx("div",{className:"mt-4 pt-4 border-t border-border-dark",children:i.jsxs("span",{className:"text-xs text-text-secondary-dark",children:["Source: ",i.jsx("span",{className:"font-mono",children:n.sourceConversationItemId})]})}),n.tags.length>0&&i.jsx("div",{className:"mt-4 pt-4 border-t border-border-dark flex items-center gap-2 flex-wrap",children:n.tags.map(b=>i.jsx(ct,{variant:"default",size:"sm",children:b},b))})]})}),i.jsx("div",{className:"lg:col-span-1",children:i.jsxs(ot,{variant:"default",padding:"md",children:[i.jsx("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:"Statistics"}),i.jsxs("div",{className:"flex flex-col gap-3",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-text-secondary-dark",children:[i.jsx(Lx,{className:"h-3.5 w-3.5"}),"Total Tokens"]}),i.jsx("span",{className:"text-sm font-medium text-text-primary-dark",children:fx(g)})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"flex items-center gap-1.5 text-xs text-text-secondary-dark pl-5",children:"Input"}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:fx(n.totalInputTokens)})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"flex items-center gap-1.5 text-xs text-text-secondary-dark pl-5",children:"Output"}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:fx(n.totalOutputTokens)})]}),i.jsx("div",{className:"border-t border-border-dark"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-text-secondary-dark",children:[i.jsx(S2,{className:"h-3.5 w-3.5"}),"Total Cost"]}),i.jsx("span",{className:"text-sm font-medium text-text-primary-dark",children:BV(n.totalCost)})]}),i.jsx("div",{className:"border-t border-border-dark"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-text-secondary-dark",children:[i.jsx(vs,{className:"h-3.5 w-3.5"}),"Elapsed Time"]}),i.jsx("span",{className:"text-sm font-medium text-text-primary-dark",children:v})]}),i.jsx("div",{className:"border-t border-border-dark"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-text-secondary-dark",children:[i.jsx(Dx,{className:"h-3.5 w-3.5"}),"Work Items"]}),i.jsx("span",{className:"text-sm font-medium text-text-primary-dark",children:r.length})]})]})]})})]}),i.jsxs("div",{"data-testid":"request-detail-workitems",children:[i.jsx("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(Dx,{className:"h-4 w-4"}),"Execution Timeline (",r.length," work items)"]})}),i.jsx(pIe,{workItems:r,onItemClick:x})]})]}):i.jsxs("div",{className:"p-6","data-testid":"request-detail-not-found",children:[i.jsx(de,{variant:"ghost",size:"sm",icon:zr,onClick:p,className:"mb-6",children:"Back to Requests"}),i.jsx(ot,{variant:"default",padding:"lg",children:i.jsx(Cs,{icon:Za,title:"Request not found.",compact:!0})})]})};GV.displayName="RequestDetail";const mIe=()=>{},gIe=({onSaved:t})=>{const[e,n]=w.useState(!1),[s,r]=w.useState(""),[a,o]=w.useState(!1);w.useEffect(()=>{const c=()=>{o(!!b0()),n(!0)};return window.addEventListener(aM,c),()=>window.removeEventListener(aM,c)},[]);const l=w.useCallback(c=>{c.preventDefault();const d=s.trim();d&&(T8(d),n(!1),t?t():window.location.reload())},[s,t]);return e?i.jsx("div",{className:"relative z-[100]",children:i.jsx(Kr,{isOpen:!0,onClose:mIe,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(xs,{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:C1,disabled:!s.trim(),"data-testid":"api-token-submit",children:"Save and reload"})})]})})}):null};function xIe(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 v5(t){return!Ste.some(e=>t===e||t.startsWith(`${e}/`))}function b5(){try{return window.localStorage.getItem(cM)==="1"}catch{return!1}}function yIe(t){try{t?window.localStorage.setItem(cM,"1"):window.localStorage.removeItem(cM)}catch{}}const vIe=()=>{const t=uo(),e=ps(),n=w.useRef(t.pathname);return n.current=t.pathname,w.useEffect(()=>{if(b5()||!v5(n.current))return;let s=!1;return eo.getStatus().then(r=>{s||b5()||!v5(n.current)||xIe(r)&&e(J2,{replace:!0})}).catch(()=>{}),()=>{s=!0}},[]),null},bIe=({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(Mn.Fragment,{children:[i.jsxs("div",{className:"flex flex-col items-center","data-testid":`step-${s}`,children:[i.jsx("div",{className:na("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($n,{className:"w-4 h-4"}):s+1}),i.jsx("span",{className:na("mt-1.5 text-[10px] font-medium uppercase tracking-wide",a?"text-primary":"text-text-secondary-dark"),children:n})]}),!o&&i.jsx("div",{className:na("h-0.5 w-12 mx-1 mt-[-12px] transition-colors duration-200",r?"bg-primary":"bg-border-dark")})]},n)})});function _5(t){return t.status!=="running"}function _Ie(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 SIe(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 wIe=({questions:t,submitLabel:e,submitting:n=!1,error:s=null,serverProblems:r=[],onSubmit:a})=>{const[o,l]=w.useState(()=>_Ie(t)),[c,d]=w.useState([]),u=new Set([...c,...r]),h=(x,y)=>{l(m=>({...m,[x]:y})),d(m=>m.filter(g=>g!==x))},f=(x,y)=>{const m=o[x],g=Array.isArray(m)?m:[];h(x,g.includes(y)?g.filter(v=>v!==y):[...g,y])},p=x=>{x.preventDefault();const y=SIe(t,o);d(y),y.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 y=`bundle-q-${x.id}`,m=o[x.id],g=u.has(x.id);return i.jsxs(Ei,{children:[i.jsx(gt,{id:`${y}-label`,htmlFor:x.type==="multiselect"?void 0:y,required:x.required,children:x.label}),x.type==="text"&&i.jsx(Bt,{id:y,value:typeof m=="string"?m:"",placeholder:x.placeholder,error:g,onChange:v=>h(x.id,v.target.value)}),x.type==="textarea"&&i.jsx(qs,{id:y,rows:3,value:typeof m=="string"?m:"",placeholder:x.placeholder,error:g,onChange:v=>h(x.id,v.target.value)}),x.type==="select"&&i.jsxs(pn,{id:y,value:typeof m=="string"?m:"",error:g,onChange:v=>h(x.id,v.target.value),children:[!x.required&&x.default===""&&i.jsx("option",{value:"",children:"—"}),x.required&&i.jsx("option",{value:"",children:"Select…"}),(x.options??[]).map(v=>i.jsx("option",{value:v.value,children:v.label??v.value},v.value))]}),x.type==="multiselect"&&i.jsx("div",{role:"group","aria-labelledby":`${y}-label`,className:"flex flex-wrap gap-2",id:y,children:(x.options??[]).map(v=>{const b=Array.isArray(m)&&m.includes(v.value);return i.jsx(de,{type:"button",size:"sm",variant:b?"primary":"secondary","aria-pressed":b,"data-testid":`bundle-option-${x.id}-${v.value}`,onClick:()=>f(x.id,v.value),children:v.label??v.value},v.value)})}),x.help&&i.jsx(Ql,{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(et,{variant:"error",size:"sm",children:s}),i.jsx(de,{type:"submit",fullWidth:!0,loading:n,"data-testid":"bundle-deploy",children:e})]})},DA={LIST:"/api/bundles",detail:t=>`/api/bundles/${encodeURIComponent(t)}`,APPLY:"/api/bundles/apply",job:t=>`/api/bundles/apply/${encodeURIComponent(t)}`},CIe=1500,kIe={queued:"Waiting",running:"In progress",done:"Done",failed:"Failed",pending:"Finishes automatically later",skipped:"Skipped"},EIe={"crewly-agent":"Crewly Agent (DeepSeek)","claude-code":"Claude Code","codex-cli":"Codex","gemini-cli":"Gemini CLI","opencode-cli":"OpenCode","antigravity-cli":"Antigravity CLI"},AIe={entry:"Entry (2 vCPU, 4 GB)",standard:"Standard (4 vCPU, 8 GB)",advanced:"Advanced (8 vCPU, 16 GB)"};class d_ extends Error{constructor(e,n=null,s=[],r=[]){super(e),this.code=n,this.missing=s,this.invalid=r,this.name="BundleRequestError"}}async function OA(t,e){var s;let n;try{n=(await t()).data}catch(r){if(F1(r)){const a=((s=r.response)==null?void 0:s.data)??{};throw new d_(a.error||r.message||e,a.code??null,a.missing??[],a.invalid??[])}throw r instanceof Error?r:new d_(e)}if(!(n!=null&&n.success)||n.data===void 0||n.data===null)throw new d_((n==null?void 0:n.error)||e);return n.data}class TIe{async getBundle(e){return OA(()=>We.get(DA.detail(e)),"Couldn't load this bundle")}async apply(e,n,s){return(await OA(()=>We.post(DA.APPLY,{templateId:e,answers:n,...s?{runtime:s}:{}}),"Deploy failed")).deployment}async getJob(e){return OA(()=>We.get(DA.job(e)),"Couldn't load deploy progress")}}const kb=new TIe,MIe=({status:t})=>t==="done"?i.jsx(ra,{className:"h-4 w-4 shrink-0 text-emerald-400","aria-hidden":!0}):t==="failed"?i.jsx(ul,{className:"h-4 w-4 shrink-0 text-red-400","aria-hidden":!0}):t==="running"?i.jsx(HT,{className:"h-4 w-4 shrink-0 animate-spin text-primary","aria-hidden":!0}):t==="pending"?i.jsx(vs,{className:"h-4 w-4 shrink-0 text-amber-400","aria-hidden":!0}):i.jsx(_2,{className:"h-4 w-4 shrink-0 text-text-secondary-dark","aria-hidden":!0}),NIe=({templateId:t,onBack:e,onDone:n,pollIntervalMs:s=CIe})=>{const[r,a]=w.useState(null),[o,l]=w.useState(null),[c,d]=w.useState(null),[u,h]=w.useState(!1),[f,p]=w.useState(null),[x,y]=w.useState([]),m=w.useRef(null),g=w.useCallback(async()=>{l(null);try{const k=await kb.getBundle(t);a(k.bundle),k.deployment&&d(k.deployment)}catch(k){l(k instanceof Error?k.message:String(k))}},[t]);w.useEffect(()=>{g()},[g]),w.useEffect(()=>{if(!(!c||_5(c)))return m.current=setTimeout(()=>{kb.getJob(c.jobId).then(d).catch(k=>p(k instanceof Error?k.message:String(k)))},s),()=>{m.current&&clearTimeout(m.current)}},[c,s]);const v=async k=>{h(!0),p(null),y([]);try{d(await kb.apply(t,k))}catch(E){E instanceof d_&&y([...E.missing,...E.invalid].map(M=>M.id)),p(E instanceof Error?E.message:String(E))}finally{h(!1)}},b=async()=>{h(!0),p(null);try{d(await kb.apply(t,{}))}catch(k){p(k instanceof Error?k.message:String(k))}finally{h(!1)}},_=()=>{const k=(c==null?void 0:c.teams[0])??null;n({starterId:t,teamId:(k==null?void 0:k.teamId)??null,teamName:(k==null?void 0:k.name)??null,suggestions:[],bundle:!0})};if(o)return i.jsx(et,{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:sn,onClick:()=>void g(),children:"Retry"}),i.jsx(de,{type:"button",size:"sm",variant:"ghost",icon:zr,onClick:e,children:"Choose another"})]})]})});if(!r)return i.jsx(Ut,{centered:!0,text:"Loading bundle…"});if(c){const k=_5(c),E=c.steps.some(T=>T.status==="failed"),M=c.connectors.filter(T=>T.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:k?`"${r.label}" is deployed.`:`Deploying "${r.label}"…`}),i.jsx("ul",{className:"space-y-2",children:c.steps.map(T=>i.jsxs("li",{className:"flex items-start gap-2 text-sm","data-testid":`bundle-step-${T.id}`,children:[i.jsx(MIe,{status:T.status}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("span",{className:"text-text-primary-dark",children:T.label})," ",i.jsxs("span",{className:"text-xs text-text-secondary-dark",children:["· ",kIe[T.status]]}),(T.error??T.message)&&i.jsx("p",{className:"text-xs text-text-secondary-dark",children:T.error??T.message})]})]},T.id))}),M.length>0&&i.jsx(et,{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:M.map(T=>i.jsxs("li",{children:[i.jsxs("a",{className:"text-primary underline",href:T.connectPath,children:[T.id,T.products.length>0?` (${T.products.join(", ")})`:""]}),T.required?"":" (optional)",": ",T.why]},T.id))})}),f&&i.jsx(et,{variant:"error",size:"sm",children:f}),k&&i.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[E&&i.jsx(de,{type:"button",variant:"secondary",icon:sn,loading:u,onClick:()=>void b(),"data-testid":"bundle-retry",children:"Retry failed steps"}),i.jsx(de,{type:"button",fullWidth:!0,onClick:_,"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(ct,{variant:"primary",children:EIe[r.recommendedRuntime]??r.recommendedRuntime}),i.jsx(ct,{children:AIe[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(k=>i.jsx("li",{children:k},k))})]}),i.jsxs("p",{className:"mt-2 text-xs text-text-secondary-dark",children:["Members: ",r.teams.flatMap(k=>k.members.map(E=>`${E.name} (${E.title})`)).join(", ")]})]}),i.jsx(wIe,{questions:r.questions,submitLabel:`Deploy "${r.label}"`,submitting:u,error:f,serverProblems:x,onSubmit:k=>void v(k)}),i.jsx(de,{type:"button",variant:"ghost",icon:zr,onClick:e,children:"Choose another"})]})},jIe=({onDone:t})=>{const[e,n]=w.useState(null),[s,r]=w.useState(null),[a,o]=w.useState(null),[l,c]=w.useState(null),[d,u]=w.useState(!1),[h,f]=w.useState(null),p=async()=>{o(null);try{const m=await oc.getStarters();n(m),r(g=>{var v;return g??((v=m.find(b=>b.recommended)??m[0])==null?void 0:v.id)??null})}catch(m){o(m instanceof Error?m.message:String(m))}};w.useEffect(()=>{p()},[]);const x=async()=>{var g,v;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 oc.createStarterTeam(m.id);t({starterId:m.id,teamId:((g=b.team)==null?void 0:g.id)??null,teamName:((v=b.team)==null?void 0:v.name)??null,suggestions:m.suggestions})}catch(b){c(b instanceof Error?b.message:String(b))}finally{u(!1)}}};if(a)return i.jsx(et,{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:sn,onClick:()=>void p(),children:"Retry"})]})});if(!e)return i.jsx(Ut,{centered:!0,text:"Loading team templates…"});if(h)return i.jsx(NIe,{templateId:h,onBack:()=>f(null),onDone:t});const y=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(ot,{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:v=>{(v.key==="Enter"||v.key===" ")&&(v.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(ct,{variant:"primary",children:"Recommended"}),m.kind==="bundle"&&i.jsx(ct,{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(is,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),m.members.map(v=>v.name).join(", ")]})]}),g&&i.jsx($n,{className:"h-5 w-5 shrink-0 text-primary","aria-hidden":!0})]})},m.id)})}),l&&i.jsx(et,{variant:"error",size:"sm",children:l}),i.jsx(de,{type:"button",fullWidth:!0,loading:d,disabled:!y,onClick:()=>void x(),"data-testid":"starter-create",children:(y==null?void 0:y.members.length)===0?"Start with just the Orc":(y==null?void 0:y.kind)==="bundle"?`Next: details for "${y.label}"`:`Create "${(y==null?void 0:y.label)??""}"`})]})},RIe=4e3,IIe=({suggestions:t,teamId:e,teamName:n,onSent:s})=>{const[r,a]=w.useState(""),[o,l]=w.useState(!1),[c,d]=w.useState(null),[u,h]=w.useState(null),f=r.trim(),p=async()=>{if(f){l(!0),d(null);try{const x=await oc.sendFirstTask(f,e);h(x),s(x)}catch(x){d(x instanceof Error?x.message:String(x))}finally{l(!1)}}};return u?i.jsx(et,{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(qs,{"aria-label":"First task",rows:4,maxLength:RIe,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(et,{variant:"error",size:"sm",children:c}),i.jsx(de,{type:"button",fullWidth:!0,icon:f0,loading:o,disabled:!f,onClick:()=>void p(),"data-testid":"first-task-send",children:"Send it"})]})};async function BA(t,e){var s;let n;try{n=(await t()).data}catch(r){if(F1(r)){const a=(s=r.response)==null?void 0:s.data;throw new Error((a==null?void 0:a.error)||(a==null?void 0:a.message)||r.message||e)}throw r instanceof Error?r:new Error(e)}if(!(n!=null&&n.success)||!n.data)throw new Error((n==null?void 0:n.error)||(n==null?void 0:n.message)||e);return n.data}class PIe{async start(e){return BA(()=>We.post(Ek.START,e?{deviceName:e}:{}),"Could not reach Crewly Cloud")}async status(){return BA(()=>We.get(Ek.STATUS),"Could not read pairing status")}async cancel(){return BA(()=>We.post(Ek.CANCEL),"Could not cancel")}}const FA=new PIe,WV={start:"Connect with your phone",intro:"No need to be at this machine: scan the code or open the link on your phone, sign in and tap Approve. This machine connects by itself.",scan:"Scan with your phone, or open:",code:"Check the code matches",waiting:"Waiting for you to approve on your phone…",cancel:"Cancel",connected:t=>`Connected to Crewly Cloud${t?` (${t})`:""}`,expired:"The link expired. Get a new one.",denied:"The request was denied on crewlyai.com.",cancelled:"Cancelled.",retry:"Get a new link"},LIe=({labels:t=WV,autoStart:e=!1,onConnected:n})=>{const[s,r]=w.useState(null),[a,o]=w.useState(null),[l,c]=w.useState(!1),d=w.useRef(!1),u=w.useCallback(async()=>{c(!0),o(null);try{r(await FA.start())}catch(y){o(y instanceof Error?y.message:String(y))}finally{c(!1)}},[]);w.useEffect(()=>{e&&u()},[e,u]);const h=(s==null?void 0:s.state)==="pending";w.useEffect(()=>{if(!h)return;const y=setInterval(()=>{FA.status().then(r).catch(()=>{})},cne);return()=>clearInterval(y)},[h]),w.useEffect(()=>{(s==null?void 0:s.state)==="connected"&&!d.current&&(d.current=!0,n==null||n(s.tier))},[s,n]);const f=async()=>{try{r(await FA.cancel())}catch(y){o(y instanceof Error?y.message:String(y))}};if((s==null?void 0:s.state)==="connected")return i.jsx(et,{variant:"success",icon:ra,title:t.connected(s.tier),"data-testid":"cloud-pairing-connected",children:s.email??""});if((s==null?void 0:s.state)==="pending"&&s.verificationUrl)return i.jsxs("div",{className:"space-y-4","data-testid":"cloud-pairing-pending",children:[i.jsx("p",{className:"text-sm text-text-secondary-dark",children:t.intro}),i.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-2xl border border-border-dark p-4",children:[i.jsx("div",{className:"rounded-xl bg-white p-2","data-testid":"cloud-pairing-qr",children:i.jsx(R1,{value:s.verificationUrl,size:dne,level:"M"})}),i.jsx("p",{className:"text-xs text-text-secondary-dark",children:t.scan}),i.jsxs("a",{href:s.verificationUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex max-w-full items-center gap-1 break-all text-sm text-primary underline","data-testid":"cloud-pairing-link",children:[s.verificationUrl," ",i.jsx(ws,{className:"h-3 w-3 shrink-0","aria-hidden":!0})]}),i.jsx("p",{className:"text-xs text-text-secondary-dark",children:t.code}),i.jsx("p",{className:"font-mono text-2xl font-bold tracking-widest text-text-primary-dark select-all cursor-text break-all","data-testid":"cloud-pairing-code",onClick:y=>U1(y.currentTarget),children:s.userCode})]}),i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-secondary-dark","data-testid":"cloud-pairing-waiting",children:[i.jsx(Ut,{size:"xs",centered:!1}),t.waiting]}),i.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>void f(),"data-testid":"cloud-pairing-cancel",children:t.cancel})]})]});const p={expired:t.expired,denied:t.denied,cancelled:t.cancelled},x=s?p[s.state]??(s.state==="error"?s.error:void 0):void 0;return i.jsxs("div",{className:"space-y-3","data-testid":"cloud-pairing-idle",children:[(a||x)&&i.jsx(et,{variant:a||(s==null?void 0:s.state)==="error"||(s==null?void 0:s.state)==="denied"?"error":"warning",size:"sm",children:a??x}),i.jsx(de,{type:"button",fullWidth:!0,icon:n6,loading:l,onClick:()=>void u(),"data-testid":"cloud-pairing-start",children:s||a?t.retry:t.start})]})},DIe=({connected:t,tier:e,tokenPageSignInUrl:n,onConnected:s,navigateTo:r=a=>window.location.assign(a)})=>{const[a,o]=w.useState(!1),[l,c]=w.useState(""),[d,u]=w.useState(""),[h,f]=w.useState(!1),[p,x]=w.useState(null);if(t)return i.jsxs(et,{variant:"success",icon:ra,title:"Connected to Crewly Cloud","data-testid":"cloud-connected",children:[e?`Plan: ${e}. `:"","You can use Crewly from your phone now."]});const y=async()=>{f(!0),x(null);try{await oc.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(LIe,{autoStart:!0,labels:WV,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:sh,onClick:()=>r(mne(window.location.origin,tj("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(ws,{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(gt,{htmlFor:"cloud-token",children:"Token"}),i.jsx(Bt,{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(gt,{htmlFor:"cloud-refresh-token",children:"Refresh token (keeps you signed in)"}),i.jsx(Bt,{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(et,{variant:"error",size:"sm",children:p}),i.jsx(de,{type:"button",fullWidth:!0,loading:h,disabled:!l.trim(),onClick:()=>void y(),"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"})]})},OIe="/connections?platform=slack",BIe=({connected:t,cloudConnected:e,onGoToCloud:n,onConnected:s,navigateTo:r=a=>window.location.assign(a)})=>{const[a,o]=w.useState(!1),[l,c]=w.useState(null),d=w.useRef(!1);if(w.useEffect(()=>{t||!e||d.current||(d.current=!0,oc.refreshSlack().then(h=>{h.connected&&s()}).catch(()=>{}))},[t,e,s]),t)return i.jsx(et,{variant:"success",icon:ra,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(et,{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 oc.getSlackInstallUrl(`${window.location.origin}${tj("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(et,{variant:"error",size:"sm",children:l}),i.jsx(de,{type:"button",fullWidth:!0,icon:Xp,loading:a,onClick:()=>void u(),"data-testid":"slack-install",children:"Install Crewly in Slack"}),i.jsxs("a",{href:OIe,className:"inline-flex items-center gap-1 text-xs text-primary underline",children:["More Slack settings ",i.jsx(ws,{className:"h-3 w-3","aria-hidden":!0})]})]})},FIe=["harness","team","first_task","cloud","slack"];function UIe(t){return typeof t=="string"&&FIe.includes(t)}function u_(t,e){return t==null?void 0:t.steps.find(n=>n.id===e)}const Yn={HARNESS:0,ORC:1,LOGIN:2,TEAM:3,TASK:4,CLOUD:5,SLACK:6,DONE:7},zIe={harness:Yn.HARNESS,team:Yn.TEAM,first_task:Yn.TASK,cloud:Yn.CLOUD,slack:Yn.SLACK};function HIe(t){return UIe(t)?zIe[t]:Yn.HARNESS}function S5(t,e){var r;const n=((r=u_(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 Wc=({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})]}),Eb=({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:zr,onClick:t,children:"Back"}),i.jsx(de,{type:"button",variant:s?"primary":"secondary",icon:ip,iconPosition:"right",onClick:e,children:n})]}),GIe=()=>{const t=ps(),[e]=bh(),{overview:n,loading:s,error:r,refresh:a,setOrcHarness:o,savingOrc:l,replaceHarness:c}=m7(),{checklist:d,loading:u,refresh:h}=q8(),[f,p]=w.useState(()=>HIe(e.get($8))),[x,y]=w.useState(Y2),[m,g]=w.useState(null),[v,b]=w.useState(null),[_,k]=w.useState(!1),E=e.get("error"),M=N8((n==null?void 0:n.harnesses)??[],n==null?void 0:n.orcHarness),T=M.some(P=>P.installed),A=M.find(P=>P.id===(n==null?void 0:n.orcHarness))??null;w.useEffect(()=>{if(f!==Yn.TASK||v||u)return;let P=!1;return oc.getStarters().then(B=>{P||b(S5(d,B))}).catch(()=>{P||b(S5(d,[]))}),()=>{P=!0}},[f,v,d,u]);const N=()=>{yIe(!0),t(P3,{replace:!0})},D=()=>{g(Eve(M,(n==null?void 0:n.orcHarness)??null,x)),p(Yn.ORC)},I=async()=>{m&&(m!==(n==null?void 0:n.orcHarness)&&!await o(m)||p(Yn.LOGIN))},F=P=>{b({teamId:P.teamId,teamName:P.teamName,suggestions:P.suggestions,bundle:P.bundle}),h(),p(Yn.TASK)},z=w.useCallback(()=>{h()},[h]),W=()=>u?i.jsx(Ut,{centered:!0}):i.jsx(et,{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:sn,onClick:z,children:"Retry"})]})}),G=()=>s?i.jsx(Ut,{centered:!0,text:"Checking coding harnesses…"}):i.jsx(et,{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:sn,onClick:()=>void a(),children:"Retry"})]})}),K=()=>{var P;if(f<=Yn.LOGIN&&!n)return G();switch(f){case Yn.HARNESS:return i.jsxs(i.Fragment,{children:[i.jsx(Wc,{title:"Pick and install a coding harness",subtitle:"Crewly's AI teammates work through a coding harness. Claude Code is recommended."}),i.jsx(g7,{harnesses:M,systemTools:(n==null?void 0:n.systemTools)??[],selectedId:x,onSelect:y,onInstallFinished:()=>void a()}),i.jsx("div",{className:"mt-6 flex justify-end",children:i.jsx(de,{type:"button",icon:ip,iconPosition:"right",disabled:!T,onClick:D,children:"Next"})}),!T&&i.jsx("p",{className:"mt-2 text-right text-xs text-text-secondary-dark",children:"Install at least one to continue."})]});case Yn.ORC:return i.jsxs(i.Fragment,{children:[i.jsx(Wc,{title:"Which harness should the Orc use?",subtitle:"The orchestrator (Orc) coordinates your team. Choose its harness."}),i.jsx(x7,{harnesses:M,value:m,onChange:g,disabled:l}),r&&i.jsx(et,{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:zr,onClick:()=>p(Yn.HARNESS),children:"Back"}),i.jsx(de,{type:"button",icon:ip,iconPosition:"right",loading:l,disabled:!m,onClick:()=>void I(),children:"Next"})]})]});case Yn.LOGIN:{const B=(A==null?void 0:A.loginState)==="logged_in";return i.jsxs(i.Fragment,{children:[i.jsx(Wc,{title:"Sign in",subtitle:"Sign in so the orchestrator can work."}),A?i.jsx(v7,{harness:A,onLoggedIn:()=>void a(),onHarnessUpdated:c}):i.jsx(et,{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:zr,onClick:()=>p(Yn.ORC),children:"Back"}),i.jsx(de,{type:"button",variant:B?"primary":"secondary",icon:ip,iconPosition:"right",onClick:()=>p(Yn.TEAM),children:B?"Next":"Sign in later"})]})]})}case Yn.TEAM:{const B=((P=u_(d,"team"))==null?void 0:P.detail.teams)??[];return i.jsxs(i.Fragment,{children:[i.jsx(Wc,{title:"Create your first team",subtitle:"Pick a starter team. You can add more later."}),B.length>0&&i.jsxs(et,{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(jIe,{onDone:F}),i.jsx(Eb,{onBack:()=>p(Yn.LOGIN),onNext:()=>p(Yn.TASK),nextLabel:"Skip",primary:!1})]})}case Yn.TASK:return i.jsxs(i.Fragment,{children:[i.jsx(Wc,{title:"Give your team its first task",subtitle:"One sentence is enough."}),(v==null?void 0:v.bundle)&&i.jsx(et,{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."}),v?i.jsx(IIe,{suggestions:v.suggestions,teamId:v.teamId,teamName:v.teamName,onSent:()=>{k(!0),z()}}):i.jsx(Ut,{centered:!0}),i.jsx(Eb,{onBack:()=>p(Yn.TEAM),onNext:()=>p(Yn.CLOUD),nextLabel:_?"Next":"Skip",primary:_})]});case Yn.CLOUD:{const B=u_(d,"cloud");return i.jsxs(i.Fragment,{children:[i.jsx(Wc,{title:"Connect Crewly Cloud",subtitle:"Manage Crewly from your phone; needed for Slack."}),E&&!(B!=null&&B.done)&&i.jsxs(et,{variant:"warning",size:"sm",className:"mb-3",children:["Sign-in didn't finish (",E,"). Try again, or use copy and paste instead."]}),B?i.jsx(DIe,{connected:B.done,tier:B.detail.tier,tokenPageSignInUrl:B.detail.tokenPageSignInUrl,onConnected:z}):W(),i.jsx(Eb,{onBack:()=>p(Yn.TASK),onNext:()=>p(Yn.SLACK),nextLabel:B!=null&&B.done?"Next":"Skip",primary:!!(B!=null&&B.done)})]})}case Yn.SLACK:{const B=u_(d,"slack");return i.jsxs(i.Fragment,{children:[i.jsx(Wc,{title:"Connect Slack",subtitle:"Talk to your team from Slack."}),B?i.jsx(BIe,{connected:B.done,cloudConnected:B.detail.cloudConnected,onGoToCloud:()=>p(Yn.CLOUD),onConnected:z}):W(),i.jsx(Eb,{onBack:()=>p(Yn.CLOUD),onNext:()=>p(Yn.DONE),nextLabel:B!=null&&B.done?"Next":"Skip",primary:!!(B!=null&&B.done)})]})}default:{const B=A?W1[A.loginState]:null;return i.jsxs("div",{className:"space-y-4","data-testid":"setup-done",children:[i.jsxs("div",{className:"text-center",children:[i.jsx(ra,{className:"mx-auto h-12 w-12 text-emerald-400"}),i.jsx(Wc,{title:"Setup complete",subtitle:"You're ready to use Crewly."})]}),A&&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:G1(A)})," ",i.jsx(ct,{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(ra,{className:"h-4 w-4 text-emerald-400","aria-label":"Done"}):i.jsx(_2,{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:fM[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 → Harness.'}),i.jsx("div",{className:"text-center",children:i.jsx(de,{type:"button",size:"default",onClick:()=>t(P3,{replace:!0}),children:"Open Crewly"})})]})}}};return i.jsx(HY,{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!==Yn.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,"/",Ak.length," · ",Ak[f]]}),i.jsx("div",{className:"mb-6 hidden overflow-x-auto sm:block",children:i.jsx(bIe,{steps:[...Ak],currentStep:f})}),i.jsx(ot,{padding:"none",className:"p-4 sm:p-6",children:K()})]})})};function WIe(){const{id:t}=vh();return i.jsx(Fb,{to:`/tasks/${t??""}`,replace:!0})}function VIe(){return i.jsx(XQ,{children:i.jsx(nne,{children:i.jsx(oee,{children:i.jsxs(zY,{children:[i.jsx(gIe,{}),i.jsxs(JX,{children:[i.jsx(vIe,{}),i.jsxs(HX,{children:[i.jsx(An,{path:"/auth/callback",element:i.jsx(Eje,{})}),i.jsx(An,{path:"/auth",element:i.jsx(Tje,{})}),i.jsx(An,{path:"/setup",element:i.jsx(GIe,{})}),i.jsxs(An,{path:"/",element:i.jsx(rne,{}),children:[i.jsx(An,{index:!0,element:i.jsx(vne,{})}),i.jsx(An,{path:"projects",element:i.jsx(Sne,{})}),i.jsx(An,{path:"projects/:id",element:i.jsx(Ese,{})}),i.jsx(An,{path:"teams",element:i.jsx(Yse,{})}),i.jsx(An,{path:"teams/:id",element:i.jsx(Pre,{})}),i.jsx(An,{path:"assignments",element:i.jsx(zre,{})}),i.jsx(An,{path:"scheduled-checkins",element:i.jsx(qre,{})}),i.jsx(An,{path:"triggers",element:i.jsx(aie,{})}),i.jsx(An,{path:"factory",element:i.jsx(Bye,{})}),i.jsx(An,{path:"connections",element:i.jsx(hSe,{})}),i.jsx(An,{path:"browser",element:i.jsx(MSe,{})}),i.jsx(An,{path:"marketplace",element:i.jsx(HSe,{})}),i.jsx(An,{path:"marketplace/:id",element:i.jsx(VSe,{})}),i.jsx(An,{path:"wiki",element:i.jsx(j2e,{})}),i.jsx(An,{path:"security",element:i.jsx(TV,{})}),i.jsx(An,{path:"monitoring/costs",element:i.jsx(l5,{})}),i.jsx(An,{path:"usage",element:i.jsx(l5,{})}),i.jsx(An,{path:"settings",element:i.jsx(Bve,{})}),i.jsx(An,{path:"pricing",element:i.jsx(jje,{})}),i.jsx(An,{path:"cloud",element:i.jsx(Xje,{})}),i.jsx(An,{path:"tasks",element:i.jsx(uIe,{})}),i.jsx(An,{path:"tasks/:id",element:i.jsx(GV,{})}),i.jsx(An,{path:"requests",element:i.jsx(Fb,{to:"/tasks",replace:!0})}),i.jsx(An,{path:"requests/:id",element:i.jsx(WIe,{})}),i.jsx(An,{path:"missions",element:i.jsx(jV,{})}),i.jsx(An,{path:"missions/:id",element:i.jsx(IV,{})}),i.jsx(An,{path:"tickets",element:i.jsx(FRe,{})}),i.jsx(An,{path:"workitems",element:i.jsx(zV,{})}),i.jsx(An,{path:"workitems/:id",element:i.jsx(HV,{})}),i.jsx(An,{path:"team-chat",element:i.jsx(f_e,{})}),i.jsx(An,{path:"chat",element:i.jsx(Fb,{to:"/team-chat",replace:!0})}),i.jsx(An,{path:"agents",element:i.jsx(Fb,{to:"/team-chat",replace:!0})})]})]})]})]})})})})}fte();UA.createRoot(document.getElementById("root")).render(i.jsx(Mn.StrictMode,{children:i.jsx(VIe,{})}));
4951
+ //# sourceMappingURL=index-64c8a616.js.map