crewly 1.20.250 → 1.20.252

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 (176) hide show
  1. package/config/skills/agent/core/app-comments/SKILL.md +11 -1
  2. package/config/skills/agent/core/app-data/SKILL.md +65 -3
  3. package/config/skills/agent/core/app-data/execute.sh +51 -3
  4. package/config/skills/agent/core/app-data/execute.test.sh +42 -0
  5. package/config/skills/agent/core/complete-task/SKILL.md +5 -1
  6. package/config/skills/agent/core/complete-task/execute.sh +30 -15
  7. package/config/skills/agent/core/complete-task/execute.test.sh +45 -1
  8. package/config/skills/agent/core/publish-app/SKILL.md +5 -1
  9. package/config/skills/agent/core/publish-app/execute.sh +26 -3
  10. package/config/skills/agent/core/publish-app/execute.test.sh +18 -0
  11. package/dist/backend/backend/src/constants.d.ts +66 -0
  12. package/dist/backend/backend/src/constants.d.ts.map +1 -1
  13. package/dist/backend/backend/src/constants.js +66 -0
  14. package/dist/backend/backend/src/constants.js.map +1 -1
  15. package/dist/backend/backend/src/controllers/apps/apps.controller.d.ts +17 -0
  16. package/dist/backend/backend/src/controllers/apps/apps.controller.d.ts.map +1 -1
  17. package/dist/backend/backend/src/controllers/apps/apps.controller.js +31 -0
  18. package/dist/backend/backend/src/controllers/apps/apps.controller.js.map +1 -1
  19. package/dist/backend/backend/src/controllers/apps/apps.routes.d.ts +7 -0
  20. package/dist/backend/backend/src/controllers/apps/apps.routes.d.ts.map +1 -1
  21. package/dist/backend/backend/src/controllers/apps/apps.routes.js +29 -2
  22. package/dist/backend/backend/src/controllers/apps/apps.routes.js.map +1 -1
  23. package/dist/backend/backend/src/controllers/team/team.controller.d.ts.map +1 -1
  24. package/dist/backend/backend/src/controllers/team/team.controller.js +43 -4
  25. package/dist/backend/backend/src/controllers/team/team.controller.js.map +1 -1
  26. package/dist/backend/backend/src/index.d.ts.map +1 -1
  27. package/dist/backend/backend/src/index.js +13 -0
  28. package/dist/backend/backend/src/index.js.map +1 -1
  29. package/dist/backend/backend/src/services/agent/agent-registration.service.js +2 -2
  30. package/dist/backend/backend/src/services/agent/agent-registration.service.js.map +1 -1
  31. package/dist/backend/backend/src/services/agent/resource-mode.service.d.ts +13 -0
  32. package/dist/backend/backend/src/services/agent/resource-mode.service.d.ts.map +1 -1
  33. package/dist/backend/backend/src/services/agent/resource-mode.service.js +36 -0
  34. package/dist/backend/backend/src/services/agent/resource-mode.service.js.map +1 -1
  35. package/dist/backend/backend/src/services/ai/prompt-modules/skills-reference.module.js +1 -1
  36. package/dist/backend/backend/src/services/ai/prompt-modules/skills-reference.module.js.map +1 -1
  37. package/dist/backend/backend/src/services/apps/app-collaborators.service.d.ts +103 -0
  38. package/dist/backend/backend/src/services/apps/app-collaborators.service.d.ts.map +1 -0
  39. package/dist/backend/backend/src/services/apps/app-collaborators.service.js +161 -0
  40. package/dist/backend/backend/src/services/apps/app-collaborators.service.js.map +1 -0
  41. package/dist/backend/backend/src/services/apps/app-comment-room.service.d.ts +149 -0
  42. package/dist/backend/backend/src/services/apps/app-comment-room.service.d.ts.map +1 -0
  43. package/dist/backend/backend/src/services/apps/app-comment-room.service.js +316 -0
  44. package/dist/backend/backend/src/services/apps/app-comment-room.service.js.map +1 -0
  45. package/dist/backend/backend/src/services/apps/app-comments-slack.service.d.ts +38 -1
  46. package/dist/backend/backend/src/services/apps/app-comments-slack.service.d.ts.map +1 -1
  47. package/dist/backend/backend/src/services/apps/app-comments-slack.service.js +58 -3
  48. package/dist/backend/backend/src/services/apps/app-comments-slack.service.js.map +1 -1
  49. package/dist/backend/backend/src/services/apps/app-roster.service.d.ts +37 -1
  50. package/dist/backend/backend/src/services/apps/app-roster.service.d.ts.map +1 -1
  51. package/dist/backend/backend/src/services/apps/app-roster.service.js +62 -7
  52. package/dist/backend/backend/src/services/apps/app-roster.service.js.map +1 -1
  53. package/dist/backend/backend/src/services/apps/app-wake-message.d.ts +6 -0
  54. package/dist/backend/backend/src/services/apps/app-wake-message.d.ts.map +1 -1
  55. package/dist/backend/backend/src/services/apps/app-wake-message.js +12 -10
  56. package/dist/backend/backend/src/services/apps/app-wake-message.js.map +1 -1
  57. package/dist/backend/backend/src/services/apps/app-wake.service.d.ts +30 -0
  58. package/dist/backend/backend/src/services/apps/app-wake.service.d.ts.map +1 -1
  59. package/dist/backend/backend/src/services/apps/app-wake.service.js +90 -16
  60. package/dist/backend/backend/src/services/apps/app-wake.service.js.map +1 -1
  61. package/dist/backend/backend/src/services/apps/apps-cloud.client.d.ts +6 -0
  62. package/dist/backend/backend/src/services/apps/apps-cloud.client.d.ts.map +1 -1
  63. package/dist/backend/backend/src/services/apps/apps-cloud.client.js +5 -4
  64. package/dist/backend/backend/src/services/apps/apps-cloud.client.js.map +1 -1
  65. package/dist/backend/backend/src/services/apps/apps.service.d.ts +115 -2
  66. package/dist/backend/backend/src/services/apps/apps.service.d.ts.map +1 -1
  67. package/dist/backend/backend/src/services/apps/apps.service.js +181 -9
  68. package/dist/backend/backend/src/services/apps/apps.service.js.map +1 -1
  69. package/dist/backend/backend/src/services/apps/apps.wiring.d.ts +57 -1
  70. package/dist/backend/backend/src/services/apps/apps.wiring.d.ts.map +1 -1
  71. package/dist/backend/backend/src/services/apps/apps.wiring.js +233 -4
  72. package/dist/backend/backend/src/services/apps/apps.wiring.js.map +1 -1
  73. package/dist/backend/backend/src/services/chat-v2/chat-v2.service.d.ts +1 -1
  74. package/dist/backend/backend/src/services/chat-v2/chat-v2.service.d.ts.map +1 -1
  75. package/dist/backend/backend/src/services/chat-v2/chat-v2.service.js +3 -0
  76. package/dist/backend/backend/src/services/chat-v2/chat-v2.service.js.map +1 -1
  77. package/dist/backend/backend/src/services/decisions/decision.service.d.ts +2 -0
  78. package/dist/backend/backend/src/services/decisions/decision.service.d.ts.map +1 -1
  79. package/dist/backend/backend/src/services/decisions/decision.service.js +1 -0
  80. package/dist/backend/backend/src/services/decisions/decision.service.js.map +1 -1
  81. package/dist/backend/backend/src/services/messaging/sub-agent-message-queue.service.d.ts +24 -1
  82. package/dist/backend/backend/src/services/messaging/sub-agent-message-queue.service.d.ts.map +1 -1
  83. package/dist/backend/backend/src/services/messaging/sub-agent-message-queue.service.js +44 -1
  84. package/dist/backend/backend/src/services/messaging/sub-agent-message-queue.service.js.map +1 -1
  85. package/dist/backend/backend/src/services/orchestrator/commitment-approval-guard.d.ts +48 -0
  86. package/dist/backend/backend/src/services/orchestrator/commitment-approval-guard.d.ts.map +1 -1
  87. package/dist/backend/backend/src/services/orchestrator/commitment-approval-guard.js +46 -0
  88. package/dist/backend/backend/src/services/orchestrator/commitment-approval-guard.js.map +1 -1
  89. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-decision.d.ts +43 -1
  90. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-decision.d.ts.map +1 -1
  91. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-decision.js +34 -0
  92. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-decision.js.map +1 -1
  93. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-stats.d.ts.map +1 -1
  94. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-stats.js +1 -0
  95. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot-stats.js.map +1 -1
  96. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot.service.d.ts.map +1 -1
  97. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot.service.js +23 -7
  98. package/dist/backend/backend/src/services/project-tickets/ticket-autopilot.service.js.map +1 -1
  99. package/dist/backend/backend/src/services/reconciler/reconcile-rules.d.ts +5 -0
  100. package/dist/backend/backend/src/services/reconciler/reconcile-rules.d.ts.map +1 -1
  101. package/dist/backend/backend/src/services/reconciler/reconcile-rules.js.map +1 -1
  102. package/dist/backend/backend/src/services/reconciler/reconciler-data-provider.d.ts +18 -2
  103. package/dist/backend/backend/src/services/reconciler/reconciler-data-provider.d.ts.map +1 -1
  104. package/dist/backend/backend/src/services/reconciler/reconciler-data-provider.js +67 -8
  105. package/dist/backend/backend/src/services/reconciler/reconciler-data-provider.js.map +1 -1
  106. package/dist/backend/backend/src/services/reconciler/reconciler.service.d.ts +117 -3
  107. package/dist/backend/backend/src/services/reconciler/reconciler.service.d.ts.map +1 -1
  108. package/dist/backend/backend/src/services/reconciler/reconciler.service.js +304 -19
  109. package/dist/backend/backend/src/services/reconciler/reconciler.service.js.map +1 -1
  110. package/dist/backend/backend/src/services/reconciler/stalled-agent-recovery.d.ts +66 -0
  111. package/dist/backend/backend/src/services/reconciler/stalled-agent-recovery.d.ts.map +1 -0
  112. package/dist/backend/backend/src/services/reconciler/stalled-agent-recovery.js +107 -0
  113. package/dist/backend/backend/src/services/reconciler/stalled-agent-recovery.js.map +1 -0
  114. package/dist/backend/backend/src/services/trace/trace-metrics.d.ts.map +1 -1
  115. package/dist/backend/backend/src/services/trace/trace-metrics.js +2 -1
  116. package/dist/backend/backend/src/services/trace/trace-metrics.js.map +1 -1
  117. package/dist/backend/backend/src/services/trace/trace.types.d.ts +1 -1
  118. package/dist/backend/backend/src/services/trace/trace.types.d.ts.map +1 -1
  119. package/dist/backend/backend/src/services/trace/trace.types.js +2 -0
  120. package/dist/backend/backend/src/services/trace/trace.types.js.map +1 -1
  121. package/dist/backend/backend/src/services/v3/workitem-dispatch.subscriber.d.ts +15 -0
  122. package/dist/backend/backend/src/services/v3/workitem-dispatch.subscriber.d.ts.map +1 -1
  123. package/dist/backend/backend/src/services/v3/workitem-dispatch.subscriber.js +47 -0
  124. package/dist/backend/backend/src/services/v3/workitem-dispatch.subscriber.js.map +1 -1
  125. package/dist/backend/backend/src/types/decision.types.d.ts +27 -2
  126. package/dist/backend/backend/src/types/decision.types.d.ts.map +1 -1
  127. package/dist/backend/backend/src/types/v2/index.d.ts +1 -1
  128. package/dist/backend/backend/src/types/v2/index.d.ts.map +1 -1
  129. package/dist/backend/backend/src/types/v2/index.js.map +1 -1
  130. package/dist/backend/backend/src/types/v2/reconcile.types.d.ts +20 -0
  131. package/dist/backend/backend/src/types/v2/reconcile.types.d.ts.map +1 -1
  132. package/dist/backend/backend/src/types/v2/reconcile.types.js.map +1 -1
  133. package/dist/backend/build-info.json +2 -2
  134. package/dist/cli/backend/src/constants.d.ts +66 -0
  135. package/dist/cli/backend/src/constants.d.ts.map +1 -1
  136. package/dist/cli/backend/src/constants.js +66 -0
  137. package/dist/cli/backend/src/constants.js.map +1 -1
  138. package/dist/cli/backend/src/services/agent/agent-registration.service.js +2 -2
  139. package/dist/cli/backend/src/services/agent/agent-registration.service.js.map +1 -1
  140. package/dist/cli/backend/src/services/agent/resource-mode.service.d.ts +13 -0
  141. package/dist/cli/backend/src/services/agent/resource-mode.service.d.ts.map +1 -1
  142. package/dist/cli/backend/src/services/agent/resource-mode.service.js +36 -0
  143. package/dist/cli/backend/src/services/agent/resource-mode.service.js.map +1 -1
  144. package/dist/cli/backend/src/services/ai/prompt-modules/skills-reference.module.js +1 -1
  145. package/dist/cli/backend/src/services/ai/prompt-modules/skills-reference.module.js.map +1 -1
  146. package/dist/cli/backend/src/services/chat-v2/chat-v2.service.d.ts +1 -1
  147. package/dist/cli/backend/src/services/chat-v2/chat-v2.service.d.ts.map +1 -1
  148. package/dist/cli/backend/src/services/chat-v2/chat-v2.service.js +3 -0
  149. package/dist/cli/backend/src/services/chat-v2/chat-v2.service.js.map +1 -1
  150. package/dist/cli/backend/src/services/decisions/decision.service.d.ts +2 -0
  151. package/dist/cli/backend/src/services/decisions/decision.service.d.ts.map +1 -1
  152. package/dist/cli/backend/src/services/decisions/decision.service.js +1 -0
  153. package/dist/cli/backend/src/services/decisions/decision.service.js.map +1 -1
  154. package/dist/cli/backend/src/services/messaging/sub-agent-message-queue.service.d.ts +24 -1
  155. package/dist/cli/backend/src/services/messaging/sub-agent-message-queue.service.d.ts.map +1 -1
  156. package/dist/cli/backend/src/services/messaging/sub-agent-message-queue.service.js +44 -1
  157. package/dist/cli/backend/src/services/messaging/sub-agent-message-queue.service.js.map +1 -1
  158. package/dist/cli/backend/src/services/orchestrator/commitment-approval-guard.d.ts +48 -0
  159. package/dist/cli/backend/src/services/orchestrator/commitment-approval-guard.d.ts.map +1 -1
  160. package/dist/cli/backend/src/services/orchestrator/commitment-approval-guard.js +46 -0
  161. package/dist/cli/backend/src/services/orchestrator/commitment-approval-guard.js.map +1 -1
  162. package/dist/cli/backend/src/services/trace/trace.types.d.ts +1 -1
  163. package/dist/cli/backend/src/services/trace/trace.types.d.ts.map +1 -1
  164. package/dist/cli/backend/src/services/trace/trace.types.js +2 -0
  165. package/dist/cli/backend/src/services/trace/trace.types.js.map +1 -1
  166. package/dist/cli/backend/src/types/decision.types.d.ts +27 -2
  167. package/dist/cli/backend/src/types/decision.types.d.ts.map +1 -1
  168. package/dist/cli/backend/src/types/v2/index.d.ts +1 -1
  169. package/dist/cli/backend/src/types/v2/index.d.ts.map +1 -1
  170. package/dist/cli/backend/src/types/v2/index.js.map +1 -1
  171. package/dist/cli/backend/src/types/v2/reconcile.types.d.ts +20 -0
  172. package/dist/cli/backend/src/types/v2/reconcile.types.d.ts.map +1 -1
  173. package/dist/cli/backend/src/types/v2/reconcile.types.js.map +1 -1
  174. package/frontend/dist/assets/{index-2db17f1e.js → index-83188f0b.js} +2 -2
  175. package/frontend/dist/index.html +1 -1
  176. package/package.json +1 -1
@@ -162,7 +162,7 @@ You are a QA Tester AI agent responsible for:
162
162
  `};_.useEffect(()=>{t&&p()},[t]);const p=async()=>{if(t){d(!0),h(null);try{const b=await fetch(`/api/projects/files?projectPath=${encodeURIComponent(t)}&type=crewly-md`);if(b.ok){const S=await b.json();a(S.files||[])}else h("Failed to load available files")}catch(b){h("Error loading files: "+b.message)}finally{d(!1)}}},x=async b=>{d(!0),h(null);try{const S=await fetch(`/api/projects/file-content?projectPath=${encodeURIComponent(t||"")}&filePath=${encodeURIComponent(b)}`);if(S.ok){const E=await S.json();s({name:b.split("/").pop()||b,path:b,content:E.content,modified:!1})}else h("Failed to load file")}catch(S){h("Error loading file: "+S.message)}finally{d(!1)}},v=b=>{const S=b;s({name:S,path:`.crewly/${S}`,content:f[b],modified:!0})},m=async()=>{if(!(!n||!t)){d(!0),h(null);try{(await fetch("/api/projects/save-file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectPath:t,filePath:n.path,content:n.content})})).ok?(s({...n,modified:!1}),await p()):h("Failed to save file")}catch(b){h("Error saving file: "+b.message)}finally{d(!1)}}},g=b=>{n&&s({...n,content:b,modified:!0})},y=b=>{const S=b.replace(/^# (.*)/gm,"<h1>$1</h1>").replace(/^## (.*)/gm,"<h2>$1</h2>").replace(/^### (.*)/gm,"<h3>$1</h3>").replace(/\*\*(.*?)\*\*/g,"<strong>$1</strong>").replace(/\*(.*?)\*/g,"<em>$1</em>").replace(/`(.*?)`/g,"<code>$1</code>").replace(/- \[ \] (.*)/g,"☐ $1").replace(/- \[x\] (.*)/gi,"☑ $1").replace(/^- (.*)/gm,"• $1").replace(/\n/g,"<br>");return Wle.sanitize(S)};return i.jsx("div",{className:"markdown-editor-overlay",children:i.jsxs("div",{className:"markdown-editor",children:[i.jsxs("div",{className:"markdown-editor-header",children:[i.jsxs("div",{className:"header-left",children:[i.jsx("h2",{children:"Markdown Editor"}),n&&i.jsxs("span",{className:"file-info",children:[n.name,n.modified&&i.jsx("span",{className:"modified-indicator",children:"●"})]})]}),i.jsxs("div",{className:"header-right",children:[n&&i.jsxs(i.Fragment,{children:[i.jsx(ue,{variant:"outline",size:"sm",onClick:()=>l(!o),title:o?"Edit Mode":"Preview Mode",icon:o?zH:aM}),i.jsx(ue,{variant:"primary",size:"sm",onClick:m,disabled:!n.modified||c,title:"Save File",icon:Kd})]}),i.jsx(Zt,{"aria-label":"Close",variant:"ghost",icon:ys,onClick:e})]})]}),u&&i.jsx("div",{className:"error-message",children:u}),i.jsx("div",{className:"markdown-editor-content",children:n?i.jsx("div",{className:"editor-pane",children:o?i.jsx("div",{className:"markdown-preview",dangerouslySetInnerHTML:{__html:y(n.content)}}):i.jsx("textarea",{className:"markdown-textarea",value:n.content,onChange:b=>g(b.target.value),placeholder:"Enter your markdown content here...",spellCheck:!1})}):i.jsxs("div",{className:"file-browser",children:[i.jsxs("div",{className:"file-section",children:[i.jsxs("h3",{children:[i.jsx(qo,{size:16})," Available Files"]}),c?i.jsx(zt,{size:"sm",text:"Loading files...",className:"loading py-4"}):r.length>0?i.jsx("ul",{className:"file-list",children:r.map((b,S)=>i.jsx("li",{children:i.jsxs("button",{onClick:()=>x(b),className:"file-item",children:[i.jsx(Ck,{size:14}),b]})},S))}):i.jsx("p",{className:"no-files",children:"No .crewly markdown files found"})]}),i.jsxs("div",{className:"file-section",children:[i.jsxs("h3",{children:[i.jsx(Ck,{size:16})," Create New File"]}),i.jsx("div",{className:"template-list",children:Object.keys(f).map(b=>i.jsxs("button",{onClick:()=>v(b),className:"template-item",children:[i.jsx(Ck,{size:14}),b]},b))})]})]})}),n&&i.jsxs("div",{className:"editor-footer",children:[i.jsx("span",{className:"file-path",children:n.path}),i.jsxs("span",{className:"editor-mode",children:[o?"Preview":"Edit"," Mode"]})]})]})})},Kk=({icon:t,title:e,description:n,action:s,testId:r})=>i.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-border-soft py-3.5 sm:flex-nowrap","data-testid":r,children:[i.jsx(t,{className:"h-5 w-5 shrink-0 text-text-3","aria-hidden":"true"}),i.jsxs("div",{className:"min-w-0 flex-1 basis-56",children:[i.jsx("h5",{className:"text-[15px] font-semibold leading-[22px] text-text",children:e}),i.jsx("p",{className:"text-[13px] leading-[18px] text-text-2",children:n})]}),i.jsx("div",{className:"shrink-0",children:s})]}),Kle=({project:t,onAddGoal:e,onEditGoal:n,onAddUserJourney:s,onEditUserJourney:r,availableTeams:a,onShowTab:o,onOpenChat:l})=>{const[c,d]=_.useState({mdFileCount:0,taskCount:0,hasProjectMd:!1,hasUserJourneyMd:!1,hasInitialGoalMd:!1,hasInitialUserJourneyMd:!1}),[u,h]=_.useState(!0),[f,p]=_.useState({progressPercent:0,tasksCompleted:0,tasksTotal:0,assignedTeams:0});_.useEffect(()=>{x()},[t.id]);const x=async()=>{try{h(!0);const b=await fetch(`/api/projects/${t.id}/stats`);if(b.ok){const S=await b.json();S.success&&d(S.data)}try{const{tickets:S}=await KR(t.id),E=S.filter(M=>M.status!=="cancelled"),k=E.length,T=E.filter(M=>M.status==="done").length,A=k?Math.round(T/k*100):0,N=(a||[]).filter(M=>{var L,j;return((L=M.projectIds)==null?void 0:L.includes(t.id))||((j=M.projectIds)==null?void 0:j.includes(t.name))}).length;p({progressPercent:A,tasksCompleted:T,tasksTotal:k,assignedTeams:N})}catch(S){console.warn("Failed to compute prototype metrics",S)}}catch(b){console.error("Error loading project stats:",b)}finally{h(!1)}},v="font-semibold text-primary-text hover:underline underline-offset-2",m=`${f.tasksCompleted} of ${f.tasksTotal} task${f.tasksTotal===1?"":"s"}`,g=`${f.assignedTeams} team${f.assignedTeams===1?"":"s"}`,y=l??(()=>window.location.assign(Yt.chat));return i.jsxs("div",{className:"flex flex-col gap-8","data-testid":"project-detail-view",children:[i.jsx("section",{"aria-label":"Project progress",children:u?i.jsx("p",{className:"text-[15px] text-text-2",children:"Loading project metrics..."}):i.jsxs("p",{className:"text-[15px] leading-[22px] text-text-2","data-testid":"project-metrics",children:[i.jsxs("span",{className:"font-semibold text-text",children:[f.progressPercent,"% done"]}),i.jsx("span",{className:"text-text-3",children:" — "}),o?i.jsx("button",{type:"button",className:v,onClick:()=>o("tasks"),children:m}):i.jsx("span",{children:m}),i.jsx("span",{className:"text-text-3",children:" · "}),o?i.jsx("button",{type:"button",className:v,onClick:()=>o("teams"),children:g}):i.jsx("span",{children:g})]})}),i.jsxs("section",{"aria-labelledby":"project-spec-h",children:[i.jsx("h4",{id:"project-spec-h",className:"mb-1 text-[13px] font-semibold text-text-2",children:"Specification"}),i.jsx(Kk,{icon:El,title:"Project Goal",description:"Define project objectives and success criteria",testId:"spec-goal",action:c.hasInitialGoalMd?i.jsx(ue,{variant:"secondary",size:"sm",icon:El,onClick:n,children:"Edit"}):i.jsx(ue,{variant:"secondary",size:"sm",onClick:e,children:"Add Goal"})}),i.jsx(Kk,{icon:hee,title:"User Journey",description:"Map user interactions and experience flows",testId:"spec-journey",action:c.hasInitialUserJourneyMd?i.jsx(ue,{variant:"secondary",size:"sm",icon:El,onClick:r,children:"Edit"}):i.jsx(ue,{variant:"secondary",size:"sm",onClick:s,children:"Add User Journey"})}),i.jsx(Kk,{icon:iR,title:"Generate Project Tasks",description:"Talk it through with the orchestrator; the tasks land on this project's board",testId:"spec-generate",action:i.jsx(ue,{variant:"secondary",size:"sm",onClick:y,children:"Open Chat to Generate Tasks"})})]})]})},l$="/api/tickets",qle=15e3,Xle=300,Yle=24*60*60*1e3,sp={idea:"Ideas",todo:"To do",in_progress:"In progress",blocked:"Blocked",to_review:"To review",done:"Done",cancelled:"Cancelled"},c$={issue:"Issue",feature:"Feature",idea:"Idea",question:"Question"},d$=["issue","feature","idea","question"],Jle=[{value:"urgent",label:"P0"},{value:"high",label:"P1"},{value:"normal",label:"P2"},{value:"low",label:"P3"}],Zle={owner:"Me",decompose:"Breakdown",reject:"Sent back",agent:"Agent"},qk={auto:"Auto",judgment:"Manual"},Qle={"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"},oB={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"},pn={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"},ui={NEW_TICKET:"New ticket",NEEDS_YOU:"Needs you",SHOW:"Show",HIDE:"Hide",SHOW_LESS:"Show less",FILTER_PROJECT:"Project",FILTER_TYPE:"Type",FILTER_INCLUDE:"Include",CANCELLED:"Cancelled",NO_PROJECT:"No project (your asks)",EMPTY_PROJECT_TITLE:"No tickets in this project yet",EMPTY_PROJECT_DESC:"Create one, or ask a team member in chat. Team members pick up Ready tickets on their own.",NO_MATCH:"No tickets match the current filters.",PROJECT_HINT:"Tickets live in .crewly/tickets/ in the project and are tracked in git. Team members pick up Ready tickets on their own.",TYPE_HIDES_PROJECT:"Type applies to your asks only, so project tickets are hidden while it is set."},lB={to_review:"Nothing to review",in_progress:"Nothing in progress",todo:"Nothing to do",blocked:"Nothing blocked",idea:"No ideas",done:"Nothing done yet",cancelled:"Nothing cancelled"};class qR extends Error{constructor(n,s,r){super(n);Fn(this,"status");Fn(this,"code");this.name="TicketApiError",this.status=s,this.code=r}}function ece(t){return t instanceof qR}async function Jh(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 qR(s.error||s.message||`HTTP ${n.status}`,n.status,s.code);return s.data}function fy(t,e){return{method:t,headers:{"Content-Type":"application/json"},...e!==void 0?{body:JSON.stringify(e)}:{}}}function Lm(t,e=""){return`${l$}/${encodeURIComponent(t)}${e}`}function tce(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 cB(t={}){const e=await Jh(`${l$}${tce(t)}`);return{tickets:(e==null?void 0:e.tickets)??[],columns:(e==null?void 0:e.columns)??{}}}function nce(t){return Jh(Lm(t))}function sce(t){return Jh(Lm(t,"/verify"),fy("POST"))}function rce(t,e){const n=e.trim();return n?Jh(Lm(t,"/reject"),fy("POST",{reason:n})):Promise.reject(new qR("A reason is required",400,"invalid"))}function ice(t){return Jh(Lm(t,"/dismiss"),fy("POST"))}function ace(t,e){return Jh(Lm(t,"/acceptance"),fy("PUT",{items:e}))}function oce(t,e){return Jh(Lm(t),fy("PATCH",e))}function lce(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)/Yle))}function u$(t,e=Date.now()){const n=lce(t,e);return n===null?null:n<=0?pn.AUTO_ACCEPT_SOON:`${pn.AUTO_ACCEPT_IN_DAYS} ${n} ${n===1?"day":"days"}`}function cce(t){if(!t)return null;const e=Qle[t.channel]??t.channel,n=t.authorName||t.author;return n?`${e} · ${n}`:e}function dB(t){if(!t)return"";const e=Date.parse(t);return Number.isNaN(e)?t:new Date(e).toLocaleString()}function uB(t){return(t??[]).map(e=>({text:e.text,...e.check?{check:e.check}:{}}))}function nw(t){return ece(t)&&t.code&&oB[t.code]?oB[t.code]:t instanceof Error&&t.message?t.message:String(t)}const hB="judgment",dce=({acceptance:t,onSave:e,disabled:n=!1})=>{const[s,r]=_.useState(""),[a,o]=_.useState(hB),[l,c]=_.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=uB(t).filter((v,m)=>m!==p);await u(x)},f=async p=>{p.preventDefault();const x=s.trim();if(!x)return;await u([...uB(t),{text:x,check:a}])&&(r(""),o(hB))};return i.jsxs("div",{"data-testid":"ticket-acceptance",children:[t.length===0?i.jsx("p",{className:"text-sm text-text-secondary-dark",children:pn.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(mn,{size:"sm",variant:p.source==="reject"?"error":"default",children:Zle[p.source??"owner"]}),i.jsx(mn,{size:"sm",variant:p.check==="auto"?"info":"default",children:qk[p.check??"judgment"]}),p.selfCheck&&i.jsx(mn,{size:"sm",variant:p.selfCheck==="pass"?"success":"error",children:p.selfCheck==="pass"?pn.SELF_CHECK_PASS:pn.SELF_CHECK_FAIL})]}),p.evidence&&i.jsx("p",{className:"mt-1 text-xs text-text-secondary-dark break-words",children:p.evidence})]}),i.jsx(Zt,{icon:Qs,variant:"ghost","aria-label":`${pn.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(Dt,{value:s,onChange:p=>r(p.target.value),placeholder:pn.ACCEPTANCE_ADD_PLACEHOLDER,"aria-label":pn.ACCEPTANCE_ADD_PLACEHOLDER,disabled:d})}),i.jsx("div",{className:"sm:w-28",children:i.jsxs(vn,{value:a,onChange:p=>o(p.target.value),"aria-label":pn.ACCEPTANCE_CHECK_ARIA,disabled:d,children:[i.jsx("option",{value:"judgment",children:qk.judgment}),i.jsx("option",{value:"auto",children:qk.auto})]})}),i.jsx(ue,{type:"submit",variant:"secondary",icon:qn,disabled:d||!s.trim(),children:pn.ACCEPTANCE_ADD})]})]})},uce=new Set(["done","cancelled"]),Kv=({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]}),hce=({ticketId:t,onClose:e,onChanged:n,now:s})=>{const[r,a]=_.useState(null),[o,l]=_.useState(null),[c,d]=_.useState(null),[u,h]=_.useState(null),[f,p]=_.useState(""),[x,v]=_.useState(!1),[m,g]=_.useState(""),[y,b]=_.useState(null),S=_.useCallback(async P=>{try{const B=await nce(P);a(B),p(B.board.title),l(null)}catch(B){l(nw(B))}},[]);_.useEffect(()=>{a(null),l(null),d(null),v(!1),g(""),b(null),t&&S(t)},[t,S]);const E=async(P,B,I=!1)=>{if(!t)return!1;h(P),d(null);try{return await B(),n(),I?e():await S(t),!0}catch(F){return d(nw(F)),!1}finally{h(null)}},k=P=>{t&&E("patch",()=>oce(t,P))},T=async P=>{if(!t)return;if(!await E("acceptance",()=>ace(t,P)))throw new Error("acceptance save failed")},A=()=>{if(!t)return;const P=m.trim();if(!P){b(pn.REJECT_REASON_REQUIRED);return}b(null),E("reject",()=>rce(t,P)).then(B=>{B&&(v(!1),g(""))})},N=(r==null?void 0:r.board)??null,M=t!==null,L=N!==null&&!uce.has(N.column),j=(N==null?void 0:N.column)==="to_review",D=N!==null&&f.trim()!==""&&f.trim()!==N.title,U=(r==null?void 0:r.ticket.discussion)??[],$=(N==null?void 0:N.description)||(r==null?void 0:r.ticket.description)||"",G=j?u$(N==null?void 0:N.autoAcceptAt,s):null,K=N&&L?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:pn.REJECT_REASON_LABEL}),i.jsx(er,{id:"ticket-reject-reason",rows:3,value:m,error:y!==null,placeholder:pn.REJECT_REASON_PLACEHOLDER,onChange:P=>{g(P.target.value),y&&b(null)}}),y&&i.jsx("p",{className:"text-xs text-red-400",role:"alert",children:y}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(ue,{variant:"ghost",onClick:()=>v(!1),disabled:u!==null,children:pn.CANCEL}),i.jsx(ue,{variant:"warning",icon:QD,onClick:A,loading:u==="reject",children:pn.REJECT_CONFIRM})]})]}):i.jsxs("div",{className:"flex w-full flex-wrap items-center justify-end gap-2",children:[i.jsx(ue,{variant:"danger-ghost",icon:ys,onClick:()=>void E("dismiss",()=>ice(t),!0),loading:u==="dismiss",disabled:u!==null&&u!=="dismiss",children:pn.DISMISS}),j&&i.jsx(ue,{variant:"warning",icon:QD,onClick:()=>v(!0),disabled:u!==null,children:pn.REJECT}),i.jsx(ue,{variant:"success",icon:rs,onClick:()=>void E("verify",()=>sce(t),!0),loading:u==="verify",disabled:u!==null&&u!=="verify",children:pn.VERIFY})]}):void 0;return i.jsxs(a9,{isOpen:M,onClose:e,size:"lg",title:(N==null?void 0:N.tkt)??(N==null?void 0:N.title)??pn.DETAIL_LOADING,subtitle:N?sp[N.column]??N.column:void 0,footer:K,"data-testid":"ticket-detail-drawer",children:[!N&&!o&&i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(zt,{})}),o&&i.jsx(Ye,{variant:"error",size:"sm",children:o}),N&&i.jsxs("div",{className:"space-y-6",children:[c&&i.jsx(Ye,{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:pn.TITLE_LABEL}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Dt,{id:"ticket-title",value:f,onChange:P=>p(P.target.value)}),D&&i.jsx(ue,{variant:"secondary",onClick:()=>k({title:f.trim()}),loading:u==="patch",children:pn.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:pn.PRIORITY_LABEL}),i.jsx(vn,{id:"ticket-priority",value:N.priority,disabled:u!==null,onChange:P=>k({priority:P.target.value}),children:Jle.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:pn.KIND_LABEL}),i.jsx(vn,{id:"ticket-kind",value:N.kind,disabled:u!==null,onChange:P=>k({kind:P.target.value}),children:d$.map(P=>i.jsx("option",{value:P,children:c$[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:pn.ORIGIN_LABEL}),i.jsx("dd",{className:"text-text-primary-dark","data-testid":"ticket-origin",children:cce(N.origin)??"—"})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-text-secondary-dark",children:pn.ASSIGNEE_LABEL}),i.jsx("dd",{className:"text-text-primary-dark",children:N.assignee||pn.UNASSIGNED})]})]}),i.jsxs("div",{className:"flex flex-wrap gap-1",children:[(N.rejectCount??0)>0&&i.jsxs(mn,{variant:"error",size:"sm",children:[pn.REJECTED_TIMES," ×",N.rejectCount]}),(N.submitCount??0)>0&&i.jsxs(mn,{size:"sm",children:[pn.SUBMITTED_TIMES," ×",N.submitCount]}),G&&i.jsx(mn,{variant:"primary",size:"sm",children:G})]})]}),$&&i.jsx(Kv,{title:pn.DESCRIPTION_LABEL,children:i.jsx("p",{className:"whitespace-pre-wrap break-words text-sm text-text-primary-dark",children:$})}),i.jsx(Kv,{title:pn.REPLY_LABEL,children:N.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:N.reply.excerpt}),i.jsxs("p",{className:"mt-1 text-xs text-text-secondary-dark",children:[N.reply.by," · ",dB(N.reply.at)]})]}):i.jsx("p",{className:"text-sm text-text-secondary-dark",children:pn.NO_REPLY})}),i.jsx(Kv,{title:pn.ACCEPTANCE_LABEL,children:i.jsx(dce,{acceptance:N.acceptance??[],onSave:T,disabled:u!==null&&u!=="acceptance"})}),i.jsx(Kv,{title:pn.DISCUSSION_LABEL,children:U.length===0?i.jsx("p",{className:"text-sm text-text-secondary-dark",children:pn.NO_DISCUSSION}):i.jsx("ul",{className:"space-y-2","data-testid":"ticket-discussion",children:U.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," · ",dB(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}`))})})]})]})},fce={attention:"text-attention",danger:"text-danger",success:"text-success",primary:"text-primary-text",neutral:"text-text-3"},pce=({card:t,assigneeName:e,onOpen:n})=>{const s=t.priority==="P0"||t.priority==="P1";return i.jsxs("button",{type:"button",onClick:()=>n(t),"aria-label":`${t.ref??""} ${t.fullTitle}`.trim(),title:t.fullTitle,"data-testid":`ticket-card-${t.key}`,className:"block w-full rounded-[0.5rem] bg-surface px-3.5 py-3 text-left transition-colors hover:bg-surface-hover focus:outline-none focus-visible:ring-1 focus-visible:ring-primary",children:[i.jsx("span",{className:"line-clamp-2 break-words text-[15px] font-semibold leading-snug text-text",children:t.title}),i.jsxs("span",{className:"mt-1 block truncate text-[13px] leading-snug text-text-2",children:[s&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:t.priority==="P0"?"font-bold text-danger":"font-bold text-attention","data-testid":"ticket-card-priority",children:t.priority}),i.jsx("span",{className:"text-text-3",children:" · "})]}),i.jsx("span",{className:e?void 0:"text-text-3",children:e??pn.UNASSIGNED}),t.flag&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-3",children:" · "}),i.jsx("span",{className:`font-semibold ${fce[t.flag.tone]??"text-text-2"}`,title:t.flag.title,"data-testid":"ticket-card-flag",children:t.flag.text})]})]})]})},mce=["to_review","in_progress","todo","blocked"],fB=["idea","done"],gce=5,qv="__none__";function XR(t){return t.replace(/^\s*\[[^\]]{1,40}\]\s*/,"").replace(/\s*\[Slack (Image|File):[^\]]*\]?\s*$/i,"").trim()||t}function xce(t){switch(t){case"backlog":case"ready":return"todo";case"in_progress":return"in_progress";case"review":return"to_review";case"done":return"done";case"cancelled":return"cancelled";default:return"todo"}}function yce(t,e){if(t.column==="to_review"){const n=t.rejectCount??0,s=u$(t.autoAcceptAt,e);return s?{text:s,tone:"attention",...n>0?{title:`${pn.REJECT_BADGE} ×${n}`}:{}}:n>0?{text:`${pn.REJECT_BADGE} ×${n}`,tone:"danger"}:null}return t.column==="done"&&t.acceptedBy?t.acceptedBy==="owner"?{text:pn.ACCEPTED_BY_OWNER,tone:"success"}:{text:pn.ACCEPTED_BY_SILENCE,tone:"attention",title:pn.ACCEPTED_BY_SILENCE_HINT}:null}function pB(t,e){return{key:`t:${t.id}`,source:"ticket",ref:t.tkt,title:XR(t.title),fullTitle:t.title,column:t.column,assignee:t.assignee,priority:t.priorityLabel,flag:yce(t,e),projectId:null,projectName:null,updatedAt:t.updatedAt,searchText:"",ticket:t}}function mB(t,e){return{key:`p:${e.id}:${t.id}`,source:"project",ref:t.id,title:XR(t.title),fullTitle:t.title,column:xce(t.status),assignee:t.assignee,priority:t.priority,flag:t.status==="backlog"?{text:"Backlog",tone:"neutral"}:null,projectId:e.id,projectName:e.name,updatedAt:t.updatedAt,searchText:[t.id,t.title,t.description,t.labels.join(" "),t.assignee??""].join(`
163
163
  `).toLowerCase(),projectTicket:t}}const gB={P0:0,P1:1,P2:2,P3:3};function vce(t,e){const n=(gB[t.priority]??9)-(gB[e.priority]??9);return n!==0?n:(Date.parse(e.updatedAt)||0)-(Date.parse(t.updatedAt)||0)}function bce(t){const e={idea:[],todo:[],in_progress:[],blocked:[],to_review:[],done:[],cancelled:[]};for(const n of t)(e[n.column]??(e[n.column]=[])).push(n);for(const n of Object.keys(e))e[n].sort(vce);return e}function _ce(t,e){const n=e.trim().toLowerCase();return!n||t.source==="ticket"?!0:t.searchText.includes(n)}function Sce(t){const e=new Map;for(const n of t)for(const s of n.members??[])s.sessionName&&e.set(s.sessionName,{name:s.name,team:n.name});return e}function Xd(t,e,n=!1){if(!t)return null;if(t===KG)return"Orc";const s=e.get(t);return s?n?`${s.name} · ${s.team}`:s.name:t}function xB(t){return t.split(",").map(e=>e.trim()).filter(Boolean)}function yB(t,e=[]){return t.split(`
164
164
  `).map(n=>n.trim()).filter(Boolean).map(n=>{var r;const s=/^\[( |x|X)\]\s*(.*)$/.exec(n);return s?{text:s[2].trim(),done:s[1].toLowerCase()==="x"}:{text:n,done:((r=e.find(a=>a.text===n))==null?void 0:r.done)??!1}}).filter(n=>n.text.length>0)}function wce(t){return t.map(e=>e.done?`[x] ${e.text}`:e.text).join(`
165
- `)}const Ece="TKT";function Cce(t){const e=new Set;for(const n of t){const s=/^([A-Za-z0-9]+)-\d+$/.exec(n);s&&e.add(s[1].toUpperCase())}return e}function h$(t,e=new Set){const n=/\b([A-Z][A-Z0-9]{0,9})-(\d+)\b/g;for(let s=n.exec(t);s;s=n.exec(t))if(s[1]===Ece||e.has(s[1]))return s[0];return null}const f$=({open:t,ticket:e,projectId:n,projects:s,teams:r,onClose:a,onSaved:o})=>{const l=e===null,[c,d]=_.useState(()=>{var k;return vB(n??((k=s[0])==null?void 0:k.id)??"")}),[u,h]=_.useState(""),[f,p]=_.useState(!1),[x,v]=_.useState(null);_.useEffect(()=>{var k;t&&(v(null),e?(h(e.assignee??""),d({title:e.title,project:n??"",priority:e.priority,status:e.status,labels:e.labels.join(", "),description:e.description,acceptance:wce(e.acceptance),ownerReview:e.ownerReview})):d(vB(n??((k=s[0])==null?void 0:k.id)??"")))},[t,e]),_.useEffect(()=>{t&&l&&!n&&!c.project&&s.length>0&&d(k=>({...k,project:s[0].id}))},[t,l,n,c.project,s]);const m=n??c.project,g=_.useMemo(()=>{const k=r.filter(T=>(T.projectIds??[]).includes(m));return(k.length>0?k:r).flatMap(T=>(T.members??[]).map(A=>({value:A.sessionName,label:`${A.name} (${T.name})`})))},[r,m]),y=async k=>{p(!0),v(null);try{await k(),o(),a()}catch(T){v(T instanceof Error?T.message:"Request failed")}finally{p(!1)}},b=()=>{if(l){y(()=>xle(m,{title:c.title,priority:c.priority,status:c.status,labels:xB(c.labels),description:c.description,acceptance:yB(c.acceptance).map(k=>k.text),ownerReview:c.ownerReview}));return}!e||!n||y(()=>yle(n,e.id,{title:c.title,priority:c.priority,labels:xB(c.labels),description:c.description,acceptance:yB(c.acceptance,e.acceptance),ownerReview:c.ownerReview,...c.status!==e.status?{status:c.status}:{}}))},S=()=>{!e||!n||!u||y(()=>vle(n,e.id,u))},E=e?[e.status,...ple[e.status]]:["backlog","ready"];return i.jsxs(XS,{isOpen:t,onClose:a,onSubmit:b,title:e?`${e.id}: ${e.title}`:"New ticket",submitText:l?"Create ticket":"Save",loading:f,submitDisabled:!c.title.trim()||!m,size:l?void 0:"lg",children:[x&&i.jsx(Ye,{variant:"error",size:"sm",className:"mb-3",onClose:()=>v(null),children:x}),i.jsxs(hi,{children:[i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-title",required:!0,children:"Title"}),i.jsx(Dt,{id:"pt-title",value:c.title,onChange:k=>d({...c,title:k.target.value}),required:!0})]}),l&&!n&&i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-project",required:!0,children:"Project"}),i.jsxs(vn,{id:"pt-project","aria-label":"Project",value:c.project,onChange:k=>d({...c,project:k.target.value}),children:[s.length===0&&i.jsx("option",{value:"",children:"No projects yet"}),s.map(k=>i.jsx("option",{value:k.id,children:k.name},k.id))]}),i.jsx(kc,{children:"Saved in the project's .crewly/tickets/ folder. Team members pick up Ready tickets on their own."})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-priority",children:"Priority"}),i.jsx(vn,{id:"pt-priority","aria-label":"Priority",value:c.priority,onChange:k=>d({...c,priority:k.target.value}),children:mle.map(k=>i.jsx("option",{value:k,children:k},k))})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-status",children:"Status"}),i.jsx(vn,{id:"pt-status","aria-label":"Status",value:c.status,onChange:k=>d({...c,status:k.target.value}),children:E.map(k=>i.jsx("option",{value:k,children:fle[k]},k))})]})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-labels",children:"Labels"}),i.jsx(Dt,{id:"pt-labels",value:c.labels,onChange:k=>d({...c,labels:k.target.value}),placeholder:"ui, export"})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-description",children:"Description"}),i.jsx(er,{id:"pt-description",rows:5,value:c.description,onChange:k=>d({...c,description:k.target.value})})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-acceptance",children:"Acceptance criteria"}),i.jsx(er,{id:"pt-acceptance",rows:4,value:c.acceptance,onChange:k=>d({...c,acceptance:k.target.value}),placeholder:"One per line; start a line with [x] when it is met"})]}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-text",children:[i.jsx("input",{type:"checkbox",checked:c.ownerReview,onChange:k=>d({...c,ownerReview:k.target.checked})}),"I review it myself before it counts as done"]})]}),e&&i.jsxs(hi,{children:[i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-assignee",children:"Assignee"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(vn,{id:"pt-assignee","aria-label":"Assignee",value:u,onChange:k=>h(k.target.value),children:[i.jsx("option",{value:"",children:"Nobody"}),g.map(k=>i.jsx("option",{value:k.value,children:k.label},k.value)),u&&!g.some(k=>k.value===u)&&i.jsx("option",{value:u,children:u})]}),i.jsx(ue,{type:"button",size:"sm",variant:"secondary",onClick:S,disabled:!u||u===e.assignee||f,children:"Assign"})]}),i.jsx(kc,{children:"Assigning a team member starts the work: they get it as a task right away."})]}),i.jsxs("div",{className:"text-xs text-text-2",children:[i.jsxs("div",{children:["File: ",i.jsx("code",{children:e.fileName}),e.workItemId&&i.jsxs(i.Fragment,{children:[" · ",i.jsxs(hs,{to:qt.run(e.workItemId),className:"text-primary-text hover:underline",children:["Run ",e.workItemId.slice(0,8)]})]})]}),e.log.length>0&&i.jsx("ul",{className:"mt-2 space-y-1","aria-label":"Ticket log",children:e.log.slice(-10).map((k,T)=>i.jsx("li",{children:k},T))})]})]})]})};function vB(t){return{title:"",project:t,priority:gle,status:"backlog",labels:"",description:"",acceptance:"",ownerReview:!1}}const YR=({value:t,onChange:e,placeholder:n,"data-testid":s})=>{const[r,a]=_.useState(t!==""),o=_.useRef(null),l=r||t!=="";return _.useEffect(()=>{var c;r&&((c=o.current)==null||c.focus())},[r]),l?i.jsxs("div",{className:"relative w-full sm:w-64",children:[i.jsx(Al,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-3","aria-hidden":"true"}),i.jsx("input",{ref:o,type:"search",value:t,onChange:c=>e(c.target.value),onKeyDown:c=>{c.key==="Escape"&&(e(""),a(!1))},onBlur:()=>{t===""&&a(!1)},placeholder:n,"aria-label":n,"data-testid":s,className:"h-9 w-full rounded-2xl border border-border bg-bg pl-9 pr-8 text-sm text-text placeholder:text-text-3 focus:border-primary-text/60 focus:outline-none"}),t!==""&&i.jsx("button",{type:"button",onClick:()=>{e(""),a(!1)},"aria-label":"Clear search",className:"absolute right-2 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-full text-text-3 hover:text-text",children:i.jsx(ys,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}):i.jsx("button",{type:"button",onClick:()=>a(!0),"aria-label":n,title:n,className:"inline-flex h-9 w-9 items-center justify-center rounded-2xl text-text-2 transition-colors hover:bg-surface-2 hover:text-text",children:i.jsx(Al,{className:"h-4 w-4","aria-hidden":"true"})})},kce=2e3,Ace=6e4;function Pm(t){const[e,n]=_.useState([]);_.useEffect(()=>{if(t)return;let a=!0,o,l=0;const c=()=>{Promise.resolve().then(()=>dt.getTeams()).then(d=>{a&&Array.isArray(d)&&n(d)}).catch(()=>{if(!a)return;const d=Math.min(kce*2**l,Ace);l+=1,o=setTimeout(c,d)})};return c(),()=>{a=!1,o&&clearTimeout(o)}},[t]);const s=t??e,r=_.useMemo(()=>Sce(s),[s]);return{teams:s,names:r}}const Tce={project:[],type:[],include:[]},p$=({projectId:t,teams:e,showNewTicket:n=!0,refreshKey:s=0,onCountsChange:r,pollIntervalMs:a=qle,now:o})=>{var Te,He;const{teams:l,names:c}=Pm(e),[d,u]=_.useState(""),[h,f]=_.useState(""),[p,x]=_.useState(Tce),[v,m]=_.useState([]),[g,y]=_.useState([]),[b,S]=_.useState(0),[E,k]=_.useState([]),[T,A]=_.useState([]),[N,M]=_.useState(!1),[L,j]=_.useState(!1),[D,U]=_.useState(null),[$,G]=_.useState(null),[K,P]=_.useState(null),[B,I]=_.useState(null),[F,q]=_.useState(!1),[H,re]=_.useState(new Set),[ne,Y]=_.useState(!1),z=_.useRef(bB()),X=_.useRef(bB()),Z=((Te=p.type)==null?void 0:Te[0])??void 0,le=t??((He=p.project)==null?void 0:He[0])??null,ye=(p.include??[]).includes("cancelled");_.useEffect(()=>{const ge=setTimeout(()=>f(d),Xle);return()=>clearTimeout(ge)},[d]);const te=t?"locked":JSON.stringify([Z??"",h.trim(),ye]),ke=t??"*";z.current.key=te,X.current.key=ke;const ie=_.useCallback(async(ge=!1)=>{if(t){M(!0);return}await _B(z.current,te,ge,async()=>{const Re={...Z?{kind:Z}:{},...h.trim()?{q:h}:{}},[Oe,de]=await Promise.allSettled([ye?cB({column:"cancelled",...Re}):Promise.resolve(null),cB(Re)]);return()=>{var _e,We,ve,Be;de.status==="fulfilled"?(m(((_e=de.value)==null?void 0:_e.tickets)??[]),S(((ve=(We=de.value)==null?void 0:We.columns)==null?void 0:ve.cancelled)??0),U(null)):U(nw(de.reason)),Oe.status==="fulfilled"&&y(((Be=Oe.value)==null?void 0:Be.tickets)??[]),M(!0)}})},[t,te,Z,h,ye]),xe=_.useCallback(async(ge=!1)=>{await _B(X.current,ke,ge,async()=>{try{const Re=t?await KR(t).then(Oe=>{var de,_e;return{groups:[{project:{id:((de=Oe.project)==null?void 0:de.id)??t,name:((_e=Oe.project)==null?void 0:_e.name)??t},tickets:Oe.tickets}],invalid:Oe.invalid}}):await s$().then(Oe=>({groups:Oe.map(de=>({project:{id:de.project.id,name:de.project.name},tickets:de.tickets})),invalid:[]}));return()=>{k(Re.groups),A(Re.invalid),G(null),j(!0)}}catch(Re){return()=>{G(nw(Re)),j(!0)}}})},[t,ke]),oe=_.useCallback(()=>{ie(),xe()},[ie,xe]);_.useEffect(()=>{ie()},[ie,s]),_.useEffect(()=>{xe()},[xe,s]);const be=_.useRef(0);_.useEffect(()=>{if(!a)return;const ge=setInterval(()=>{typeof document<"u"&&document.hidden||(be.current+=1,ie(!0),(t||be.current%Nce===0)&&xe(!0))},a),Re=()=>{document.hidden||(ie(!0),xe(!0))};return document.addEventListener("visibilitychange",Re),()=>{clearInterval(ge),document.removeEventListener("visibilitychange",Re)}},[ie,xe,a,t]);const J=N&&L,Me=[D,$].filter(Boolean).join(" · ")||null,Se=_.useMemo(()=>E.map(ge=>ge.project),[E]),we=_.useMemo(()=>{const ge=[],Re=!t&&(le===null||le===qv),Oe=!Z&&le!==qv;if(Re){for(const de of v)ge.push(pB(de,o));if(ye)for(const de of g)ge.push(pB(de,o))}if(Oe){for(const de of E)if(!(le&&de.project.id!==le))for(const _e of de.tickets){const We=mB(_e,de.project);We.column==="cancelled"&&!ye||_ce(We,h)&&ge.push(We)}}return ge},[v,g,E,t,le,Z,ye,h,o]),Ie=_.useMemo(()=>bce(we),[we]);_.useEffect(()=>{!J||!r||r({toReview:Ie.to_review.length,total:we.filter(ge=>ge.column!=="cancelled").length,unfilteredTotal:(t?0:v.length)+E.reduce((ge,Re)=>ge+Re.tickets.filter(Oe=>mB(Oe,Re.project).column!=="cancelled").length,0)})},[J,Ie,we,r,t,v,E]);const se=_.useMemo(()=>(t?0:b)+E.reduce((ge,Re)=>ge+Re.tickets.filter(Oe=>Oe.status==="cancelled").length,0),[t,b,E]),W=_.useMemo(()=>{const ge=[];return t||(ge.push({id:"project",label:ui.FILTER_PROJECT,single:!0,options:[...E.map(Re=>({value:Re.project.id,label:Re.project.name,count:Re.tickets.filter(Oe=>Oe.status!=="cancelled").length})),{value:qv,label:ui.NO_PROJECT,count:v.length}]}),ge.push({id:"type",label:ui.FILTER_TYPE,single:!0,options:d$.map(Re=>({value:Re,label:c$[Re]}))})),ge.push({id:"include",label:ui.FILTER_INCLUDE,options:[{value:"cancelled",label:ui.CANCELLED,count:se}]}),ge},[t,E,v.length,se]),ae=_.useCallback(ge=>{ge.ticket?P(ge.ticket.id):ge.projectTicket&&ge.projectId&&I({ticket:ge.projectTicket,projectId:ge.projectId})},[]),Q=ge=>re(Re=>{const Oe=new Set(Re);return Oe.has(ge)?Oe.delete(ge):Oe.add(ge),Oe}),ce=h.trim()!==""||Object.values(p).some(ge=>ge.length>0),pe=J&&we.length===0&&!ce&&!Me,je=ye?[...fB,"cancelled"]:[...fB],me=(ge,Re,Oe)=>{const de=H.has(ge),_e=de?Re:Re.slice(0,Oe);return i.jsxs(i.Fragment,{children:[_e.map(We=>i.jsx(pce,{card:We,assigneeName:Xd(We.assignee,c),onOpen:ae},We.key)),Re.length>Oe&&i.jsx("button",{type:"button",onClick:()=>Q(ge),"aria-expanded":de,className:"self-start px-0.5 py-1 text-[13px] font-semibold text-primary-text hover:underline","data-testid":`tickets-column-${ge}-more`,children:de?ui.SHOW_LESS:`Show all ${Re.length}`})]})};return i.jsxs("div",{className:"flex min-w-0 max-w-full flex-col gap-6","data-testid":"tickets-page",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(Jo,{groups:W,value:p,onChange:x}),i.jsx(YR,{value:d,onChange:u,placeholder:pn.SEARCH_PLACEHOLDER,"data-testid":"tickets-search"}),i.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":pn.REFRESH,onClick:oe}),n&&i.jsx(ue,{size:"sm",icon:qn,onClick:()=>q(!0),children:ui.NEW_TICKET})]})]}),t&&i.jsx("p",{className:"-mt-3 text-[13px] text-text-2",children:ui.PROJECT_HINT}),Z&&i.jsx("p",{className:"-mt-3 text-[13px] text-text-2",children:ui.TYPE_HIDES_PROJECT}),Me&&i.jsx(Ye,{variant:"error",size:"sm",title:pn.LOAD_FAILED,children:Me}),T.length>0&&i.jsxs(Ye,{variant:"warning",size:"sm",children:[T.length," file(s) in .crewly/tickets/ could not be read: ",T.map(ge=>`${ge.fileName} (${ge.error})`).join("; ")]}),J?pe?i.jsx(is,{icon:XH,title:t?ui.EMPTY_PROJECT_TITLE:pn.EMPTY_BOARD_TITLE,description:t?ui.EMPTY_PROJECT_DESC:pn.EMPTY_BOARD_DESC}):i.jsxs(i.Fragment,{children:[ce&&we.length===0&&i.jsx("p",{className:"text-[13px] text-text-2",children:ui.NO_MATCH}),i.jsx("div",{className:"grid min-w-0 grid-cols-1 items-start gap-6 sm:grid-cols-2 xl:grid-cols-4","data-testid":"tickets-board",children:mce.map(ge=>{const Re=Ie[ge],Oe=ge==="to_review"&&Re.length>0;return i.jsxs("section",{"aria-label":sp[ge],"data-testid":`tickets-column-${ge}`,className:Js("flex min-w-0 flex-col gap-2",Oe&&"rounded-2xl bg-attention-soft p-3"),children:[i.jsxs("header",{className:"flex items-baseline gap-2 px-0.5 pb-1",children:[i.jsx("h2",{className:Js("text-[15px] font-bold leading-snug",Oe?"text-attention":"text-text"),children:sp[ge]}),i.jsx("span",{className:"text-[13px] text-text-2","data-testid":`tickets-column-${ge}-count`,children:Re.length}),Oe&&i.jsx("span",{className:"ml-auto text-[13px] font-semibold text-attention",children:ui.NEEDS_YOU})]}),Re.length===0?i.jsx("p",{className:"px-0.5 py-3 text-[13px] text-text-3",children:lB[ge]}):me(ge,Re,gce)]},ge)})}),i.jsxs("div",{className:"flex flex-col gap-4 border-t border-border-soft pt-4",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[13px] text-text-2","data-testid":"tickets-quiet-line",children:[je.map((ge,Re)=>i.jsxs(an.Fragment,{children:[Re>0&&i.jsx("span",{className:"text-text-3",children:"·"}),i.jsxs("span",{children:[sp[ge]," ",Ie[ge].length]})]},ge)),i.jsx("span",{className:"text-text-3",children:"—"}),i.jsx("button",{type:"button",onClick:()=>Y(ge=>!ge),"aria-expanded":ne,className:"font-semibold text-primary-text hover:underline","data-testid":"tickets-quiet-toggle",children:ne?ui.HIDE:ui.SHOW})]}),ne&&je.map(ge=>i.jsxs("section",{"aria-label":sp[ge],"data-testid":`tickets-column-${ge}`,className:"flex flex-col gap-2",children:[i.jsxs("h2",{className:"text-[15px] font-bold text-text",children:[sp[ge]," ",i.jsx("span",{className:"text-[13px] font-normal text-text-2",children:Ie[ge].length})]}),Ie[ge].length===0?i.jsx("p",{className:"py-1 text-[13px] text-text-3",children:lB[ge]}):i.jsx("div",{className:"grid grid-cols-1 items-start gap-2 sm:grid-cols-2 xl:grid-cols-4",children:me(ge,Ie[ge],8)})]},ge))]})]}):i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(zt,{})}),i.jsx(hce,{ticketId:K,onClose:()=>P(null),onChanged:()=>void ie(),now:o}),i.jsx(f$,{open:F||B!==null,ticket:(B==null?void 0:B.ticket)??null,projectId:(B==null?void 0:B.projectId)??t??(le&&le!==qv?le:void 0),projects:Se,teams:l,onClose:()=>{q(!1),I(null)},onSaved:()=>void xe()})]})},Nce=4;function bB(){return{key:"",inFlight:!1,seq:0,applied:0}}async function _B(t,e,n,s){if(n&&t.inFlight)return;const r=++t.seq;t.inFlight=!0;try{const a=await s();if(t.key!==e||r<t.applied)return;t.applied=r,a()}finally{r===t.seq&&(t.inFlight=!1)}}const Mce={active:"bg-emerald-400",started:"bg-emerald-400",starting:"bg-yellow-400",activating:"bg-yellow-400",idle:"bg-yellow-400",suspended:"bg-orange-400",inactive:"bg-text-secondary-dark"},jce={orchestrator:ree,"team-leader":rR};function Rce(t){if(t.length===0)return[];const e=new Map;for(const a of t)e.set(a.id,a);const n=new Map,s=[];for(const a of t)if(!a.parentMemberId)s.push(a);else{const o=n.get(a.parentMemberId)??[];o.push(a),n.set(a.parentMemberId,o)}function r(a,o){const l=n.get(a.id)??[];return{member:a,depth:o,children:l.map(c=>r(c,o+1))}}return s.map(a=>r(a,0))}function Ice(t){return Mce[t]??"bg-text-secondary-dark"}function Lce(t){return t==="in_progress"?"Working":t.charAt(0).toUpperCase()+t.slice(1)}const JR=({node:t,expandedIds:e,onToggle:n,onNodeClick:s})=>{const{member:r,children:a,depth:o}=t,l=a.length>0,c=e.has(r.id),d=jce[r.role]??sy,u=Ice(r.agentStatus),h=Lce(r.workingStatus),f=_.useCallback(x=>{x.stopPropagation(),n(r.id)},[r.id,n]),p=_.useCallback(()=>{s==null||s(r)},[r,s]);return i.jsxs("div",{"data-testid":`tree-node-${r.id}`,children:[i.jsxs("div",{className:"flex items-center gap-2 py-1.5 px-2 rounded-md hover:bg-background-dark/50 cursor-pointer transition-colors",style:{paddingLeft:`${o*24+8}px`},onClick:p,role:"treeitem","aria-expanded":l?c:void 0,"aria-level":o+1,children:[l?i.jsx("button",{onClick:f,className:"p-0.5 rounded hover:bg-background-dark text-text-secondary-dark","aria-label":c?"Collapse":"Expand",children:c?i.jsx(wo,{size:14}):i.jsx(cr,{size:14})}):i.jsx("span",{className:"w-5"}),i.jsx(d,{size:16,className:"text-text-secondary-dark shrink-0"}),i.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${u}`,title:r.agentStatus}),i.jsx("span",{className:"text-sm font-medium text-text-primary-dark truncate",children:r.name}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:r.role}),i.jsx("span",{className:`ml-auto text-xs px-1.5 py-0.5 rounded-full ${r.workingStatus==="in_progress"?"bg-blue-500/10 text-blue-400":"bg-background-dark text-text-secondary-dark"}`,children:h})]}),l&&c&&i.jsx("div",{role:"group",children:a.map(x=>i.jsx(JR,{node:x,expandedIds:e,onToggle:n,onNodeClick:s},x.member.id))})]})};JR.displayName="TreeNode";const m$=({members:t,onNodeClick:e,className:n=""})=>{const[s,r]=_.useState(()=>{const l=new Set;for(const c of t)(c.canDelegate||c.role==="team-leader"||c.role==="orchestrator")&&l.add(c.id);return l}),a=_.useCallback(l=>{r(c=>{const d=new Set(c);return d.has(l)?d.delete(l):d.add(l),d})},[]),o=_.useMemo(()=>Rce(t),[t]);return t.length===0?i.jsx("div",{className:`text-sm text-text-secondary-dark p-4 ${n}`,children:"No team members to display."}):i.jsx("div",{className:`${n}`,role:"tree","aria-label":"Team hierarchy",children:o.map(l=>i.jsx(JR,{node:l,expandedIds:s,onToggle:a,onNodeClick:e},l.member.id))})};m$.displayName="HierarchyTreeView";function Pce(t){let e=0,n=0,s=0,r=0;for(const a of t)a.agentStatus==="active"||a.agentStatus==="started"?e++:a.agentStatus==="inactive"&&n++,a.workingStatus==="in_progress"&&s++,a.hierarchyLevel!==void 0&&a.hierarchyLevel>r&&(r=a.hierarchyLevel);return{total:t.length,active:e,idle:t.length-e-n,inactive:n,working:s,hierarchyDepth:r+1}}const rp=({label:t,value:e,icon:n,color:s})=>i.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-border-dark p-3 bg-background-dark/30",children:[i.jsx("div",{className:`p-2 rounded-md ${s}`,children:i.jsx(n,{size:16})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-lg font-semibold text-text-primary-dark",children:e}),i.jsx("p",{className:"text-xs text-text-secondary-dark",children:t})]})]});rp.displayName="StatCard";const g$=({member:t,onClick:e})=>{const n=t.agentStatus==="active"||t.agentStatus==="started"?"bg-emerald-400":t.agentStatus==="inactive"?"bg-text-secondary-dark":"bg-yellow-400";return i.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-border-dark p-3 hover:bg-background-dark/50 cursor-pointer transition-colors",onClick:()=>e==null?void 0:e(t),"data-testid":`flat-member-${t.id}`,children:[i.jsx("span",{className:`w-2.5 h-2.5 rounded-full shrink-0 ${n}`}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-sm font-medium text-text-primary-dark truncate",children:t.name}),i.jsx("p",{className:"text-xs text-text-secondary-dark",children:t.role})]}),i.jsx("span",{className:`ml-auto text-xs px-1.5 py-0.5 rounded-full ${t.workingStatus==="in_progress"?"bg-blue-500/10 text-blue-400":"bg-background-dark text-text-secondary-dark"}`,children:t.workingStatus==="in_progress"?"Working":"Idle"})]})};g$.displayName="FlatMemberCard";const x$=({team:t,onMemberClick:e,className:n=""})=>{const s=_.useMemo(()=>Pce(t.members),[t.members]),r=t.hierarchical===!0;return i.jsxs("div",{className:`space-y-4 ${n}`,"data-testid":"hierarchy-dashboard",children:[i.jsx("div",{className:"flex items-center justify-between",children:i.jsxs("div",{className:"flex items-center gap-2",children:[r?i.jsx(x0,{size:18,className:"text-primary"}):i.jsx(vr,{size:18,className:"text-primary"}),i.jsx("h3",{className:"text-lg font-semibold text-text-primary-dark",children:t.name}),r&&i.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-primary/10 text-primary border border-primary/20",children:"Hierarchical"})]})}),i.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3","data-testid":"stats-row",children:[i.jsx(rp,{label:"Total",value:s.total,icon:vr,color:"bg-blue-500/10 text-blue-400"}),i.jsx(rp,{label:"Active",value:s.active,icon:lu,color:"bg-emerald-500/10 text-emerald-400"}),i.jsx(rp,{label:"Working",value:s.working,icon:Lh,color:"bg-primary/10 text-primary"}),r?i.jsx(rp,{label:"Depth",value:s.hierarchyDepth,icon:x0,color:"bg-primary/10 text-primary"}):i.jsx(rp,{label:"Inactive",value:s.inactive,icon:vr,color:"bg-text-secondary-dark/10 text-text-secondary-dark"})]}),r?i.jsx("div",{className:"rounded-lg border border-border-dark p-3","data-testid":"hierarchy-view",children:i.jsx(m$,{members:t.members,onNodeClick:e})}):i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2","data-testid":"flat-view",children:t.members.length===0?i.jsx("p",{className:"text-sm text-text-secondary-dark col-span-2 p-4",children:"No team members."}):t.members.map(a=>i.jsx(g$,{member:a,onClick:e},a.id))})]})};x$.displayName="HierarchyDashboard";function Dce(t){return t.filter(e=>e.role!=="orchestrator")}const y$=({config:t,onChange:e,members:n,className:s=""})=>{const r=Dce(n),a=t.leaderIds??(t.leaderId?[t.leaderId]:[]),o=_.useCallback(()=>{e({hierarchical:!t.hierarchical,leaderId:t.hierarchical?null:t.leaderId,leaderIds:t.hierarchical?[]:t.leaderIds})},[t,e]),l=_.useCallback(c=>{const u=a.includes(c)?a.filter(h=>h!==c):[...a,c];e({...t,leaderIds:u,leaderId:u[0]??null})},[t,a,e]);return i.jsxs("div",{className:`rounded-lg border border-border-dark p-4 ${s}`,"data-testid":"hierarchy-mode-config",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:i.jsx(vr,{size:18,className:"text-primary"})}),i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-text-primary-dark",children:"Hierarchical Mode"}),i.jsx("p",{className:"text-xs text-text-secondary-dark",children:"Enable Team Leader management with delegation"})]})]}),i.jsx(Gi,{size:"lg",role:"switch","aria-checked":t.hierarchical,"aria-label":"Toggle hierarchical mode",checked:t.hierarchical,onChange:o})]}),t.hierarchical&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-border-dark",children:[i.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium text-text-primary-dark mb-2",children:[i.jsx(rR,{size:14,className:"text-text-secondary-dark"}),"Team Leaders",i.jsx("span",{className:"text-xs font-normal text-text-secondary-dark",children:"(select one or more)"})]}),r.length===0?i.jsx("p",{className:"text-xs text-text-secondary-dark","data-testid":"no-leaders-message",children:"Add team members first, then select leaders."}):i.jsx("div",{className:"flex flex-wrap gap-2","data-testid":"leader-select",children:r.map(c=>{const d=a.includes(c.id),u=a[0]===c.id;return i.jsxs("button",{type:"button",onClick:()=>l(c.id),className:`inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border transition-colors ${d?"bg-primary/15 border-primary/40 text-primary":"bg-background-dark border-border-dark text-text-secondary-dark hover:border-primary/50 hover:text-text-primary-dark"}`,"data-testid":`leader-toggle-${c.id}`,children:[d&&i.jsx(rs,{className:"w-3 h-3"}),c.name," (",c.role,")",u&&d&&i.jsx("span",{className:"text-[10px] bg-primary/20 px-1 rounded",children:"Primary"})]},c.id)})}),a.length>0&&i.jsxs("div",{className:"mt-3 p-3 rounded-md bg-background-dark/50","data-testid":"hierarchy-preview",children:[i.jsx("p",{className:"text-xs text-text-secondary-dark mb-2",children:"Hierarchy preview:"}),a.map(c=>{const d=n.find(h=>h.id===c),u=n.filter(h=>!a.includes(h.id)&&h.role!=="orchestrator").length;return i.jsxs("div",{className:"flex items-center gap-1 text-xs text-text-primary-dark mb-1",children:[i.jsx("span",{className:"font-medium",children:"Orchestrator"}),i.jsx(cr,{size:12,className:"text-text-secondary-dark"}),i.jsx("span",{className:"font-medium text-primary",children:(d==null?void 0:d.name)??"TL"}),a.length===1&&i.jsxs(i.Fragment,{children:[i.jsx(cr,{size:12,className:"text-text-secondary-dark"}),i.jsxs("span",{className:"text-text-secondary-dark",children:[u," workers"]})]})]},c)}),a.length>1&&i.jsx("div",{className:"flex items-center gap-1 text-xs text-text-secondary-dark mt-1",children:i.jsxs("span",{children:[n.filter(c=>!a.includes(c.id)&&c.role!=="orchestrator").length," workers (assign via member parentMemberId)"]})})]})]})]})};y$.displayName="HierarchyModeConfig";const Oce={completed:vo,assigned:jr,active:VS,working:VS,submitted:jH,input_required:$i,verifying:vee,blocked:$i,failed:qd,cancelled:qd,pending_assignment:jr},Bce={completed:"text-emerald-400",assigned:"text-yellow-400",active:"text-blue-400",working:"text-blue-400",submitted:"text-primary",input_required:"text-orange-400",verifying:"text-cyan-400",blocked:"text-orange-400",failed:"text-red-400",cancelled:"text-text-secondary-dark",pending_assignment:"text-text-secondary-dark"},Fce={high:"bg-red-500/10 text-red-400 border-red-500/20",medium:"bg-yellow-500/10 text-yellow-400 border-yellow-500/20",low:"bg-text-secondary-dark/10 text-text-secondary-dark border-border-dark"};function Uce(t){if(t.length===0)return[];const e=new Map,n=[];for(const r of t)if(!r.parentTaskId)n.push(r);else{const a=e.get(r.parentTaskId)??[];a.push(r),e.set(r.parentTaskId,a)}function s(r,a){const o=e.get(r.id)??[];return{task:r,depth:a,children:o.map(l=>s(l,a+1))}}return n.map(r=>s(r,0))}function zce(t){return{completed:"Completed",assigned:"Assigned",active:"Active",working:"Working",submitted:"Submitted",input_required:"Input Required",verifying:"Verifying",blocked:"Blocked",failed:"Failed",cancelled:"Cancelled",pending_assignment:"Pending"}[t]??t}function Hce(t){if(t.children.length===0)return t.task.status==="completed"?100:0;const e=t.children.filter(n=>n.task.status==="completed").length;return Math.round(e/t.children.length*100)}const ZR=({node:t,expandedIds:e,onToggle:n,onTaskClick:s})=>{const{task:r,children:a,depth:o}=t,l=a.length>0,c=e.has(r.id),d=Oce[r.status]??jH,u=Bce[r.status]??"text-text-secondary-dark",h=zce(r.status),f=_.useCallback(v=>{v.stopPropagation(),n(r.id)},[r.id,n]),p=_.useCallback(()=>{s==null||s(r)},[r,s]),x=l?Hce(t):null;return i.jsxs("div",{"data-testid":`task-node-${r.id}`,children:[i.jsxs("div",{className:"flex items-center gap-2 py-1.5 px-2 rounded-md hover:bg-background-dark/50 cursor-pointer transition-colors",style:{paddingLeft:`${o*24+8}px`},onClick:p,role:"treeitem","aria-expanded":l?c:void 0,"aria-level":o+1,children:[l?i.jsx("button",{onClick:f,className:"p-0.5 rounded hover:bg-background-dark text-text-secondary-dark","aria-label":c?"Collapse":"Expand",children:c?i.jsx(wo,{size:14}):i.jsx(cr,{size:14})}):i.jsx("span",{className:"w-5"}),i.jsx(d,{size:16,className:`shrink-0 ${u}`}),i.jsx("span",{className:"text-sm font-medium text-text-primary-dark truncate",children:r.taskName}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:r.assignedSessionName}),r.priority&&i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full border ${Fce[r.priority]??""}`,children:r.priority}),i.jsxs("span",{className:`ml-auto text-xs ${u}`,children:[h,x!==null&&` (${x}%)`]})]}),l&&c&&i.jsx("div",{role:"group",children:a.map(v=>i.jsx(ZR,{node:v,expandedIds:e,onToggle:n,onTaskClick:s},v.task.id))})]})};ZR.displayName="TaskNode";const v$=({tasks:t,onTaskClick:e,className:n=""})=>{const[s,r]=_.useState(()=>{const l=new Set;for(const c of t)c.childTaskIds&&c.childTaskIds.length>0&&l.add(c.id);return l}),a=_.useCallback(l=>{r(c=>{const d=new Set(c);return d.has(l)?d.delete(l):d.add(l),d})},[]),o=_.useMemo(()=>Uce(t),[t]);return t.length===0?i.jsx("div",{className:`text-sm text-text-secondary-dark p-4 ${n}`,children:"No tasks to display."}):i.jsx("div",{className:`${n}`,role:"tree","aria-label":"Task flow",children:o.map(l=>i.jsx(ZR,{node:l,expandedIds:s,onToggle:a,onTaskClick:e},l.task.id))})};v$.displayName="TaskFlowView";class Gce{constructor(){Fn(this,"cache",null);Fn(this,"lastCacheTime",0);Fn(this,"cacheTimeout",3e4)}async getInProgressTasks(){var n,s;const e=Date.now();if(this.cache&&e-this.lastCacheTime<this.cacheTimeout)return this.cache.tasks;try{const r=await fetch("/api/in-progress-tasks");if(!r.ok)return console.warn("Failed to fetch in-progress tasks:",r.statusText),((n=this.cache)==null?void 0:n.tasks)||[];const a=await r.json();return this.cache=a,this.lastCacheTime=e,a.tasks}catch(r){return console.error("Error loading in-progress tasks:",r),((s=this.cache)==null?void 0:s.tasks)||[]}}async getTaskAssignedMember(e){return(await this.getInProgressTasks()).find(s=>{var r;return s.taskPath===e||s.originalPath===e||e.includes(s.taskName)||s.originalPath.includes(((r=e.split("/").pop())==null?void 0:r.replace(".md",""))||"")})||null}async getTaskAssignedMemberDetails(e){try{const n=await this.getTaskAssignedMember(e);if(!n)return{};const s=await dt.getTeams();for(const r of s)if(r.members){const a=r.members.find(o=>o.id===n.assignedMemberId||o.sessionName===n.assignedSessionName);if(a)return{memberName:a.name,sessionName:a.sessionName||n.assignedSessionName,teamName:r.name}}return{sessionName:n.assignedSessionName}}catch(n){return console.error("Error getting task assigned member details:",n),{}}}clearCache(){this.cache=null,this.lastCacheTime=0}}const $ce=new Gce;function Wce(t){return t.map(e=>{var n,s;return{id:e.id,taskName:e.taskName||((s=(n=e.taskPath)==null?void 0:n.split("/").pop())==null?void 0:s.replace(".md",""))||e.id,status:e.status||"assigned",assignedSessionName:e.assignedSessionName||"",assignedTeamMemberId:e.assignedTeamMemberId||e.assignedMemberId||"",parentTaskId:e.parentTaskId,childTaskIds:e.childTaskIds,delegatedBy:e.delegatedBy,delegatedBySession:e.delegatedBySession,assigneeHierarchyLevel:e.assigneeHierarchyLevel,priority:e.priority,completedAt:e.completedAt,assignedAt:e.assignedAt||""}})}const Vce=({project:t,teams:e,onCountChange:n})=>{const[s,r]=_.useState([]);return _.useEffect(()=>{let a=!1;return(async()=>{try{const o=await $ce.getInProgressTasks();a||r(Wce(o))}catch{a||r([])}})(),()=>{a=!0}},[]),i.jsxs("div",{"data-testid":"project-tasks-tab",children:[s.length>0&&i.jsx(ti,{title:`Task Flow (${s.length} active)`,summary:"Who delegated what to whom",className:"mb-4 border-t-0 pt-0",unmountWhenClosed:!0,"data-testid":"project-task-flow",children:i.jsx(v$,{tasks:s})}),i.jsx(p$,{projectId:t.id,teams:e,onCountsChange:({unfilteredTotal:a})=>n==null?void 0:n(a)})]})},iE="/api/project-ticket-autopilot";class Kce extends Error{constructor(e,n){super(e),this.status=n,this.name="AutopilotApiError"}}async function aE(t,e){const n=e?await fetch(t,e):await fetch(t);let s={};try{s=await n.json()}catch{s={}}if(!n.ok||s.success===!1)throw new Kce(s.error||`HTTP ${n.status}`,n.status);return s.data}function b$(t,e){const n=new URLSearchParams({days:String(t)});return e&&n.set("label",e),`?${n.toString()}`}function qce(t,e,n=null){return aE(`${iE}/${encodeURIComponent(t)}/stats${b$(e,n)}`)}async function Xce(t,e,n=null){return(await aE(`${iE}/${encodeURIComponent(t)}/runs${b$(e,n)}`)).days}function Yce(t){return aE(`${iE}/${encodeURIComponent(t)}`)}function Jce(t,e){return aE(`${iE}/${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({speedMode:e})})}function Bi(t){const e=Math.floor(Math.max(0,t)/6e4);if(e<1)return"<1m";const n=Math.floor(e/1440),s=Math.floor(e%1440/60),r=e%60;return n>0?s>0?`${n}d ${s}h`:`${n}d`:s>0?r>0?`${s}h ${r}m`:`${s}h`:`${r}m`}function S0(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${Math.round(t/1e3)}k`:String(Math.round(t))}function Tc(t){return t>0&&t<.01?"<$0.01":`$${t.toFixed(2)}`}function w0(t,e=new Date){const n=new Date(t);if(Number.isNaN(n.getTime()))return"";const s=n.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});return n.toDateString()===e.toDateString()?s:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${s}`}const QR={runtime_quota:"runtime out of usage or signed out",delivery_failure:"a message was not delivered",waiting_on_owner:"waiting on you",waiting_on_agent:"waiting on an agent",nobody_pushing:"nobody pushing"},Zce={done:"Done",cancelled:"Cancelled",failed:"Failed",waiting_on_owner:"Waiting on you",in_progress:"In progress",no_open_work:"Nothing open"},Qce={"trace.root":"Started","trace.truncated":"Trace full","request.created":"Ticket created","request.status":"Ticket status","ticket.created":"Project ticket","workitem.created":"Work item","workitem.status":"Work item status","turn.delivered":"Delivered","turn.error":"Turn failed","turn.ended":"Turn ended","message.agent":"Agent message","skill.call":"Skill call","guard.block":"Refused",error:"Error","message.outbound":"Reply","status.routed":"Status report","decision.created":"Decision asked","decision.status":"Decision","harness.redelivery":"Redelivered","harness.wake":"Woken","harness.correction":"Corrected","harness.nudge":"Nudged","harness.subagent_sendback":"Subagent sent back","experiment.event":"Experiment",usage:"Tokens","runtime.blocked":"Runtime blocked","owner.action":"Your action","autopilot.action":"Autopilot","ticket.status":"Ticket status"};function ede(t){return Qce[t]??t}const SB=new Set(["skill.call","usage","turn.ended"]);function tde(t){return t.actor.kind==="owner"?"You":t.actor.kind==="agent"?t.actor.session??"Agent":"Crewly"}const nde=["7","14","30"],sde=[{key:"rush",label:"Rush"},{key:"normal",label:"Normal"},{key:"chill",label:"Chill"}],rde={rush:"Replans whenever the queue runs dry (≥ 1 h apart, ≤ 12 a day), self-review hourly, retries an empty replan after 1 h.",normal:"Replans when the queue runs dry (≥ 3 h apart, ≤ 4 a day), self-review daily, retries an empty replan the next day.",chill:"At most 1 replan a day, self-review weekly, retries an empty replan the next week."},ide="Rush keeps the team busy all day and can use the whole daily budget every day; the budget brake still stops it.";function wB(t){if(!(t!=null&&t.stopReason)||!t.stopReasonText)return null;const e=t.stoppedSince?new Date(t.stoppedSince).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):null;return`Stopped: ${t.stopReasonText}${e?` (since ${e})`:""}`}const Xk="__all__";function ade(t,e){const n=t.total,s=[`${n.verified} ticket${n.verified===1?"":"s"} shipped`];return n.verified>0?(s.push(`${Math.round(n.ownerTouches.total/n.verified*10)/10} owner touches per ticket`),s.push(`${Tc(n.costUsd/n.verified)} per shipped ticket`)):s.push(`${n.started} started`),`Last ${e} days${t.label?` (${t.label})`:""}: ${s.join(" · ")}`}function ode(t){return t.settings.enabled?t.pausedForToday?{label:"Paused on budget today",tone:"attention"}:{label:"On",tone:"success"}:{label:"Off",tone:"neutral"}}function lde(t,e=3){return Object.entries(t.total.stalls.byCause).filter(([,n])=>n.count>0).sort((n,s)=>s[1].ms-n[1].ms||s[1].count-n[1].count).slice(0,e).map(([n,s])=>({cause:n,count:s.count,ms:s.ms}))}function E0(t){const[e,n,s]=t.split("-").map(Number);return new Date(e,n-1,s).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function cde(t){return`${E0(t.day)}: ${t.verified} shipped, ${t.started} started, ${t.done} done, ${t.sentBack} sent back, ${Tc(t.costUsd)}${t.pausedMs>0?`, paused ${Bi(t.pausedMs)}`:""}`}const dde=({days:t})=>{const e=Math.max(1,...t.map(n=>n.verified));return i.jsxs("div",{className:"overflow-x-auto","data-testid":"autopilot-day-bars",children:[i.jsx("div",{className:"flex items-end gap-[2px] h-24 min-w-full",role:"img","aria-label":"Tickets shipped per day",children:t.map(n=>i.jsx("div",{className:"flex flex-1 min-w-[10px] h-full flex-col justify-end",title:cde(n),"data-testid":`autopilot-bar-${n.day}`,children:i.jsx("div",{className:n.verified>0?"bg-primary rounded-t":"bg-muted-dot rounded-t",style:{height:n.verified>0?`${Math.max(8,n.verified/e*100)}%`:"2px"}})},n.day))}),i.jsxs("div",{className:"mt-1 flex justify-between text-xs text-text-3",children:[i.jsx("span",{children:t[0]?E0(t[0].day):""}),i.jsx("span",{children:t.length?E0(t[t.length-1].day):""})]})]})},nd=({label:t,value:e,attention:n})=>i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:`text-lg font-semibold ${n?"text-attention":"text-text"}`,children:e}),i.jsx("div",{className:"text-xs text-text-3 truncate",children:t})]}),ude=({projectId:t})=>{const[e,n]=_.useState("14"),[s,r]=_.useState(Xk),[a,o]=_.useState(null),[l,c]=_.useState([]),[d,u]=_.useState(null),[h,f]=_.useState(!0),[p,x]=_.useState(null),[v,m]=_.useState(null),[g,y]=_.useState(!1);_.useEffect(()=>{let M=!1;return Yce(t).then(L=>{M||x(L)}).catch(()=>{M||x(null)}),()=>{M=!0}},[t]);const b=M=>{g||(p==null?void 0:p.speedMode)===M||(y(!0),m(null),Jce(t,M).then(L=>x(L)).catch(L=>m(L instanceof Error?L.message:String(L))).finally(()=>y(!1)))};_.useEffect(()=>{let M=!1;f(!0);const L=Number(e),j=s===Xk?null:s;return Promise.all([qce(t,L,j),Xce(t,L,j)]).then(([D,U])=>{M||(o(D),c(U),u(null))}).catch(D=>{M||u(D instanceof Error?D.message:String(D))}).finally(()=>{M||f(!1)}),()=>{M=!0}},[t,e,s]);const S=_.useMemo(()=>[{key:Xk,label:"All tickets"},...((a==null?void 0:a.labels)??[]).map(M=>({key:M,label:M}))],[a==null?void 0:a.labels]);if(d)return i.jsx(is,{icon:m0,title:"Autopilot numbers are not available",description:d});if(!a)return h?i.jsx("div",{className:"p-4 text-sm text-text-3",children:"Loading…"}):null;const E=Number(e),k=l.filter(M=>M.runTraceId||M.traces.length>0),T=a.total;if(!a.settings.enabled&&k.length===0)return i.jsx(is,{icon:m0,title:"Autopilot is off",description:"When the ticket autopilot drives this project, its daily runs, what shipped and where it stalled show here."});const A=ode(a),N=lde(a);return i.jsxs("div",{className:"flex flex-col gap-4 pb-6","data-testid":"autopilot-tab",children:[i.jsxs("section",{className:"rounded-[var(--crewly-radius)] border border-border bg-surface p-4",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(sn,{tone:A.tone,children:A.label}),i.jsx("h2",{className:"text-[15px] font-semibold text-text min-w-0","data-testid":"autopilot-headline",children:ade(a,E)})]}),p&&i.jsxs("div",{className:"mt-3 flex flex-col gap-1","data-testid":"autopilot-speed",children:[i.jsx(q_,{label:"Speed",options:sde.map(M=>({key:M.key,label:M.label})),value:p.speedMode,onChange:M=>b(M),testIdPrefix:"autopilot-speed"}),i.jsx("p",{className:"text-xs text-text-3",children:rde[p.speedMode]}),p.speedMode==="rush"&&i.jsx("p",{className:"text-xs text-attention","data-testid":"autopilot-rush-warning",children:ide}),v&&i.jsx("p",{className:"text-xs text-attention",children:v}),wB(p)&&i.jsx("p",{className:"text-sm text-attention","data-testid":"autopilot-stop",children:wB(p)}),p.lastSelfReview&&i.jsxs("p",{className:"text-sm text-text-2 break-words","data-testid":"autopilot-self-review",children:["Self-review: ",p.lastSelfReview.gap," · next bet: ",p.lastSelfReview.nextBet]})]}),i.jsxs("div",{className:"mt-3 flex flex-wrap gap-3",children:[i.jsx(q_,{label:"Range",options:nde.map(M=>({key:M,label:`${M} days`})),value:e,onChange:M=>n(M),testIdPrefix:"autopilot-range"}),S.length>1&&i.jsx(q_,{label:"Label",options:S,value:s,onChange:r,testIdPrefix:"autopilot-label"})]})]}),i.jsxs("section",{className:"rounded-[var(--crewly-radius)] border border-border bg-surface p-4",children:[i.jsx("h3",{className:"mb-2 text-[13px] font-semibold text-text-2",children:"Shipped per day"}),i.jsx(dde,{days:a.days}),i.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-3 sm:grid-cols-4",children:[i.jsx(nd,{label:"Started",value:String(T.started)}),i.jsx(nd,{label:"Sent back",value:String(T.sentBack),attention:T.sentBack>0}),i.jsx(nd,{label:"Your touches",value:String(T.ownerTouches.total)}),i.jsx(nd,{label:"Cycle time (median)",value:T.cycleTime.toVerified.medianMs===null?"—":Bi(T.cycleTime.toVerified.medianMs)}),i.jsx(nd,{label:"Harness interventions",value:String(T.interventions.total)}),i.jsx(nd,{label:"Cost",value:Tc(T.costUsd)}),i.jsx(nd,{label:"Team tokens / budget",value:`${S0(T.budget.ledgerTokens)} / ${S0(T.budget.dailyBudgetTokens)}`,attention:T.budget.pct>=1}),i.jsx(nd,{label:"Paused on budget",value:T.pausedMs>0?Bi(T.pausedMs):"—",attention:T.pausedMs>0})]})]}),i.jsxs("section",{className:"rounded-[var(--crewly-radius)] border border-border bg-surface p-4","data-testid":"autopilot-stalls",children:[i.jsx("h3",{className:"mb-2 text-[13px] font-semibold text-text-2",children:"Where it stalled"}),N.length===0?i.jsx("p",{className:"text-sm text-text-3",children:"No stalls in this range."}):i.jsx("ul",{className:"flex flex-col gap-1",children:N.map(M=>i.jsxs("li",{className:"flex flex-wrap justify-between gap-2 text-sm",children:[i.jsx("span",{className:"text-text",children:QR[M.cause]}),i.jsxs("span",{className:"text-text-3",children:[M.count," × · ",Bi(M.ms)]})]},M.cause))})]}),i.jsxs("section",{className:"rounded-[var(--crewly-radius)] border border-border bg-surface p-2","data-testid":"autopilot-runs",children:[i.jsx("h3",{className:"px-2 pb-1 pt-2 text-[13px] font-semibold text-text-2",children:"Runs"}),k.length===0?i.jsx("p",{className:"px-2 pb-2 text-sm text-text-3",children:"No autopilot runs in this range."}):i.jsx(fs,{limit:5,total:k.length,children:k.map(M=>{const L=a.days.find(j=>j.day===M.day);return i.jsxs("div",{className:"flex flex-col",children:[i.jsx(Ts,{primary:M.runTraceId?i.jsxs(hs,{to:qt.trace(M.runTraceId),children:[E0(M.day)," run"]}):`${E0(M.day)}`,meta:L?`${L.verified} shipped · ${L.started} started · ${Tc(L.costUsd)}${L.pausedMs>0?` · paused ${Bi(L.pausedMs)}`:""}`:void 0}),M.traces.length>0&&i.jsx(fs,{limit:3,total:M.traces.length,as:"ul",className:"pl-4",children:M.traces.map(j=>i.jsxs("li",{className:"truncate py-1 text-sm",children:[i.jsx(hs,{to:qt.trace(j.traceId),className:"text-text-2 hover:text-text",children:j.summary}),j.labels.length>0&&i.jsx("span",{className:"ml-2 text-xs text-text-3",children:j.labels.join(", ")})]},j.traceId))})]},M.day)})})]})]})},_$=({files:t,selectedFile:e,expandedFolders:n,onFileSelect:s,onToggleFolder:r,level:a=0})=>i.jsx("div",{children:t.map(o=>i.jsxs("div",{children:[i.jsxs("div",{className:`file-item ${e===o.path?"file-item--selected":""}`,style:{paddingLeft:`${a*16+8}px`},onClick:()=>{o.type==="folder"?r(o.path):s(o.path)},children:[o.type==="folder"&&i.jsx("span",{className:"folder-toggle",children:n.has(o.path)?"▼":"▶"}),i.jsx("span",{className:"file-icon",children:o.icon}),i.jsx("span",{className:"file-name",children:o.name})]}),o.type==="folder"&&n.has(o.path)&&o.children&&o.children.length>0&&i.jsx(_$,{files:o.children,selectedFile:e,expandedFolders:n,onFileSelect:s,onToggleFolder:r,level:a+1})]},o.path))}),hde=({project:t,selectedFile:e,onFileSelect:n,setIsMarkdownEditorOpen:s})=>{const[r,a]=_.useState([]),[o,l]=_.useState(new Set([".crewly"])),[c,d]=_.useState(""),[u,h]=_.useState(!1),[f,p]=_.useState(null);_.useEffect(()=>{v()},[t]),_.useEffect(()=>{e?x(e):(d(""),p(null))},[e,t]);const x=async g=>{try{h(!0),p(null);const y=await fetch(`/api/projects/${t.id}/file-content?filePath=${encodeURIComponent(g)}`);if(y.ok){const b=await y.json();d(b.data.content)}else{const b=await y.json();p(b.error||"Failed to load file")}}catch(y){console.error("Error loading file content:",y),p("Failed to load file content")}finally{h(!1)}},v=async()=>{try{console.log(`Loading files for project: ${t.name} at path: ${t.path}`);const g=await fetch(`/api/projects/${t.id}/files?depth=4&includeDotFiles=true`);if(g.ok){const y=await g.json();y.success&&y.data.files?(console.log(`Loaded ${y.data.files.length} items from project directory:`),console.log(`Original path: ${y.data.projectPath}`),console.log(`Resolved path: ${y.data.resolvedPath}`),console.log("Files found:",y.data.files.map(S=>S.name).join(", ")),a(y.data.files),y.data.files.some(S=>S.name===".crewly")&&l(S=>new Set([...S,".crewly"]))):(console.error("Failed to load project files:",y.error),a([]))}else console.error("Error loading project files:",g.status),a([])}catch(g){console.error("Error loading project files:",g),a([])}},m=g=>{const y=new Set(o);y.has(g)?y.delete(g):y.add(g),l(y)};return i.jsxs("div",{className:"editor-view",children:[i.jsxs("div",{className:"file-tree-panel",children:[i.jsxs("div",{className:"file-tree-header",children:[i.jsx("h3",{children:"Project Files"}),i.jsx("div",{className:"project-path-display",children:i.jsx("small",{title:t.path,children:t.path})})]}),i.jsx("div",{className:"file-tree",children:i.jsx(_$,{files:r,selectedFile:e,expandedFolders:o,onFileSelect:n,onToggleFolder:m})})]}),i.jsx("div",{className:"editor-panel",children:e?i.jsxs("div",{className:"file-viewer",children:[i.jsx("div",{className:"file-header",children:i.jsx("h3",{children:e})}),i.jsx("div",{className:"file-content",children:u?i.jsx("div",{className:"loading-state",children:i.jsx("p",{children:"Loading file content..."})}):f?i.jsx("div",{className:"error-state",children:i.jsxs("p",{children:["Error: ",f]})}):i.jsx("pre",{className:"code-viewer",children:i.jsx("code",{children:c})})})]}):i.jsxs("div",{className:"project-info",children:[i.jsxs("div",{className:"info-header",children:[i.jsx("h3",{children:"Project Information"}),i.jsx(ue,{variant:"primary",icon:El,onClick:()=>s(!0),title:"Edit .crewly spec files",children:"Edit Specs"})]}),i.jsxs("div",{className:"info-section",children:[i.jsx("h4",{children:"Name"}),i.jsx("p",{children:t.name})]}),i.jsxs("div",{className:"info-section",children:[i.jsx("h4",{children:"Path"}),i.jsx("p",{children:t.path})]}),i.jsxs("div",{className:"info-section",children:[i.jsx("h4",{children:"Status"}),i.jsx("p",{children:t.status})]}),t.description&&i.jsxs("div",{className:"info-section",children:[i.jsx("h4",{children:"Description"}),i.jsx("p",{children:t.description})]})]})})]})};function fde(t){const e=t.members??[],n=new Set($R(t)),s=e.find(a=>n.has(a.id)),r=`${e.length} member${e.length===1?"":"s"}`;return s?`${r} · lead ${s.name}`:r}const pde=({assignedTeams:t,onUnassignTeam:e,openTerminalWithSession:n,onAssignTeam:s,onViewTeam:r,onEditTeam:a})=>i.jsxs("section",{"aria-labelledby":"project-teams-h","data-testid":"project-teams-view",children:[i.jsx("h3",{id:"project-teams-h",className:"mb-1 text-[13px] font-semibold text-text-2",children:"Teams working on this project"}),t.length>0?i.jsx("div",{className:"border-t border-border-soft",children:t.map(o=>{const l=o.members??[],c=l.some(h=>h.agentStatus==="active"),d=l.find(h=>h.sessionName),u=[...r?[{label:"View team",onClick:()=>r(o.id)}]:[],{label:"Edit team",onClick:()=>a?a(o.id):r==null?void 0:r(o.id)},...d!=null&&d.sessionName?[{label:"Open terminal",onClick:()=>n(d.sessionName)}]:[],{label:"Unassign",danger:!0,separator:!0,onClick:()=>e(o.id,o.name)}];return i.jsx(Ts,{className:"px-0","data-testid":`project-team-${o.id}`,onClick:r?()=>r(o.id):void 0,primary:o.name,meta:i.jsx("span",{title:l.map(h=>h.name).join(", ")||void 0,children:fde(o)}),trailing:i.jsx(sn,{tone:c?"success":"neutral",children:c?"Active":"Idle"}),overflow:u,overflowLabel:`More actions for ${o.name}`},o.id)})}):i.jsx(is,{className:"empty-teams",icon:vr,title:"No teams assigned",description:"Assign teams to this project to start collaborative development."}),s&&i.jsx(ue,{variant:"secondary",size:"sm",icon:QH,onClick:s,className:"mt-4",children:"Assign team"})]}),Yk="tab";function mde(t,e,n={}){return t&&e.includes(t)?t:t&&n[t]?n[t]:e[0]}function cu(t,e){const[n,s]=Lc(),r=mde(n.get(Yk),t,e),a=_.useCallback(o=>{s(l=>{const c=new URLSearchParams(l);return o===t[0]?c.delete(Yk):c.set(Yk,o),c},{replace:!0})},[s,t]);return[r,a]}const gde={detail:"Detail",editor:"Editor",tasks:"Tasks",teams:"Teams",autopilot:"Autopilot"};function xde(t){return t.replace(/^\/(Users|home)\/[^/]+/,"~")}const yde=()=>{const{id:t}=Ic(),e=bi(),n=cs(),{openTerminalWithSession:s}=uy(),{showAlert:r,showSuccess:a,showError:o,AlertComponent:l}=Yh(),{showConfirm:c,showDeleteConfirm:d,ConfirmComponent:u}=Mm(),[h,f]=cu(Dp);_.useEffect(()=>{const me=Yse(e.hash);if(!me)return;const Te=new URLSearchParams(e.search);me===Dp[0]?Te.delete("tab"):Te.set("tab",me);const He=Te.toString();n({pathname:e.pathname,search:He?`?${He}`:"",hash:""},{replace:!0})},[e.hash,e.search,e.pathname,n]);const[p,x]=_.useState(null),[v,m]=_.useState(!1),[g,y]=_.useState(!1),[b,S]=_.useState(!1),[E,k]=_.useState(!1),[T,A]=_.useState(""),[N,M]=_.useState(""),[L,j]=_.useState({isActive:!1,steps:[]}),[D,U]=_.useState({project:null,assignedTeams:[],ticketCount:0,loading:!0,error:null}),[$,G]=_.useState({hasAlignmentIssues:!1,alignmentFilePath:null,content:null}),[K,P]=_.useState(""),[B,I]=_.useState([]),F=_.useCallback(me=>{U(Te=>Te.ticketCount===me?Te:{...Te,ticketCount:me})},[]);_.useEffect(()=>{t&&ne(t)},[t]),_.useEffect(()=>{t&&h==="teams"&&ne(t,!1)},[h,t]);const q=async me=>{try{const Te=await fetch(`/api/projects/${me}/alignment-status`);if(Te.ok){const He=await Te.json();He.success&&G(He.data)}}catch(Te){console.error("Failed to check alignment status:",Te)}},H=async()=>{if(D.project)try{(await fetch(`/api/projects/${D.project.id}/continue-with-misalignment`,{method:"POST"})).ok?(a("Orchestrator notified to continue Build Specs despite alignment issues"),G({hasAlignmentIssues:!1,alignmentFilePath:null,content:null})):o("Failed to notify orchestrator")}catch(me){o("Failed to continue with misalignment: "+(me instanceof Error?me.message:"Unknown error"))}},re=async()=>{if(D.project)try{const me=await fetch(`/api/projects/${D.project.id}/specs?fileName=alignment_comparison.md`);if(me.ok){const Te=await me.json();if(Te.success&&Te.data){const He=window.open("","_blank");He&&(He.document.write(`
165
+ `)}const Ece="TKT";function Cce(t){const e=new Set;for(const n of t){const s=/^([A-Za-z0-9]+)-\d+$/.exec(n);s&&e.add(s[1].toUpperCase())}return e}function h$(t,e=new Set){const n=/\b([A-Z][A-Z0-9]{0,9})-(\d+)\b/g;for(let s=n.exec(t);s;s=n.exec(t))if(s[1]===Ece||e.has(s[1]))return s[0];return null}const f$=({open:t,ticket:e,projectId:n,projects:s,teams:r,onClose:a,onSaved:o})=>{const l=e===null,[c,d]=_.useState(()=>{var k;return vB(n??((k=s[0])==null?void 0:k.id)??"")}),[u,h]=_.useState(""),[f,p]=_.useState(!1),[x,v]=_.useState(null);_.useEffect(()=>{var k;t&&(v(null),e?(h(e.assignee??""),d({title:e.title,project:n??"",priority:e.priority,status:e.status,labels:e.labels.join(", "),description:e.description,acceptance:wce(e.acceptance),ownerReview:e.ownerReview})):d(vB(n??((k=s[0])==null?void 0:k.id)??"")))},[t,e]),_.useEffect(()=>{t&&l&&!n&&!c.project&&s.length>0&&d(k=>({...k,project:s[0].id}))},[t,l,n,c.project,s]);const m=n??c.project,g=_.useMemo(()=>{const k=r.filter(T=>(T.projectIds??[]).includes(m));return(k.length>0?k:r).flatMap(T=>(T.members??[]).map(A=>({value:A.sessionName,label:`${A.name} (${T.name})`})))},[r,m]),y=async k=>{p(!0),v(null);try{await k(),o(),a()}catch(T){v(T instanceof Error?T.message:"Request failed")}finally{p(!1)}},b=()=>{if(l){y(()=>xle(m,{title:c.title,priority:c.priority,status:c.status,labels:xB(c.labels),description:c.description,acceptance:yB(c.acceptance).map(k=>k.text),ownerReview:c.ownerReview}));return}!e||!n||y(()=>yle(n,e.id,{title:c.title,priority:c.priority,labels:xB(c.labels),description:c.description,acceptance:yB(c.acceptance,e.acceptance),ownerReview:c.ownerReview,...c.status!==e.status?{status:c.status}:{}}))},S=()=>{!e||!n||!u||y(()=>vle(n,e.id,u))},E=e?[e.status,...ple[e.status]]:["backlog","ready"];return i.jsxs(XS,{isOpen:t,onClose:a,onSubmit:b,title:e?`${e.id}: ${e.title}`:"New ticket",submitText:l?"Create ticket":"Save",loading:f,submitDisabled:!c.title.trim()||!m,size:l?void 0:"lg",children:[x&&i.jsx(Ye,{variant:"error",size:"sm",className:"mb-3",onClose:()=>v(null),children:x}),i.jsxs(hi,{children:[i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-title",required:!0,children:"Title"}),i.jsx(Dt,{id:"pt-title",value:c.title,onChange:k=>d({...c,title:k.target.value}),required:!0})]}),l&&!n&&i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-project",required:!0,children:"Project"}),i.jsxs(vn,{id:"pt-project","aria-label":"Project",value:c.project,onChange:k=>d({...c,project:k.target.value}),children:[s.length===0&&i.jsx("option",{value:"",children:"No projects yet"}),s.map(k=>i.jsx("option",{value:k.id,children:k.name},k.id))]}),i.jsx(kc,{children:"Saved in the project's .crewly/tickets/ folder. Team members pick up Ready tickets on their own."})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-priority",children:"Priority"}),i.jsx(vn,{id:"pt-priority","aria-label":"Priority",value:c.priority,onChange:k=>d({...c,priority:k.target.value}),children:mle.map(k=>i.jsx("option",{value:k,children:k},k))})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-status",children:"Status"}),i.jsx(vn,{id:"pt-status","aria-label":"Status",value:c.status,onChange:k=>d({...c,status:k.target.value}),children:E.map(k=>i.jsx("option",{value:k,children:fle[k]},k))})]})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-labels",children:"Labels"}),i.jsx(Dt,{id:"pt-labels",value:c.labels,onChange:k=>d({...c,labels:k.target.value}),placeholder:"ui, export"})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-description",children:"Description"}),i.jsx(er,{id:"pt-description",rows:5,value:c.description,onChange:k=>d({...c,description:k.target.value})})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-acceptance",children:"Acceptance criteria"}),i.jsx(er,{id:"pt-acceptance",rows:4,value:c.acceptance,onChange:k=>d({...c,acceptance:k.target.value}),placeholder:"One per line; start a line with [x] when it is met"})]}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-text",children:[i.jsx("input",{type:"checkbox",checked:c.ownerReview,onChange:k=>d({...c,ownerReview:k.target.checked})}),"I review it myself before it counts as done"]})]}),e&&i.jsxs(hi,{children:[i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"pt-assignee",children:"Assignee"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(vn,{id:"pt-assignee","aria-label":"Assignee",value:u,onChange:k=>h(k.target.value),children:[i.jsx("option",{value:"",children:"Nobody"}),g.map(k=>i.jsx("option",{value:k.value,children:k.label},k.value)),u&&!g.some(k=>k.value===u)&&i.jsx("option",{value:u,children:u})]}),i.jsx(ue,{type:"button",size:"sm",variant:"secondary",onClick:S,disabled:!u||u===e.assignee||f,children:"Assign"})]}),i.jsx(kc,{children:"Assigning a team member starts the work: they get it as a task right away."})]}),i.jsxs("div",{className:"text-xs text-text-2",children:[i.jsxs("div",{children:["File: ",i.jsx("code",{children:e.fileName}),e.workItemId&&i.jsxs(i.Fragment,{children:[" · ",i.jsxs(hs,{to:qt.run(e.workItemId),className:"text-primary-text hover:underline",children:["Run ",e.workItemId.slice(0,8)]})]})]}),e.log.length>0&&i.jsx("ul",{className:"mt-2 space-y-1","aria-label":"Ticket log",children:e.log.slice(-10).map((k,T)=>i.jsx("li",{children:k},T))})]})]})]})};function vB(t){return{title:"",project:t,priority:gle,status:"backlog",labels:"",description:"",acceptance:"",ownerReview:!1}}const YR=({value:t,onChange:e,placeholder:n,"data-testid":s})=>{const[r,a]=_.useState(t!==""),o=_.useRef(null),l=r||t!=="";return _.useEffect(()=>{var c;r&&((c=o.current)==null||c.focus())},[r]),l?i.jsxs("div",{className:"relative w-full sm:w-64",children:[i.jsx(Al,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-3","aria-hidden":"true"}),i.jsx("input",{ref:o,type:"search",value:t,onChange:c=>e(c.target.value),onKeyDown:c=>{c.key==="Escape"&&(e(""),a(!1))},onBlur:()=>{t===""&&a(!1)},placeholder:n,"aria-label":n,"data-testid":s,className:"h-9 w-full rounded-2xl border border-border bg-bg pl-9 pr-8 text-sm text-text placeholder:text-text-3 focus:border-primary-text/60 focus:outline-none"}),t!==""&&i.jsx("button",{type:"button",onClick:()=>{e(""),a(!1)},"aria-label":"Clear search",className:"absolute right-2 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-full text-text-3 hover:text-text",children:i.jsx(ys,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}):i.jsx("button",{type:"button",onClick:()=>a(!0),"aria-label":n,title:n,className:"inline-flex h-9 w-9 items-center justify-center rounded-2xl text-text-2 transition-colors hover:bg-surface-2 hover:text-text",children:i.jsx(Al,{className:"h-4 w-4","aria-hidden":"true"})})},kce=2e3,Ace=6e4;function Pm(t){const[e,n]=_.useState([]);_.useEffect(()=>{if(t)return;let a=!0,o,l=0;const c=()=>{Promise.resolve().then(()=>dt.getTeams()).then(d=>{a&&Array.isArray(d)&&n(d)}).catch(()=>{if(!a)return;const d=Math.min(kce*2**l,Ace);l+=1,o=setTimeout(c,d)})};return c(),()=>{a=!1,o&&clearTimeout(o)}},[t]);const s=t??e,r=_.useMemo(()=>Sce(s),[s]);return{teams:s,names:r}}const Tce={project:[],type:[],include:[]},p$=({projectId:t,teams:e,showNewTicket:n=!0,refreshKey:s=0,onCountsChange:r,pollIntervalMs:a=qle,now:o})=>{var Te,He;const{teams:l,names:c}=Pm(e),[d,u]=_.useState(""),[h,f]=_.useState(""),[p,x]=_.useState(Tce),[v,m]=_.useState([]),[g,y]=_.useState([]),[b,S]=_.useState(0),[E,k]=_.useState([]),[T,A]=_.useState([]),[N,M]=_.useState(!1),[L,j]=_.useState(!1),[D,U]=_.useState(null),[$,G]=_.useState(null),[K,P]=_.useState(null),[B,I]=_.useState(null),[F,q]=_.useState(!1),[H,re]=_.useState(new Set),[ne,Y]=_.useState(!1),z=_.useRef(bB()),X=_.useRef(bB()),Z=((Te=p.type)==null?void 0:Te[0])??void 0,le=t??((He=p.project)==null?void 0:He[0])??null,ye=(p.include??[]).includes("cancelled");_.useEffect(()=>{const ge=setTimeout(()=>f(d),Xle);return()=>clearTimeout(ge)},[d]);const te=t?"locked":JSON.stringify([Z??"",h.trim(),ye]),ke=t??"*";z.current.key=te,X.current.key=ke;const ie=_.useCallback(async(ge=!1)=>{if(t){M(!0);return}await _B(z.current,te,ge,async()=>{const Re={...Z?{kind:Z}:{},...h.trim()?{q:h}:{}},[Oe,de]=await Promise.allSettled([ye?cB({column:"cancelled",...Re}):Promise.resolve(null),cB(Re)]);return()=>{var _e,We,ve,Be;de.status==="fulfilled"?(m(((_e=de.value)==null?void 0:_e.tickets)??[]),S(((ve=(We=de.value)==null?void 0:We.columns)==null?void 0:ve.cancelled)??0),U(null)):U(nw(de.reason)),Oe.status==="fulfilled"&&y(((Be=Oe.value)==null?void 0:Be.tickets)??[]),M(!0)}})},[t,te,Z,h,ye]),xe=_.useCallback(async(ge=!1)=>{await _B(X.current,ke,ge,async()=>{try{const Re=t?await KR(t).then(Oe=>{var de,_e;return{groups:[{project:{id:((de=Oe.project)==null?void 0:de.id)??t,name:((_e=Oe.project)==null?void 0:_e.name)??t},tickets:Oe.tickets}],invalid:Oe.invalid}}):await s$().then(Oe=>({groups:Oe.map(de=>({project:{id:de.project.id,name:de.project.name},tickets:de.tickets})),invalid:[]}));return()=>{k(Re.groups),A(Re.invalid),G(null),j(!0)}}catch(Re){return()=>{G(nw(Re)),j(!0)}}})},[t,ke]),oe=_.useCallback(()=>{ie(),xe()},[ie,xe]);_.useEffect(()=>{ie()},[ie,s]),_.useEffect(()=>{xe()},[xe,s]);const be=_.useRef(0);_.useEffect(()=>{if(!a)return;const ge=setInterval(()=>{typeof document<"u"&&document.hidden||(be.current+=1,ie(!0),(t||be.current%Nce===0)&&xe(!0))},a),Re=()=>{document.hidden||(ie(!0),xe(!0))};return document.addEventListener("visibilitychange",Re),()=>{clearInterval(ge),document.removeEventListener("visibilitychange",Re)}},[ie,xe,a,t]);const J=N&&L,Me=[D,$].filter(Boolean).join(" · ")||null,Se=_.useMemo(()=>E.map(ge=>ge.project),[E]),we=_.useMemo(()=>{const ge=[],Re=!t&&(le===null||le===qv),Oe=!Z&&le!==qv;if(Re){for(const de of v)ge.push(pB(de,o));if(ye)for(const de of g)ge.push(pB(de,o))}if(Oe){for(const de of E)if(!(le&&de.project.id!==le))for(const _e of de.tickets){const We=mB(_e,de.project);We.column==="cancelled"&&!ye||_ce(We,h)&&ge.push(We)}}return ge},[v,g,E,t,le,Z,ye,h,o]),Ie=_.useMemo(()=>bce(we),[we]);_.useEffect(()=>{!J||!r||r({toReview:Ie.to_review.length,total:we.filter(ge=>ge.column!=="cancelled").length,unfilteredTotal:(t?0:v.length)+E.reduce((ge,Re)=>ge+Re.tickets.filter(Oe=>mB(Oe,Re.project).column!=="cancelled").length,0)})},[J,Ie,we,r,t,v,E]);const se=_.useMemo(()=>(t?0:b)+E.reduce((ge,Re)=>ge+Re.tickets.filter(Oe=>Oe.status==="cancelled").length,0),[t,b,E]),W=_.useMemo(()=>{const ge=[];return t||(ge.push({id:"project",label:ui.FILTER_PROJECT,single:!0,options:[...E.map(Re=>({value:Re.project.id,label:Re.project.name,count:Re.tickets.filter(Oe=>Oe.status!=="cancelled").length})),{value:qv,label:ui.NO_PROJECT,count:v.length}]}),ge.push({id:"type",label:ui.FILTER_TYPE,single:!0,options:d$.map(Re=>({value:Re,label:c$[Re]}))})),ge.push({id:"include",label:ui.FILTER_INCLUDE,options:[{value:"cancelled",label:ui.CANCELLED,count:se}]}),ge},[t,E,v.length,se]),ae=_.useCallback(ge=>{ge.ticket?P(ge.ticket.id):ge.projectTicket&&ge.projectId&&I({ticket:ge.projectTicket,projectId:ge.projectId})},[]),Q=ge=>re(Re=>{const Oe=new Set(Re);return Oe.has(ge)?Oe.delete(ge):Oe.add(ge),Oe}),ce=h.trim()!==""||Object.values(p).some(ge=>ge.length>0),pe=J&&we.length===0&&!ce&&!Me,je=ye?[...fB,"cancelled"]:[...fB],me=(ge,Re,Oe)=>{const de=H.has(ge),_e=de?Re:Re.slice(0,Oe);return i.jsxs(i.Fragment,{children:[_e.map(We=>i.jsx(pce,{card:We,assigneeName:Xd(We.assignee,c),onOpen:ae},We.key)),Re.length>Oe&&i.jsx("button",{type:"button",onClick:()=>Q(ge),"aria-expanded":de,className:"self-start px-0.5 py-1 text-[13px] font-semibold text-primary-text hover:underline","data-testid":`tickets-column-${ge}-more`,children:de?ui.SHOW_LESS:`Show all ${Re.length}`})]})};return i.jsxs("div",{className:"flex min-w-0 max-w-full flex-col gap-6","data-testid":"tickets-page",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(Jo,{groups:W,value:p,onChange:x}),i.jsx(YR,{value:d,onChange:u,placeholder:pn.SEARCH_PLACEHOLDER,"data-testid":"tickets-search"}),i.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":pn.REFRESH,onClick:oe}),n&&i.jsx(ue,{size:"sm",icon:qn,onClick:()=>q(!0),children:ui.NEW_TICKET})]})]}),t&&i.jsx("p",{className:"-mt-3 text-[13px] text-text-2",children:ui.PROJECT_HINT}),Z&&i.jsx("p",{className:"-mt-3 text-[13px] text-text-2",children:ui.TYPE_HIDES_PROJECT}),Me&&i.jsx(Ye,{variant:"error",size:"sm",title:pn.LOAD_FAILED,children:Me}),T.length>0&&i.jsxs(Ye,{variant:"warning",size:"sm",children:[T.length," file(s) in .crewly/tickets/ could not be read: ",T.map(ge=>`${ge.fileName} (${ge.error})`).join("; ")]}),J?pe?i.jsx(is,{icon:XH,title:t?ui.EMPTY_PROJECT_TITLE:pn.EMPTY_BOARD_TITLE,description:t?ui.EMPTY_PROJECT_DESC:pn.EMPTY_BOARD_DESC}):i.jsxs(i.Fragment,{children:[ce&&we.length===0&&i.jsx("p",{className:"text-[13px] text-text-2",children:ui.NO_MATCH}),i.jsx("div",{className:"grid min-w-0 grid-cols-1 items-start gap-6 sm:grid-cols-2 xl:grid-cols-4","data-testid":"tickets-board",children:mce.map(ge=>{const Re=Ie[ge],Oe=ge==="to_review"&&Re.length>0;return i.jsxs("section",{"aria-label":sp[ge],"data-testid":`tickets-column-${ge}`,className:Js("flex min-w-0 flex-col gap-2",Oe&&"rounded-2xl bg-attention-soft p-3"),children:[i.jsxs("header",{className:"flex items-baseline gap-2 px-0.5 pb-1",children:[i.jsx("h2",{className:Js("text-[15px] font-bold leading-snug",Oe?"text-attention":"text-text"),children:sp[ge]}),i.jsx("span",{className:"text-[13px] text-text-2","data-testid":`tickets-column-${ge}-count`,children:Re.length}),Oe&&i.jsx("span",{className:"ml-auto text-[13px] font-semibold text-attention",children:ui.NEEDS_YOU})]}),Re.length===0?i.jsx("p",{className:"px-0.5 py-3 text-[13px] text-text-3",children:lB[ge]}):me(ge,Re,gce)]},ge)})}),i.jsxs("div",{className:"flex flex-col gap-4 border-t border-border-soft pt-4",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[13px] text-text-2","data-testid":"tickets-quiet-line",children:[je.map((ge,Re)=>i.jsxs(an.Fragment,{children:[Re>0&&i.jsx("span",{className:"text-text-3",children:"·"}),i.jsxs("span",{children:[sp[ge]," ",Ie[ge].length]})]},ge)),i.jsx("span",{className:"text-text-3",children:"—"}),i.jsx("button",{type:"button",onClick:()=>Y(ge=>!ge),"aria-expanded":ne,className:"font-semibold text-primary-text hover:underline","data-testid":"tickets-quiet-toggle",children:ne?ui.HIDE:ui.SHOW})]}),ne&&je.map(ge=>i.jsxs("section",{"aria-label":sp[ge],"data-testid":`tickets-column-${ge}`,className:"flex flex-col gap-2",children:[i.jsxs("h2",{className:"text-[15px] font-bold text-text",children:[sp[ge]," ",i.jsx("span",{className:"text-[13px] font-normal text-text-2",children:Ie[ge].length})]}),Ie[ge].length===0?i.jsx("p",{className:"py-1 text-[13px] text-text-3",children:lB[ge]}):i.jsx("div",{className:"grid grid-cols-1 items-start gap-2 sm:grid-cols-2 xl:grid-cols-4",children:me(ge,Ie[ge],8)})]},ge))]})]}):i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(zt,{})}),i.jsx(hce,{ticketId:K,onClose:()=>P(null),onChanged:()=>void ie(),now:o}),i.jsx(f$,{open:F||B!==null,ticket:(B==null?void 0:B.ticket)??null,projectId:(B==null?void 0:B.projectId)??t??(le&&le!==qv?le:void 0),projects:Se,teams:l,onClose:()=>{q(!1),I(null)},onSaved:()=>void xe()})]})},Nce=4;function bB(){return{key:"",inFlight:!1,seq:0,applied:0}}async function _B(t,e,n,s){if(n&&t.inFlight)return;const r=++t.seq;t.inFlight=!0;try{const a=await s();if(t.key!==e||r<t.applied)return;t.applied=r,a()}finally{r===t.seq&&(t.inFlight=!1)}}const Mce={active:"bg-emerald-400",started:"bg-emerald-400",starting:"bg-yellow-400",activating:"bg-yellow-400",idle:"bg-yellow-400",suspended:"bg-orange-400",inactive:"bg-text-secondary-dark"},jce={orchestrator:ree,"team-leader":rR};function Rce(t){if(t.length===0)return[];const e=new Map;for(const a of t)e.set(a.id,a);const n=new Map,s=[];for(const a of t)if(!a.parentMemberId)s.push(a);else{const o=n.get(a.parentMemberId)??[];o.push(a),n.set(a.parentMemberId,o)}function r(a,o){const l=n.get(a.id)??[];return{member:a,depth:o,children:l.map(c=>r(c,o+1))}}return s.map(a=>r(a,0))}function Ice(t){return Mce[t]??"bg-text-secondary-dark"}function Lce(t){return t==="in_progress"?"Working":t.charAt(0).toUpperCase()+t.slice(1)}const JR=({node:t,expandedIds:e,onToggle:n,onNodeClick:s})=>{const{member:r,children:a,depth:o}=t,l=a.length>0,c=e.has(r.id),d=jce[r.role]??sy,u=Ice(r.agentStatus),h=Lce(r.workingStatus),f=_.useCallback(x=>{x.stopPropagation(),n(r.id)},[r.id,n]),p=_.useCallback(()=>{s==null||s(r)},[r,s]);return i.jsxs("div",{"data-testid":`tree-node-${r.id}`,children:[i.jsxs("div",{className:"flex items-center gap-2 py-1.5 px-2 rounded-md hover:bg-background-dark/50 cursor-pointer transition-colors",style:{paddingLeft:`${o*24+8}px`},onClick:p,role:"treeitem","aria-expanded":l?c:void 0,"aria-level":o+1,children:[l?i.jsx("button",{onClick:f,className:"p-0.5 rounded hover:bg-background-dark text-text-secondary-dark","aria-label":c?"Collapse":"Expand",children:c?i.jsx(wo,{size:14}):i.jsx(cr,{size:14})}):i.jsx("span",{className:"w-5"}),i.jsx(d,{size:16,className:"text-text-secondary-dark shrink-0"}),i.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${u}`,title:r.agentStatus}),i.jsx("span",{className:"text-sm font-medium text-text-primary-dark truncate",children:r.name}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:r.role}),i.jsx("span",{className:`ml-auto text-xs px-1.5 py-0.5 rounded-full ${r.workingStatus==="in_progress"?"bg-blue-500/10 text-blue-400":"bg-background-dark text-text-secondary-dark"}`,children:h})]}),l&&c&&i.jsx("div",{role:"group",children:a.map(x=>i.jsx(JR,{node:x,expandedIds:e,onToggle:n,onNodeClick:s},x.member.id))})]})};JR.displayName="TreeNode";const m$=({members:t,onNodeClick:e,className:n=""})=>{const[s,r]=_.useState(()=>{const l=new Set;for(const c of t)(c.canDelegate||c.role==="team-leader"||c.role==="orchestrator")&&l.add(c.id);return l}),a=_.useCallback(l=>{r(c=>{const d=new Set(c);return d.has(l)?d.delete(l):d.add(l),d})},[]),o=_.useMemo(()=>Rce(t),[t]);return t.length===0?i.jsx("div",{className:`text-sm text-text-secondary-dark p-4 ${n}`,children:"No team members to display."}):i.jsx("div",{className:`${n}`,role:"tree","aria-label":"Team hierarchy",children:o.map(l=>i.jsx(JR,{node:l,expandedIds:s,onToggle:a,onNodeClick:e},l.member.id))})};m$.displayName="HierarchyTreeView";function Pce(t){let e=0,n=0,s=0,r=0;for(const a of t)a.agentStatus==="active"||a.agentStatus==="started"?e++:a.agentStatus==="inactive"&&n++,a.workingStatus==="in_progress"&&s++,a.hierarchyLevel!==void 0&&a.hierarchyLevel>r&&(r=a.hierarchyLevel);return{total:t.length,active:e,idle:t.length-e-n,inactive:n,working:s,hierarchyDepth:r+1}}const rp=({label:t,value:e,icon:n,color:s})=>i.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-border-dark p-3 bg-background-dark/30",children:[i.jsx("div",{className:`p-2 rounded-md ${s}`,children:i.jsx(n,{size:16})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-lg font-semibold text-text-primary-dark",children:e}),i.jsx("p",{className:"text-xs text-text-secondary-dark",children:t})]})]});rp.displayName="StatCard";const g$=({member:t,onClick:e})=>{const n=t.agentStatus==="active"||t.agentStatus==="started"?"bg-emerald-400":t.agentStatus==="inactive"?"bg-text-secondary-dark":"bg-yellow-400";return i.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-border-dark p-3 hover:bg-background-dark/50 cursor-pointer transition-colors",onClick:()=>e==null?void 0:e(t),"data-testid":`flat-member-${t.id}`,children:[i.jsx("span",{className:`w-2.5 h-2.5 rounded-full shrink-0 ${n}`}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-sm font-medium text-text-primary-dark truncate",children:t.name}),i.jsx("p",{className:"text-xs text-text-secondary-dark",children:t.role})]}),i.jsx("span",{className:`ml-auto text-xs px-1.5 py-0.5 rounded-full ${t.workingStatus==="in_progress"?"bg-blue-500/10 text-blue-400":"bg-background-dark text-text-secondary-dark"}`,children:t.workingStatus==="in_progress"?"Working":"Idle"})]})};g$.displayName="FlatMemberCard";const x$=({team:t,onMemberClick:e,className:n=""})=>{const s=_.useMemo(()=>Pce(t.members),[t.members]),r=t.hierarchical===!0;return i.jsxs("div",{className:`space-y-4 ${n}`,"data-testid":"hierarchy-dashboard",children:[i.jsx("div",{className:"flex items-center justify-between",children:i.jsxs("div",{className:"flex items-center gap-2",children:[r?i.jsx(x0,{size:18,className:"text-primary"}):i.jsx(vr,{size:18,className:"text-primary"}),i.jsx("h3",{className:"text-lg font-semibold text-text-primary-dark",children:t.name}),r&&i.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-primary/10 text-primary border border-primary/20",children:"Hierarchical"})]})}),i.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3","data-testid":"stats-row",children:[i.jsx(rp,{label:"Total",value:s.total,icon:vr,color:"bg-blue-500/10 text-blue-400"}),i.jsx(rp,{label:"Active",value:s.active,icon:lu,color:"bg-emerald-500/10 text-emerald-400"}),i.jsx(rp,{label:"Working",value:s.working,icon:Lh,color:"bg-primary/10 text-primary"}),r?i.jsx(rp,{label:"Depth",value:s.hierarchyDepth,icon:x0,color:"bg-primary/10 text-primary"}):i.jsx(rp,{label:"Inactive",value:s.inactive,icon:vr,color:"bg-text-secondary-dark/10 text-text-secondary-dark"})]}),r?i.jsx("div",{className:"rounded-lg border border-border-dark p-3","data-testid":"hierarchy-view",children:i.jsx(m$,{members:t.members,onNodeClick:e})}):i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2","data-testid":"flat-view",children:t.members.length===0?i.jsx("p",{className:"text-sm text-text-secondary-dark col-span-2 p-4",children:"No team members."}):t.members.map(a=>i.jsx(g$,{member:a,onClick:e},a.id))})]})};x$.displayName="HierarchyDashboard";function Dce(t){return t.filter(e=>e.role!=="orchestrator")}const y$=({config:t,onChange:e,members:n,className:s=""})=>{const r=Dce(n),a=t.leaderIds??(t.leaderId?[t.leaderId]:[]),o=_.useCallback(()=>{e({hierarchical:!t.hierarchical,leaderId:t.hierarchical?null:t.leaderId,leaderIds:t.hierarchical?[]:t.leaderIds})},[t,e]),l=_.useCallback(c=>{const u=a.includes(c)?a.filter(h=>h!==c):[...a,c];e({...t,leaderIds:u,leaderId:u[0]??null})},[t,a,e]);return i.jsxs("div",{className:`rounded-lg border border-border-dark p-4 ${s}`,"data-testid":"hierarchy-mode-config",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:i.jsx(vr,{size:18,className:"text-primary"})}),i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-text-primary-dark",children:"Hierarchical Mode"}),i.jsx("p",{className:"text-xs text-text-secondary-dark",children:"Enable Team Leader management with delegation"})]})]}),i.jsx(Gi,{size:"lg",role:"switch","aria-checked":t.hierarchical,"aria-label":"Toggle hierarchical mode",checked:t.hierarchical,onChange:o})]}),t.hierarchical&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-border-dark",children:[i.jsxs("label",{className:"flex items-center gap-2 text-sm font-medium text-text-primary-dark mb-2",children:[i.jsx(rR,{size:14,className:"text-text-secondary-dark"}),"Team Leaders",i.jsx("span",{className:"text-xs font-normal text-text-secondary-dark",children:"(select one or more)"})]}),r.length===0?i.jsx("p",{className:"text-xs text-text-secondary-dark","data-testid":"no-leaders-message",children:"Add team members first, then select leaders."}):i.jsx("div",{className:"flex flex-wrap gap-2","data-testid":"leader-select",children:r.map(c=>{const d=a.includes(c.id),u=a[0]===c.id;return i.jsxs("button",{type:"button",onClick:()=>l(c.id),className:`inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border transition-colors ${d?"bg-primary/15 border-primary/40 text-primary":"bg-background-dark border-border-dark text-text-secondary-dark hover:border-primary/50 hover:text-text-primary-dark"}`,"data-testid":`leader-toggle-${c.id}`,children:[d&&i.jsx(rs,{className:"w-3 h-3"}),c.name," (",c.role,")",u&&d&&i.jsx("span",{className:"text-[10px] bg-primary/20 px-1 rounded",children:"Primary"})]},c.id)})}),a.length>0&&i.jsxs("div",{className:"mt-3 p-3 rounded-md bg-background-dark/50","data-testid":"hierarchy-preview",children:[i.jsx("p",{className:"text-xs text-text-secondary-dark mb-2",children:"Hierarchy preview:"}),a.map(c=>{const d=n.find(h=>h.id===c),u=n.filter(h=>!a.includes(h.id)&&h.role!=="orchestrator").length;return i.jsxs("div",{className:"flex items-center gap-1 text-xs text-text-primary-dark mb-1",children:[i.jsx("span",{className:"font-medium",children:"Orchestrator"}),i.jsx(cr,{size:12,className:"text-text-secondary-dark"}),i.jsx("span",{className:"font-medium text-primary",children:(d==null?void 0:d.name)??"TL"}),a.length===1&&i.jsxs(i.Fragment,{children:[i.jsx(cr,{size:12,className:"text-text-secondary-dark"}),i.jsxs("span",{className:"text-text-secondary-dark",children:[u," workers"]})]})]},c)}),a.length>1&&i.jsx("div",{className:"flex items-center gap-1 text-xs text-text-secondary-dark mt-1",children:i.jsxs("span",{children:[n.filter(c=>!a.includes(c.id)&&c.role!=="orchestrator").length," workers (assign via member parentMemberId)"]})})]})]})]})};y$.displayName="HierarchyModeConfig";const Oce={completed:vo,assigned:jr,active:VS,working:VS,submitted:jH,input_required:$i,verifying:vee,blocked:$i,failed:qd,cancelled:qd,pending_assignment:jr},Bce={completed:"text-emerald-400",assigned:"text-yellow-400",active:"text-blue-400",working:"text-blue-400",submitted:"text-primary",input_required:"text-orange-400",verifying:"text-cyan-400",blocked:"text-orange-400",failed:"text-red-400",cancelled:"text-text-secondary-dark",pending_assignment:"text-text-secondary-dark"},Fce={high:"bg-red-500/10 text-red-400 border-red-500/20",medium:"bg-yellow-500/10 text-yellow-400 border-yellow-500/20",low:"bg-text-secondary-dark/10 text-text-secondary-dark border-border-dark"};function Uce(t){if(t.length===0)return[];const e=new Map,n=[];for(const r of t)if(!r.parentTaskId)n.push(r);else{const a=e.get(r.parentTaskId)??[];a.push(r),e.set(r.parentTaskId,a)}function s(r,a){const o=e.get(r.id)??[];return{task:r,depth:a,children:o.map(l=>s(l,a+1))}}return n.map(r=>s(r,0))}function zce(t){return{completed:"Completed",assigned:"Assigned",active:"Active",working:"Working",submitted:"Submitted",input_required:"Input Required",verifying:"Verifying",blocked:"Blocked",failed:"Failed",cancelled:"Cancelled",pending_assignment:"Pending"}[t]??t}function Hce(t){if(t.children.length===0)return t.task.status==="completed"?100:0;const e=t.children.filter(n=>n.task.status==="completed").length;return Math.round(e/t.children.length*100)}const ZR=({node:t,expandedIds:e,onToggle:n,onTaskClick:s})=>{const{task:r,children:a,depth:o}=t,l=a.length>0,c=e.has(r.id),d=Oce[r.status]??jH,u=Bce[r.status]??"text-text-secondary-dark",h=zce(r.status),f=_.useCallback(v=>{v.stopPropagation(),n(r.id)},[r.id,n]),p=_.useCallback(()=>{s==null||s(r)},[r,s]),x=l?Hce(t):null;return i.jsxs("div",{"data-testid":`task-node-${r.id}`,children:[i.jsxs("div",{className:"flex items-center gap-2 py-1.5 px-2 rounded-md hover:bg-background-dark/50 cursor-pointer transition-colors",style:{paddingLeft:`${o*24+8}px`},onClick:p,role:"treeitem","aria-expanded":l?c:void 0,"aria-level":o+1,children:[l?i.jsx("button",{onClick:f,className:"p-0.5 rounded hover:bg-background-dark text-text-secondary-dark","aria-label":c?"Collapse":"Expand",children:c?i.jsx(wo,{size:14}):i.jsx(cr,{size:14})}):i.jsx("span",{className:"w-5"}),i.jsx(d,{size:16,className:`shrink-0 ${u}`}),i.jsx("span",{className:"text-sm font-medium text-text-primary-dark truncate",children:r.taskName}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:r.assignedSessionName}),r.priority&&i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full border ${Fce[r.priority]??""}`,children:r.priority}),i.jsxs("span",{className:`ml-auto text-xs ${u}`,children:[h,x!==null&&` (${x}%)`]})]}),l&&c&&i.jsx("div",{role:"group",children:a.map(v=>i.jsx(ZR,{node:v,expandedIds:e,onToggle:n,onTaskClick:s},v.task.id))})]})};ZR.displayName="TaskNode";const v$=({tasks:t,onTaskClick:e,className:n=""})=>{const[s,r]=_.useState(()=>{const l=new Set;for(const c of t)c.childTaskIds&&c.childTaskIds.length>0&&l.add(c.id);return l}),a=_.useCallback(l=>{r(c=>{const d=new Set(c);return d.has(l)?d.delete(l):d.add(l),d})},[]),o=_.useMemo(()=>Uce(t),[t]);return t.length===0?i.jsx("div",{className:`text-sm text-text-secondary-dark p-4 ${n}`,children:"No tasks to display."}):i.jsx("div",{className:`${n}`,role:"tree","aria-label":"Task flow",children:o.map(l=>i.jsx(ZR,{node:l,expandedIds:s,onToggle:a,onTaskClick:e},l.task.id))})};v$.displayName="TaskFlowView";class Gce{constructor(){Fn(this,"cache",null);Fn(this,"lastCacheTime",0);Fn(this,"cacheTimeout",3e4)}async getInProgressTasks(){var n,s;const e=Date.now();if(this.cache&&e-this.lastCacheTime<this.cacheTimeout)return this.cache.tasks;try{const r=await fetch("/api/in-progress-tasks");if(!r.ok)return console.warn("Failed to fetch in-progress tasks:",r.statusText),((n=this.cache)==null?void 0:n.tasks)||[];const a=await r.json();return this.cache=a,this.lastCacheTime=e,a.tasks}catch(r){return console.error("Error loading in-progress tasks:",r),((s=this.cache)==null?void 0:s.tasks)||[]}}async getTaskAssignedMember(e){return(await this.getInProgressTasks()).find(s=>{var r;return s.taskPath===e||s.originalPath===e||e.includes(s.taskName)||s.originalPath.includes(((r=e.split("/").pop())==null?void 0:r.replace(".md",""))||"")})||null}async getTaskAssignedMemberDetails(e){try{const n=await this.getTaskAssignedMember(e);if(!n)return{};const s=await dt.getTeams();for(const r of s)if(r.members){const a=r.members.find(o=>o.id===n.assignedMemberId||o.sessionName===n.assignedSessionName);if(a)return{memberName:a.name,sessionName:a.sessionName||n.assignedSessionName,teamName:r.name}}return{sessionName:n.assignedSessionName}}catch(n){return console.error("Error getting task assigned member details:",n),{}}}clearCache(){this.cache=null,this.lastCacheTime=0}}const $ce=new Gce;function Wce(t){return t.map(e=>{var n,s;return{id:e.id,taskName:e.taskName||((s=(n=e.taskPath)==null?void 0:n.split("/").pop())==null?void 0:s.replace(".md",""))||e.id,status:e.status||"assigned",assignedSessionName:e.assignedSessionName||"",assignedTeamMemberId:e.assignedTeamMemberId||e.assignedMemberId||"",parentTaskId:e.parentTaskId,childTaskIds:e.childTaskIds,delegatedBy:e.delegatedBy,delegatedBySession:e.delegatedBySession,assigneeHierarchyLevel:e.assigneeHierarchyLevel,priority:e.priority,completedAt:e.completedAt,assignedAt:e.assignedAt||""}})}const Vce=({project:t,teams:e,onCountChange:n})=>{const[s,r]=_.useState([]);return _.useEffect(()=>{let a=!1;return(async()=>{try{const o=await $ce.getInProgressTasks();a||r(Wce(o))}catch{a||r([])}})(),()=>{a=!0}},[]),i.jsxs("div",{"data-testid":"project-tasks-tab",children:[s.length>0&&i.jsx(ti,{title:`Task Flow (${s.length} active)`,summary:"Who delegated what to whom",className:"mb-4 border-t-0 pt-0",unmountWhenClosed:!0,"data-testid":"project-task-flow",children:i.jsx(v$,{tasks:s})}),i.jsx(p$,{projectId:t.id,teams:e,onCountsChange:({unfilteredTotal:a})=>n==null?void 0:n(a)})]})},iE="/api/project-ticket-autopilot";class Kce extends Error{constructor(e,n){super(e),this.status=n,this.name="AutopilotApiError"}}async function aE(t,e){const n=e?await fetch(t,e):await fetch(t);let s={};try{s=await n.json()}catch{s={}}if(!n.ok||s.success===!1)throw new Kce(s.error||`HTTP ${n.status}`,n.status);return s.data}function b$(t,e){const n=new URLSearchParams({days:String(t)});return e&&n.set("label",e),`?${n.toString()}`}function qce(t,e,n=null){return aE(`${iE}/${encodeURIComponent(t)}/stats${b$(e,n)}`)}async function Xce(t,e,n=null){return(await aE(`${iE}/${encodeURIComponent(t)}/runs${b$(e,n)}`)).days}function Yce(t){return aE(`${iE}/${encodeURIComponent(t)}`)}function Jce(t,e){return aE(`${iE}/${encodeURIComponent(t)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({speedMode:e})})}function Bi(t){const e=Math.floor(Math.max(0,t)/6e4);if(e<1)return"<1m";const n=Math.floor(e/1440),s=Math.floor(e%1440/60),r=e%60;return n>0?s>0?`${n}d ${s}h`:`${n}d`:s>0?r>0?`${s}h ${r}m`:`${s}h`:`${r}m`}function S0(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${Math.round(t/1e3)}k`:String(Math.round(t))}function Tc(t){return t>0&&t<.01?"<$0.01":`$${t.toFixed(2)}`}function w0(t,e=new Date){const n=new Date(t);if(Number.isNaN(n.getTime()))return"";const s=n.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});return n.toDateString()===e.toDateString()?s:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${s}`}const QR={runtime_quota:"runtime out of usage or signed out",delivery_failure:"a message was not delivered",waiting_on_owner:"waiting on you",waiting_on_agent:"waiting on an agent",nobody_pushing:"nobody pushing"},Zce={done:"Done",cancelled:"Cancelled",failed:"Failed",waiting_on_owner:"Waiting on you",in_progress:"In progress",no_open_work:"Nothing open"},Qce={"trace.root":"Started","trace.truncated":"Trace full","request.created":"Ticket created","request.status":"Ticket status","ticket.created":"Project ticket","workitem.created":"Work item","workitem.status":"Work item status","turn.delivered":"Delivered","turn.error":"Turn failed","turn.ended":"Turn ended","message.agent":"Agent message","skill.call":"Skill call","guard.block":"Refused",error:"Error","message.outbound":"Reply","status.routed":"Status report","decision.created":"Decision asked","decision.status":"Decision","harness.redelivery":"Redelivered","harness.wake":"Woken","harness.correction":"Corrected","harness.nudge":"Nudged","harness.recover":"Recovered","harness.subagent_sendback":"Subagent sent back","experiment.event":"Experiment",usage:"Tokens","runtime.blocked":"Runtime blocked","owner.action":"Your action","autopilot.action":"Autopilot","ticket.status":"Ticket status"};function ede(t){return Qce[t]??t}const SB=new Set(["skill.call","usage","turn.ended"]);function tde(t){return t.actor.kind==="owner"?"You":t.actor.kind==="agent"?t.actor.session??"Agent":"Crewly"}const nde=["7","14","30"],sde=[{key:"rush",label:"Rush"},{key:"normal",label:"Normal"},{key:"chill",label:"Chill"}],rde={rush:"Replans whenever the queue runs dry (≥ 1 h apart, ≤ 12 a day), self-review hourly, retries an empty replan after 1 h.",normal:"Replans when the queue runs dry (≥ 3 h apart, ≤ 4 a day), self-review daily, retries an empty replan the next day.",chill:"At most 1 replan a day, self-review weekly, retries an empty replan the next week."},ide="Rush keeps the team busy all day and can use the whole daily budget every day; the budget brake still stops it.";function wB(t){if(!(t!=null&&t.stopReason)||!t.stopReasonText)return null;const e=t.stoppedSince?new Date(t.stoppedSince).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):null;return`Stopped: ${t.stopReasonText}${e?` (since ${e})`:""}`}const Xk="__all__";function ade(t,e){const n=t.total,s=[`${n.verified} ticket${n.verified===1?"":"s"} shipped`];return n.verified>0?(s.push(`${Math.round(n.ownerTouches.total/n.verified*10)/10} owner touches per ticket`),s.push(`${Tc(n.costUsd/n.verified)} per shipped ticket`)):s.push(`${n.started} started`),`Last ${e} days${t.label?` (${t.label})`:""}: ${s.join(" · ")}`}function ode(t){return t.settings.enabled?t.pausedForToday?{label:"Paused on budget today",tone:"attention"}:{label:"On",tone:"success"}:{label:"Off",tone:"neutral"}}function lde(t,e=3){return Object.entries(t.total.stalls.byCause).filter(([,n])=>n.count>0).sort((n,s)=>s[1].ms-n[1].ms||s[1].count-n[1].count).slice(0,e).map(([n,s])=>({cause:n,count:s.count,ms:s.ms}))}function E0(t){const[e,n,s]=t.split("-").map(Number);return new Date(e,n-1,s).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function cde(t){return`${E0(t.day)}: ${t.verified} shipped, ${t.started} started, ${t.done} done, ${t.sentBack} sent back, ${Tc(t.costUsd)}${t.pausedMs>0?`, paused ${Bi(t.pausedMs)}`:""}`}const dde=({days:t})=>{const e=Math.max(1,...t.map(n=>n.verified));return i.jsxs("div",{className:"overflow-x-auto","data-testid":"autopilot-day-bars",children:[i.jsx("div",{className:"flex items-end gap-[2px] h-24 min-w-full",role:"img","aria-label":"Tickets shipped per day",children:t.map(n=>i.jsx("div",{className:"flex flex-1 min-w-[10px] h-full flex-col justify-end",title:cde(n),"data-testid":`autopilot-bar-${n.day}`,children:i.jsx("div",{className:n.verified>0?"bg-primary rounded-t":"bg-muted-dot rounded-t",style:{height:n.verified>0?`${Math.max(8,n.verified/e*100)}%`:"2px"}})},n.day))}),i.jsxs("div",{className:"mt-1 flex justify-between text-xs text-text-3",children:[i.jsx("span",{children:t[0]?E0(t[0].day):""}),i.jsx("span",{children:t.length?E0(t[t.length-1].day):""})]})]})},nd=({label:t,value:e,attention:n})=>i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:`text-lg font-semibold ${n?"text-attention":"text-text"}`,children:e}),i.jsx("div",{className:"text-xs text-text-3 truncate",children:t})]}),ude=({projectId:t})=>{const[e,n]=_.useState("14"),[s,r]=_.useState(Xk),[a,o]=_.useState(null),[l,c]=_.useState([]),[d,u]=_.useState(null),[h,f]=_.useState(!0),[p,x]=_.useState(null),[v,m]=_.useState(null),[g,y]=_.useState(!1);_.useEffect(()=>{let M=!1;return Yce(t).then(L=>{M||x(L)}).catch(()=>{M||x(null)}),()=>{M=!0}},[t]);const b=M=>{g||(p==null?void 0:p.speedMode)===M||(y(!0),m(null),Jce(t,M).then(L=>x(L)).catch(L=>m(L instanceof Error?L.message:String(L))).finally(()=>y(!1)))};_.useEffect(()=>{let M=!1;f(!0);const L=Number(e),j=s===Xk?null:s;return Promise.all([qce(t,L,j),Xce(t,L,j)]).then(([D,U])=>{M||(o(D),c(U),u(null))}).catch(D=>{M||u(D instanceof Error?D.message:String(D))}).finally(()=>{M||f(!1)}),()=>{M=!0}},[t,e,s]);const S=_.useMemo(()=>[{key:Xk,label:"All tickets"},...((a==null?void 0:a.labels)??[]).map(M=>({key:M,label:M}))],[a==null?void 0:a.labels]);if(d)return i.jsx(is,{icon:m0,title:"Autopilot numbers are not available",description:d});if(!a)return h?i.jsx("div",{className:"p-4 text-sm text-text-3",children:"Loading…"}):null;const E=Number(e),k=l.filter(M=>M.runTraceId||M.traces.length>0),T=a.total;if(!a.settings.enabled&&k.length===0)return i.jsx(is,{icon:m0,title:"Autopilot is off",description:"When the ticket autopilot drives this project, its daily runs, what shipped and where it stalled show here."});const A=ode(a),N=lde(a);return i.jsxs("div",{className:"flex flex-col gap-4 pb-6","data-testid":"autopilot-tab",children:[i.jsxs("section",{className:"rounded-[var(--crewly-radius)] border border-border bg-surface p-4",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(sn,{tone:A.tone,children:A.label}),i.jsx("h2",{className:"text-[15px] font-semibold text-text min-w-0","data-testid":"autopilot-headline",children:ade(a,E)})]}),p&&i.jsxs("div",{className:"mt-3 flex flex-col gap-1","data-testid":"autopilot-speed",children:[i.jsx(q_,{label:"Speed",options:sde.map(M=>({key:M.key,label:M.label})),value:p.speedMode,onChange:M=>b(M),testIdPrefix:"autopilot-speed"}),i.jsx("p",{className:"text-xs text-text-3",children:rde[p.speedMode]}),p.speedMode==="rush"&&i.jsx("p",{className:"text-xs text-attention","data-testid":"autopilot-rush-warning",children:ide}),v&&i.jsx("p",{className:"text-xs text-attention",children:v}),wB(p)&&i.jsx("p",{className:"text-sm text-attention","data-testid":"autopilot-stop",children:wB(p)}),p.lastSelfReview&&i.jsxs("p",{className:"text-sm text-text-2 break-words","data-testid":"autopilot-self-review",children:["Self-review: ",p.lastSelfReview.gap," · next bet: ",p.lastSelfReview.nextBet]})]}),i.jsxs("div",{className:"mt-3 flex flex-wrap gap-3",children:[i.jsx(q_,{label:"Range",options:nde.map(M=>({key:M,label:`${M} days`})),value:e,onChange:M=>n(M),testIdPrefix:"autopilot-range"}),S.length>1&&i.jsx(q_,{label:"Label",options:S,value:s,onChange:r,testIdPrefix:"autopilot-label"})]})]}),i.jsxs("section",{className:"rounded-[var(--crewly-radius)] border border-border bg-surface p-4",children:[i.jsx("h3",{className:"mb-2 text-[13px] font-semibold text-text-2",children:"Shipped per day"}),i.jsx(dde,{days:a.days}),i.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-3 sm:grid-cols-4",children:[i.jsx(nd,{label:"Started",value:String(T.started)}),i.jsx(nd,{label:"Sent back",value:String(T.sentBack),attention:T.sentBack>0}),i.jsx(nd,{label:"Your touches",value:String(T.ownerTouches.total)}),i.jsx(nd,{label:"Cycle time (median)",value:T.cycleTime.toVerified.medianMs===null?"—":Bi(T.cycleTime.toVerified.medianMs)}),i.jsx(nd,{label:"Harness interventions",value:String(T.interventions.total)}),i.jsx(nd,{label:"Cost",value:Tc(T.costUsd)}),i.jsx(nd,{label:"Team tokens / budget",value:`${S0(T.budget.ledgerTokens)} / ${S0(T.budget.dailyBudgetTokens)}`,attention:T.budget.pct>=1}),i.jsx(nd,{label:"Paused on budget",value:T.pausedMs>0?Bi(T.pausedMs):"—",attention:T.pausedMs>0})]})]}),i.jsxs("section",{className:"rounded-[var(--crewly-radius)] border border-border bg-surface p-4","data-testid":"autopilot-stalls",children:[i.jsx("h3",{className:"mb-2 text-[13px] font-semibold text-text-2",children:"Where it stalled"}),N.length===0?i.jsx("p",{className:"text-sm text-text-3",children:"No stalls in this range."}):i.jsx("ul",{className:"flex flex-col gap-1",children:N.map(M=>i.jsxs("li",{className:"flex flex-wrap justify-between gap-2 text-sm",children:[i.jsx("span",{className:"text-text",children:QR[M.cause]}),i.jsxs("span",{className:"text-text-3",children:[M.count," × · ",Bi(M.ms)]})]},M.cause))})]}),i.jsxs("section",{className:"rounded-[var(--crewly-radius)] border border-border bg-surface p-2","data-testid":"autopilot-runs",children:[i.jsx("h3",{className:"px-2 pb-1 pt-2 text-[13px] font-semibold text-text-2",children:"Runs"}),k.length===0?i.jsx("p",{className:"px-2 pb-2 text-sm text-text-3",children:"No autopilot runs in this range."}):i.jsx(fs,{limit:5,total:k.length,children:k.map(M=>{const L=a.days.find(j=>j.day===M.day);return i.jsxs("div",{className:"flex flex-col",children:[i.jsx(Ts,{primary:M.runTraceId?i.jsxs(hs,{to:qt.trace(M.runTraceId),children:[E0(M.day)," run"]}):`${E0(M.day)}`,meta:L?`${L.verified} shipped · ${L.started} started · ${Tc(L.costUsd)}${L.pausedMs>0?` · paused ${Bi(L.pausedMs)}`:""}`:void 0}),M.traces.length>0&&i.jsx(fs,{limit:3,total:M.traces.length,as:"ul",className:"pl-4",children:M.traces.map(j=>i.jsxs("li",{className:"truncate py-1 text-sm",children:[i.jsx(hs,{to:qt.trace(j.traceId),className:"text-text-2 hover:text-text",children:j.summary}),j.labels.length>0&&i.jsx("span",{className:"ml-2 text-xs text-text-3",children:j.labels.join(", ")})]},j.traceId))})]},M.day)})})]})]})},_$=({files:t,selectedFile:e,expandedFolders:n,onFileSelect:s,onToggleFolder:r,level:a=0})=>i.jsx("div",{children:t.map(o=>i.jsxs("div",{children:[i.jsxs("div",{className:`file-item ${e===o.path?"file-item--selected":""}`,style:{paddingLeft:`${a*16+8}px`},onClick:()=>{o.type==="folder"?r(o.path):s(o.path)},children:[o.type==="folder"&&i.jsx("span",{className:"folder-toggle",children:n.has(o.path)?"▼":"▶"}),i.jsx("span",{className:"file-icon",children:o.icon}),i.jsx("span",{className:"file-name",children:o.name})]}),o.type==="folder"&&n.has(o.path)&&o.children&&o.children.length>0&&i.jsx(_$,{files:o.children,selectedFile:e,expandedFolders:n,onFileSelect:s,onToggleFolder:r,level:a+1})]},o.path))}),hde=({project:t,selectedFile:e,onFileSelect:n,setIsMarkdownEditorOpen:s})=>{const[r,a]=_.useState([]),[o,l]=_.useState(new Set([".crewly"])),[c,d]=_.useState(""),[u,h]=_.useState(!1),[f,p]=_.useState(null);_.useEffect(()=>{v()},[t]),_.useEffect(()=>{e?x(e):(d(""),p(null))},[e,t]);const x=async g=>{try{h(!0),p(null);const y=await fetch(`/api/projects/${t.id}/file-content?filePath=${encodeURIComponent(g)}`);if(y.ok){const b=await y.json();d(b.data.content)}else{const b=await y.json();p(b.error||"Failed to load file")}}catch(y){console.error("Error loading file content:",y),p("Failed to load file content")}finally{h(!1)}},v=async()=>{try{console.log(`Loading files for project: ${t.name} at path: ${t.path}`);const g=await fetch(`/api/projects/${t.id}/files?depth=4&includeDotFiles=true`);if(g.ok){const y=await g.json();y.success&&y.data.files?(console.log(`Loaded ${y.data.files.length} items from project directory:`),console.log(`Original path: ${y.data.projectPath}`),console.log(`Resolved path: ${y.data.resolvedPath}`),console.log("Files found:",y.data.files.map(S=>S.name).join(", ")),a(y.data.files),y.data.files.some(S=>S.name===".crewly")&&l(S=>new Set([...S,".crewly"]))):(console.error("Failed to load project files:",y.error),a([]))}else console.error("Error loading project files:",g.status),a([])}catch(g){console.error("Error loading project files:",g),a([])}},m=g=>{const y=new Set(o);y.has(g)?y.delete(g):y.add(g),l(y)};return i.jsxs("div",{className:"editor-view",children:[i.jsxs("div",{className:"file-tree-panel",children:[i.jsxs("div",{className:"file-tree-header",children:[i.jsx("h3",{children:"Project Files"}),i.jsx("div",{className:"project-path-display",children:i.jsx("small",{title:t.path,children:t.path})})]}),i.jsx("div",{className:"file-tree",children:i.jsx(_$,{files:r,selectedFile:e,expandedFolders:o,onFileSelect:n,onToggleFolder:m})})]}),i.jsx("div",{className:"editor-panel",children:e?i.jsxs("div",{className:"file-viewer",children:[i.jsx("div",{className:"file-header",children:i.jsx("h3",{children:e})}),i.jsx("div",{className:"file-content",children:u?i.jsx("div",{className:"loading-state",children:i.jsx("p",{children:"Loading file content..."})}):f?i.jsx("div",{className:"error-state",children:i.jsxs("p",{children:["Error: ",f]})}):i.jsx("pre",{className:"code-viewer",children:i.jsx("code",{children:c})})})]}):i.jsxs("div",{className:"project-info",children:[i.jsxs("div",{className:"info-header",children:[i.jsx("h3",{children:"Project Information"}),i.jsx(ue,{variant:"primary",icon:El,onClick:()=>s(!0),title:"Edit .crewly spec files",children:"Edit Specs"})]}),i.jsxs("div",{className:"info-section",children:[i.jsx("h4",{children:"Name"}),i.jsx("p",{children:t.name})]}),i.jsxs("div",{className:"info-section",children:[i.jsx("h4",{children:"Path"}),i.jsx("p",{children:t.path})]}),i.jsxs("div",{className:"info-section",children:[i.jsx("h4",{children:"Status"}),i.jsx("p",{children:t.status})]}),t.description&&i.jsxs("div",{className:"info-section",children:[i.jsx("h4",{children:"Description"}),i.jsx("p",{children:t.description})]})]})})]})};function fde(t){const e=t.members??[],n=new Set($R(t)),s=e.find(a=>n.has(a.id)),r=`${e.length} member${e.length===1?"":"s"}`;return s?`${r} · lead ${s.name}`:r}const pde=({assignedTeams:t,onUnassignTeam:e,openTerminalWithSession:n,onAssignTeam:s,onViewTeam:r,onEditTeam:a})=>i.jsxs("section",{"aria-labelledby":"project-teams-h","data-testid":"project-teams-view",children:[i.jsx("h3",{id:"project-teams-h",className:"mb-1 text-[13px] font-semibold text-text-2",children:"Teams working on this project"}),t.length>0?i.jsx("div",{className:"border-t border-border-soft",children:t.map(o=>{const l=o.members??[],c=l.some(h=>h.agentStatus==="active"),d=l.find(h=>h.sessionName),u=[...r?[{label:"View team",onClick:()=>r(o.id)}]:[],{label:"Edit team",onClick:()=>a?a(o.id):r==null?void 0:r(o.id)},...d!=null&&d.sessionName?[{label:"Open terminal",onClick:()=>n(d.sessionName)}]:[],{label:"Unassign",danger:!0,separator:!0,onClick:()=>e(o.id,o.name)}];return i.jsx(Ts,{className:"px-0","data-testid":`project-team-${o.id}`,onClick:r?()=>r(o.id):void 0,primary:o.name,meta:i.jsx("span",{title:l.map(h=>h.name).join(", ")||void 0,children:fde(o)}),trailing:i.jsx(sn,{tone:c?"success":"neutral",children:c?"Active":"Idle"}),overflow:u,overflowLabel:`More actions for ${o.name}`},o.id)})}):i.jsx(is,{className:"empty-teams",icon:vr,title:"No teams assigned",description:"Assign teams to this project to start collaborative development."}),s&&i.jsx(ue,{variant:"secondary",size:"sm",icon:QH,onClick:s,className:"mt-4",children:"Assign team"})]}),Yk="tab";function mde(t,e,n={}){return t&&e.includes(t)?t:t&&n[t]?n[t]:e[0]}function cu(t,e){const[n,s]=Lc(),r=mde(n.get(Yk),t,e),a=_.useCallback(o=>{s(l=>{const c=new URLSearchParams(l);return o===t[0]?c.delete(Yk):c.set(Yk,o),c},{replace:!0})},[s,t]);return[r,a]}const gde={detail:"Detail",editor:"Editor",tasks:"Tasks",teams:"Teams",autopilot:"Autopilot"};function xde(t){return t.replace(/^\/(Users|home)\/[^/]+/,"~")}const yde=()=>{const{id:t}=Ic(),e=bi(),n=cs(),{openTerminalWithSession:s}=uy(),{showAlert:r,showSuccess:a,showError:o,AlertComponent:l}=Yh(),{showConfirm:c,showDeleteConfirm:d,ConfirmComponent:u}=Mm(),[h,f]=cu(Dp);_.useEffect(()=>{const me=Yse(e.hash);if(!me)return;const Te=new URLSearchParams(e.search);me===Dp[0]?Te.delete("tab"):Te.set("tab",me);const He=Te.toString();n({pathname:e.pathname,search:He?`?${He}`:"",hash:""},{replace:!0})},[e.hash,e.search,e.pathname,n]);const[p,x]=_.useState(null),[v,m]=_.useState(!1),[g,y]=_.useState(!1),[b,S]=_.useState(!1),[E,k]=_.useState(!1),[T,A]=_.useState(""),[N,M]=_.useState(""),[L,j]=_.useState({isActive:!1,steps:[]}),[D,U]=_.useState({project:null,assignedTeams:[],ticketCount:0,loading:!0,error:null}),[$,G]=_.useState({hasAlignmentIssues:!1,alignmentFilePath:null,content:null}),[K,P]=_.useState(""),[B,I]=_.useState([]),F=_.useCallback(me=>{U(Te=>Te.ticketCount===me?Te:{...Te,ticketCount:me})},[]);_.useEffect(()=>{t&&ne(t)},[t]),_.useEffect(()=>{t&&h==="teams"&&ne(t,!1)},[h,t]);const q=async me=>{try{const Te=await fetch(`/api/projects/${me}/alignment-status`);if(Te.ok){const He=await Te.json();He.success&&G(He.data)}}catch(Te){console.error("Failed to check alignment status:",Te)}},H=async()=>{if(D.project)try{(await fetch(`/api/projects/${D.project.id}/continue-with-misalignment`,{method:"POST"})).ok?(a("Orchestrator notified to continue Build Specs despite alignment issues"),G({hasAlignmentIssues:!1,alignmentFilePath:null,content:null})):o("Failed to notify orchestrator")}catch(me){o("Failed to continue with misalignment: "+(me instanceof Error?me.message:"Unknown error"))}},re=async()=>{if(D.project)try{const me=await fetch(`/api/projects/${D.project.id}/specs?fileName=alignment_comparison.md`);if(me.ok){const Te=await me.json();if(Te.success&&Te.data){const He=window.open("","_blank");He&&(He.document.write(`
166
166
  <html>
167
167
  <head>
168
168
  <title>Alignment Comparison Analysis</title>
@@ -4952,4 +4952,4 @@ Deployed to staging
4952
4952
  `).map(n=>n.trim()).filter(Boolean),parentMissionId:t.parentMissionId||""};return t.periodType&&t.periodStart&&t.periodEnd?e.period={type:t.periodType,startDate:new Date(t.periodStart).toISOString(),endDate:new Date(t.periodEnd).toISOString(),...t.periodLabel?{label:t.periodLabel}:{}}:!t.periodType&&!t.periodStart&&!t.periodEnd&&(e.period=null),e}const dX=()=>{var re,ne,Y,z,X;const{id:t}=Ic(),e=cs(),[n,s]=_.useState(null),[r,a]=_.useState(!0),[o,l]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[f,p]=_.useState(null),[x,v]=_.useState(!1),[m,g]=_.useState(null),[y,b]=_.useState(new Map),[S,E]=_.useState(new Map),[k,T]=_.useState(new Map),[A,N]=_.useState(0),M=_.useCallback(async(Z=!0)=>{if(t){Z?a(!0):d(!0),l(null);try{const le=await dt.getMission(t);s(le)}catch(le){const ye=le instanceof Error?le.message:"Failed to load goal";l(ye)}finally{a(!1),d(!1)}}},[t]);_.useEffect(()=>{M()},[M]),_.useEffect(()=>{let Z=!1;return(async()=>{try{const le=await dt.getMissions();if(Z)return;b(new Map(le.map(ye=>[ye.id,ye.objective]))),E(new Map(le.map(ye=>[ye.id,{level:ye.level,parentMissionId:ye.parentMissionId}])))}catch{}})(),()=>{Z=!0}},[t]),_.useEffect(()=>{let Z=!1;return(async()=>{try{const le=await dt.getTeams();!Z&&Array.isArray(le)&&T(new Map(le.map(ye=>[ye.id,ye.name])))}catch{}})(),()=>{Z=!0}},[]);const L=_.useCallback(()=>{N(Z=>Z+1),M(!1)},[M]),j=_.useCallback(Z=>{s(le=>le&&le.id===Z.id?{...le,...Z}:le),L()},[L]),D=_.useCallback(()=>{n&&(p(uBe(n)),g(null),h(!0))},[n]),U=_.useCallback(()=>{h(!1),p(null),g(null)},[]),$=_.useCallback(async()=>{if(!(!t||!f)){if(!f.objective.trim()){g("Objective cannot be empty.");return}if(!f.ownerTeamId.trim()){g("Owner team cannot be empty.");return}v(!0),g(null);try{const Z=await dt.updateMission(t,hBe(f));s(Z),h(!1),p(null)}catch(Z){const le=Z instanceof Error?Z.message:"Failed to save goal";g(le)}finally{v(!1)}}},[t,f]),G=_.useMemo(()=>(Z,le)=>{p(ye=>ye&&{...ye,[Z]:le})},[]);if(r)return i.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:i.jsx(zt,{size:"xl",text:"Loading goal..."})});if(o)return i.jsxs("div",{className:"p-6 max-w-[1000px] mx-auto","data-testid":"mission-detail-error",children:[i.jsx(ue,{variant:"ghost",size:"sm",icon:Ba,onClick:()=>e(qt.goals()),className:"mb-6",children:"Back to Goals"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsxs("div",{className:"flex flex-col items-center text-center py-8",children:[i.jsx("p",{className:"text-red-400 mb-2",children:o}),i.jsx(ue,{variant:"secondary",size:"sm",icon:$t,onClick:()=>M(),children:"Retry"})]})})]});if(!n)return i.jsxs("div",{className:"p-6 max-w-[1000px] mx-auto",children:[i.jsx(ue,{variant:"ghost",size:"sm",icon:Ba,onClick:()=>e(qt.goals()),className:"mb-6",children:"Back to Goals"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsx(is,{icon:ny,title:"Goal not found.",compact:!0})})]});const K=sI(n,S),P=(re=n.approval)==null?void 0:re.state,B=aX(n),I=iX(n.ownerTeamId,k),F=u&&!!f,q=(Z,le,ye)=>i.jsxs("div",{className:"flex items-baseline justify-between gap-4 border-t border-border-soft py-2 text-sm first:border-t-0","data-testid":ye,children:[i.jsx("dt",{className:"shrink-0 text-text-2",children:Z}),i.jsx("dd",{className:"min-w-0 text-right text-text",children:le})]}),H="mb-2 text-[13px] font-semibold text-text-2";return i.jsxs("div",{className:"p-6 max-w-5xl mx-auto","data-testid":"mission-detail-page",children:[i.jsx(_r,{eyebrow:i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:Yt.teams,className:"text-text-2 hover:text-text",children:"Teams"}),i.jsx(cr,{className:"h-3.5 w-3.5 text-text-3","aria-hidden":"true"}),i.jsx(hs,{to:qt.goals(),className:"text-text-2 hover:text-text","data-testid":"mission-detail-back",children:"Goals"})]}),title:F?"Edit goal":n.objective,subtitle:i.jsxs("span",{className:"inline-flex flex-wrap items-center gap-x-1.5",children:[i.jsx("span",{"data-testid":`level-badge-${K}`,children:cc[K]}),i.jsx("span",{className:"text-text-3",children:"·"}),i.jsx(sn,{tone:B.tone,children:B.label}),n.priority&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-3",children:"·"}),i.jsxs("span",{children:[qM[n.priority]," priority"]})]}),((ne=n.period)==null?void 0:ne.label)&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-3",children:"·"}),i.jsx("span",{children:n.period.label})]}),i.jsx("span",{className:"text-text-3",children:"·"}),i.jsx("span",{title:k.has(n.ownerTeamId)?void 0:`Team id ${n.ownerTeamId}`,children:I})]}),actions:F?i.jsxs(i.Fragment,{children:[i.jsx(ue,{variant:"primary",size:"sm",icon:Kd,onClick:$,disabled:x,"data-testid":"mission-save",children:x?"Saving…":"Save"}),i.jsx(ue,{variant:"ghost",size:"sm",icon:ys,onClick:U,disabled:x,"data-testid":"mission-cancel",children:"Cancel"})]}):i.jsxs(i.Fragment,{children:[i.jsx(ue,{variant:"primary",size:"sm",icon:Ih,onClick:D,"data-testid":"mission-edit",children:"Edit"}),i.jsx(Eo,{icon:fa,label:"More goal actions",buttonClassName:"inline-flex h-9 w-9 items-center justify-center rounded-2xl border border-border-soft text-text-2 transition-colors hover:bg-surface-hover hover:text-text",items:[{label:c?"Refreshing…":"Refresh",icon:$t,onClick:()=>M(!1),disabled:c}]})]})}),P&&P!=="pending_approval"&&((Y=n.approval)==null?void 0:Y.decidedAt)&&!F&&i.jsx("div",{className:"mb-4",children:i.jsx(ZM,{state:P})}),P==="pending_approval"&&!F&&i.jsxs("div",{className:"mb-6 flex flex-wrap items-center gap-3","data-testid":"mission-pending-banner",children:[i.jsx(ZM,{state:P}),i.jsxs("span",{className:"text-[13px] text-attention",children:["Proposed",(z=n.approval)!=null&&z.proposedBy?` by ${n.approval.proposedBy}`:"",". Waiting for your decision."]}),i.jsx(eP,{missionId:n.id,onDecided:j})]}),P==="rejected"&&((X=n.approval)==null?void 0:X.rejectionReason)&&i.jsxs("p",{className:"mb-4 text-[13px] text-danger","data-testid":"mission-rejection-reason",children:["Rejected: ",n.approval.rejectionReason]}),m&&i.jsx("div",{"data-testid":"mission-save-error",className:"mb-4",children:i.jsx(Ye,{variant:"error",onClose:()=>g(null),children:m})}),F&&f?i.jsxs("div",{className:"flex flex-col gap-4 rounded-2xl border border-border-soft p-5","data-testid":"mission-edit-form",children:[i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Objective",i.jsx(ss,{"aria-label":"Objective",value:f.objective,onChange:Z=>G("objective",Z.target.value),fullWidth:!0,"data-testid":"edit-objective"})]}),i.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Status",i.jsxs(vn,{value:f.status,onChange:Z=>G("status",Z.target.value),"data-testid":"edit-status",children:[i.jsx("option",{value:"active",children:"Active"}),i.jsx("option",{value:"paused",children:"Paused"}),i.jsx("option",{value:"completed",children:"Completed"}),i.jsx("option",{value:"cancelled",children:"Cancelled"})]})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Priority",i.jsxs(vn,{value:f.priority,onChange:Z=>G("priority",Z.target.value),"data-testid":"edit-priority",children:[i.jsx("option",{value:"critical",children:"Critical"}),i.jsx("option",{value:"high",children:"High"}),i.jsx("option",{value:"medium",children:"Medium"}),i.jsx("option",{value:"low",children:"Low"})]})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Owner team",i.jsx(ss,{"aria-label":"Owner Team",value:f.ownerTeamId,onChange:Z=>G("ownerTeamId",Z.target.value),fullWidth:!0,"data-testid":"edit-owner-team"})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Parent goal",i.jsx(ss,{"aria-label":"Parent Mission ID",placeholder:"(none)",value:f.parentMissionId,onChange:Z=>G("parentMissionId",Z.target.value),fullWidth:!0,"data-testid":"edit-parent"})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Review cadence (cron)",i.jsx(ss,{"aria-label":"Cadence",value:f.cadence,onChange:Z=>G("cadence",Z.target.value),fullWidth:!0,"data-testid":"edit-cadence"})]})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Current strategy",i.jsx(er,{"aria-label":"Current Strategy",rows:4,value:f.currentStrategy,onChange:Z=>G("currentStrategy",Z.target.value),"data-testid":"edit-strategy"})]}),i.jsxs("label",{className:"flex flex-col gap-1 text-sm text-text-2",children:["Success criteria (one per line)",i.jsx(er,{"aria-label":"Success Criteria (one per line)",rows:5,placeholder:"One criterion per line",value:f.successCriteriaText,onChange:Z=>G("successCriteriaText",Z.target.value),"data-testid":"edit-success-criteria"})]}),i.jsxs("fieldset",{className:"flex flex-col gap-2",children:[i.jsx("legend",{className:"mb-1 text-sm text-text-2",children:"OKR period"}),i.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-4",children:[i.jsxs(vn,{value:f.periodType,onChange:Z=>G("periodType",Z.target.value),"data-testid":"edit-period-type",children:[i.jsx("option",{value:"",children:"— No period —"}),i.jsx("option",{value:"weekly",children:"Weekly"}),i.jsx("option",{value:"biweekly",children:"Biweekly"}),i.jsx("option",{value:"monthly",children:"Monthly"}),i.jsx("option",{value:"quarterly",children:"Quarterly"}),i.jsx("option",{value:"custom",children:"Custom"})]}),i.jsx(ss,{type:"date","aria-label":"Period start",value:f.periodStart,onChange:Z=>G("periodStart",Z.target.value),fullWidth:!0,"data-testid":"edit-period-start"}),i.jsx(ss,{type:"date","aria-label":"Period end",value:f.periodEnd,onChange:Z=>G("periodEnd",Z.target.value),fullWidth:!0,"data-testid":"edit-period-end"}),i.jsx(ss,{"aria-label":"Period label",placeholder:"Label (optional)",value:f.periodLabel,onChange:Z=>G("periodLabel",Z.target.value),fullWidth:!0,"data-testid":"edit-period-label"})]})]})]}):i.jsxs("div",{className:"flex flex-col gap-8",children:[i.jsx(iBe,{missionId:n.id,onChanged:L}),i.jsx(lBe,{parentMissionId:n.id,onDecided:j}),i.jsxs("section",{"aria-labelledby":"goal-strategy-h",children:[i.jsx("h2",{id:"goal-strategy-h",className:H,children:"Current strategy"}),i.jsx("p",{className:"whitespace-pre-wrap text-[15px] leading-relaxed text-text",children:n.currentStrategy||"No strategy defined."})]}),i.jsx(ti,{title:"More",summary:"Success criteria, cascade, learnings, progress, settings, period, timestamps","data-testid":"goal-more",children:i.jsxs("div",{className:"grid grid-cols-1 gap-8 lg:grid-cols-3",children:[i.jsxs("div",{className:"flex flex-col gap-8 lg:col-span-2",children:[i.jsxs("section",{"aria-labelledby":"goal-criteria-h",children:[i.jsxs("h2",{id:"goal-criteria-h",className:H,children:["Success criteria (",n.successCriteria.length,")"]}),n.successCriteria.length===0?i.jsx("p",{className:"text-sm text-text-2",children:"No success criteria defined."}):i.jsx("ul",{className:"space-y-2",children:n.successCriteria.map((Z,le)=>i.jsxs("li",{className:"flex items-start gap-2 text-sm text-text",children:[i.jsx(DH,{className:"mt-0.5 h-4 w-4 shrink-0 text-text-3","aria-hidden":"true"}),Z]},le))})]}),i.jsx(oBe,{missionId:n.id,level:K,parentMissionId:n.parentMissionId,missionNames:y,refreshKey:A}),n.learnings&&n.learnings.length>0&&i.jsxs("section",{"aria-labelledby":"goal-learnings-h",children:[i.jsxs("h2",{id:"goal-learnings-h",className:H,children:["Learnings (",n.learnings.length,")"]}),i.jsx(fs,{as:"ul",limit:6,className:"space-y-2","data-testid":"goal-learnings",children:n.learnings.map((Z,le)=>i.jsx("li",{className:"border-l-2 border-border-soft pl-4 text-sm text-text",children:Z},le))})]})]}),i.jsxs("div",{className:"flex flex-col gap-8",children:[i.jsx(dBe,{missionId:n.id,refreshKey:A}),i.jsxs("section",{"aria-labelledby":"goal-settings-h",children:[i.jsx("h2",{id:"goal-settings-h",className:H,children:"Team & settings"}),i.jsxs("dl",{children:[q("Owner team",i.jsx("span",{title:n.ownerTeamId,children:I})),q("Status",lE(n.status)),q("Priority",qM[n.priority??"medium"]),q("Parent goal",n.parentMissionId?i.jsx(ue,{type:"button",variant:"link",size:"xs",onClick:()=>e(qt.goal(n.parentMissionId)),className:"max-w-full truncate","data-testid":"mission-parent-link",children:y.get(n.parentMissionId)??n.parentMissionId}):"—"),q("Level",i.jsx("span",{"data-testid":"mission-level",children:K})),n.projectId&&q("Project",i.jsx(ue,{type:"button",variant:"link",size:"xs",onClick:()=>e(qt.project(n.projectId)),"data-testid":"mission-project-link",children:"Open project"})),q("Active tasks",n.activeProjectTaskIds.length),q("Review cadence",i.jsx("span",{className:"font-mono text-xs",children:n.cadence||"N/A"})),q("Reference",i.jsx("span",{className:"font-mono text-xs",children:n.id.slice(0,12)}))]})]}),i.jsxs("section",{"aria-labelledby":"goal-period-h",children:[i.jsx("h2",{id:"goal-period-h",className:H,children:"OKR period"}),n.period?i.jsxs("dl",{children:[q("Type",n.period.type),q("Start",Qf(n.period.startDate)),q("End",Qf(n.period.endDate)),n.period.label&&q("Label",n.period.label)]}):i.jsx("p",{className:"text-sm text-text-2",children:"No period defined."})]}),i.jsxs("section",{"aria-labelledby":"goal-times-h",children:[i.jsx("h2",{id:"goal-times-h",className:H,children:"Timestamps"}),i.jsxs("dl",{children:[q("Created",Qf(n.createdAt)),q("Updated",i.jsx("span",{title:Qf(n.updatedAt),children:Nl(n.updatedAt)})),n.lastReviewAt&&q("Last review",Qf(n.lastReviewAt)),n.nextReviewAt&&q("Next review",Qf(n.nextReviewAt))]})]}),n.activeProjectTaskIds.length>0&&i.jsxs("section",{"aria-labelledby":"goal-task-ids-h",children:[i.jsx("h2",{id:"goal-task-ids-h",className:H,children:"Active task ids"}),i.jsx("p",{className:"flex flex-wrap gap-x-3 gap-y-1 font-mono text-xs text-text-2",children:n.activeProjectTaskIds.map(Z=>i.jsx("span",{title:Z,children:Z.slice(0,12)},Z))})]})]})]})})]})]})};dX.displayName="MissionDetail";function tP(t){return{queued:"Queued",scheduled:"Scheduled",running:"Running",blocked:"Blocked",done:"Completed",failed:"Failed",cancelled:"Cancelled"}[t]??t}function nP(t){return{delegate:"Delegate",project_task:"Project Task",check:"Check",notify:"Notify",cron_run:"Cron Run",review:"Review",confirm:"Confirm",reconcile:"Reconcile",ticket_triage:"Ticket triage",autopilot_retro:"Autopilot retro",goal_replan:"Goal replan",autopilot_self_review:"Autopilot self-review"}[t]??t}function q2(t){return{orchestrator:"Orchestrator",team_lead:"Team Lead",agent:"Agent",system:"System"}[t]??t}function sC(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 Sx(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 uX(t){return t===0?"—":t<.01?`$${t.toFixed(4)}`:`$${t.toFixed(2)}`}function qx(t){return t===0?"—":t<1e3?t.toString():t<1e6?`${(t/1e3).toFixed(1)}K`:`${(t/1e6).toFixed(1)}M`}function hX(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 fBe(t,e){if(t==="error")return qd;if(t==="progress_update")return AH;if(t==="agent_reasoning"||t==="tool_action")return Ra;switch(e){case"queued":return jr;case"running":return Ra;case"done":return vo;case"failed":return qd;case"cancelled":return YQ;case"blocked":return Vd;default:return jr}}function pBe(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 mBe(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 sP=({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=fBe(e.kind,e.status),r=pBe(e.kind,e.status),a=mBe(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:Sx(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)})});sP.displayName="WorkItemTimeline";const no=({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})]}),fX=({item:t})=>{const e=gBe(t);return i.jsxs("div",{className:"space-y-4","data-testid":"workitem-metrics",children:[i.jsxs(tn,{variant:"default",padding:"md",children:[i.jsx("h3",{className:"text-xs font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:"Token Usage"}),i.jsxs("div",{className:"divide-y divide-border-dark",children:[i.jsx(no,{icon:g0,label:"Input Tokens",value:qx(t.inputTokens)}),i.jsx(no,{icon:g0,label:"Output Tokens",value:qx(t.outputTokens)}),i.jsx(no,{icon:Qj,label:"Cost",value:uX(t.cost),valueClass:t.cost>0?"text-yellow-400":"text-text-primary-dark"})]})]}),i.jsxs(tn,{variant:"default",padding:"md",children:[i.jsx("h3",{className:"text-xs font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:"Execution"}),i.jsxs("div",{className:"divide-y divide-border-dark",children:[i.jsx(no,{icon:$t,label:"Retries",value:`${t.retryCount} / ${t.maxRetries}`}),i.jsx(no,{icon:jr,label:"Duration",value:e}),i.jsx(no,{icon:sy,label:"Owner",value:q2(t.owner)}),t.target&&i.jsx(no,{icon:ny,label:"Agent",value:t.target})]})]}),(t.requestId||t.missionId||t.projectTaskId||t.triggerId)&&i.jsxs(tn,{variant:"default",padding:"md",children:[i.jsx("h3",{className:"text-xs font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:"Linked References"}),i.jsxs("div",{className:"divide-y divide-border-dark",children:[t.requestId&&i.jsx(no,{icon:ep,label:"Request",value:ix(t.requestId)}),t.missionId&&i.jsx(no,{icon:ep,label:"Mission",value:ix(t.missionId)}),t.projectTaskId&&i.jsx(no,{icon:ep,label:"Project Task",value:ix(t.projectTaskId)}),t.triggerId&&i.jsx(no,{icon:ep,label:"Trigger",value:ix(t.triggerId)}),t.parentWorkItemId&&i.jsx(no,{icon:ep,label:"Parent Item",value:ix(t.parentWorkItemId)})]})]}),i.jsxs(tn,{variant:"default",padding:"md",children:[i.jsx("h3",{className:"text-xs font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:"Timestamps"}),i.jsxs("div",{className:"space-y-2 text-sm",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary-dark",children:"Created"}),i.jsx("span",{className:"text-text-primary-dark",children:Sx(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:Sx(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:Sx(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:Sx(t.scheduledAt)})]})]})]})]})};fX.displayName="WorkItemMetrics";function gBe(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 ix(t){return t.length<=12?t:`${t.slice(0,8)}...`}let T_=null;function xBe(){return T_||(T_=Promise.resolve().then(()=>s$()).then(t=>Cce(t.flatMap(e=>e.tickets.map(n=>n.id)))).catch(t=>{throw T_=null,t})),T_}function pX(){const[t,e]=_.useState(()=>new Set);return _.useEffect(()=>{let n=!0;return xBe().then(s=>{n&&e(s)}).catch(()=>{}),()=>{n=!1}},[]),t}const mX=()=>{const{id:t}=Ic(),e=cs(),{names:n}=Pm(),s=pX(),[r,a]=_.useState(null),[o,l]=_.useState(!0),[c,d]=_.useState(null),[u,h]=_.useState(!1),f=_.useCallback(async(y=!0)=>{if(t){y?l(!0):h(!0),d(null);try{const b=await dt.getWorkItem(t);a(b)}catch(b){const S=b instanceof Error?b.message:"Failed to load run";d(S)}finally{l(!1),h(!1)}}},[t]);_.useEffect(()=>{f(!0)},[f]),_.useEffect(()=>{if(!r||r.status!=="running")return;const y=setInterval(()=>{f(!1)},1e4);return()=>clearInterval(y)},[r==null?void 0:r.status,f]);const p=()=>{e(qt.runs())},x=()=>{f(!1)};if(o)return i.jsx("div",{className:"flex items-center justify-center h-64","data-testid":"workitem-detail-loading",children:i.jsx(zt,{})});if(c)return i.jsxs("div",{className:"p-6","data-testid":"workitem-detail-error",children:[i.jsx(ue,{variant:"ghost",size:"sm",icon:Ba,onClick:p,className:"mb-6",children:"Back to Runs"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsxs("div",{className:"flex flex-col items-center text-center py-8",children:[i.jsx("p",{className:"text-danger text-lg font-medium mb-2",children:"Failed to load run"}),i.jsx("p",{className:"text-text-2 text-sm mb-4",children:c}),i.jsx(ue,{variant:"secondary",size:"sm",icon:$t,onClick:()=>f(!0),children:"Retry"})]})})]});if(!r)return i.jsxs("div",{className:"p-6","data-testid":"workitem-detail-not-found",children:[i.jsx(ue,{variant:"ghost",size:"sm",icon:Ba,onClick:p,className:"mb-6",children:"Back to Runs"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsx(is,{icon:aee,title:"Run not found.",compact:!0})})]});const v=hX(r),m=Xd(r.target,n,!0),g=h$(r.title,s);return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-6","data-testid":"workitem-detail",children:[i.jsx(_r,{className:"mb-0",eyebrow:i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:qt.ticketsBoard(),className:"text-text-2 hover:text-text",children:"Tickets"}),i.jsx("span",{className:"text-text-3",children:"/"}),i.jsx(hs,{to:qt.runs(),className:"text-text-2 hover:text-text","data-testid":"workitem-detail-back",children:"Runs"})]}),title:r.title,subtitle:i.jsxs(i.Fragment,{children:[m?`${q2(r.owner)} · ${m}`:q2(r.owner),` · created ${sC(r.createdAt)} · `,i.jsxs("span",{className:"font-mono text-text-3",title:r.id,children:["run ",iN(r.id)]})]}),actions:i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:x,loading:u,"data-testid":"workitem-detail-refresh"}),"data-testid":"workitem-detail-header"}),i.jsxs("div",{className:"-mt-2 flex flex-wrap items-center gap-x-4 gap-y-2 text-[13px] text-text-2",children:[i.jsx(sn,{tone:yBe(r.status),children:tP(r.status)}),i.jsx("span",{children:nP(r.type)}),i.jsxs("span",{children:["Retry ",r.retryCount,"/",r.maxRetries]}),g&&i.jsx("span",{children:g}),r.requestId&&i.jsxs(hs,{to:qt.request(r.requestId),className:"font-semibold text-primary-text hover:underline",children:["Request ",iN(r.requestId)]}),r.missionId&&i.jsxs(hs,{to:qt.goal(r.missionId),className:"font-semibold text-primary-text hover:underline",children:["Goal ",iN(r.missionId)]})]}),r.description&&i.jsx("p",{className:"whitespace-pre-wrap text-sm leading-relaxed text-text-2",children:r.description}),i.jsxs("section",{"aria-labelledby":"workitem-timeline-heading",className:"rounded-2xl bg-surface p-4",children:[i.jsx("h2",{id:"workitem-timeline-heading",className:"mb-4 text-[15px] font-bold text-text",children:"Activity timeline"}),i.jsx(sP,{events:v})]}),i.jsx(ti,{title:"Details",summary:"Tokens, cost, retries, duration, links and timestamps",children:i.jsx(fX,{item:r})})]})};function yBe(t){return t==="cancelled"||t==="queued"||t==="scheduled"?"neutral":eE(t)}mX.displayName="WorkItemDetail";function iN(t){return t.length<=12?t:t.slice(0,8)}const ax=new Set(["open","waiting_owner","ready","overdue"]),vBe={open:{label:"Open",variant:"info"},waiting_owner:{label:"Waiting on you",variant:"warning"},ready:{label:"Ready to deliver",variant:"warning"},overdue:{label:"Overdue",variant:"error"},delivered:{label:"Delivered",variant:"success"},resolved:{label:"Answered",variant:"success"},superseded:{label:"Superseded",variant:"default"},expired:{label:"Expired",variant:"default"},cancelled:{label:"Cancelled",variant:"default"},skipped:{label:"Skipped",variant:"default"}};function Uz(t){if(!t)return"";const e=new Date(t);return Number.isNaN(e.getTime())?"":e.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}const bBe=({items:t,onSkip:e})=>{const[n,s]=an.useState(null),[r,a]=an.useState(null),o=async d=>{if(e){s(d),a(null);try{await e(d)}catch(u){a(u instanceof Error?u.message:String(u))}finally{s(null)}}},l=[...t].sort((d,u)=>Number(ax.has(u.status))-Number(ax.has(d.status))||Date.parse(u.createdAt)-Date.parse(d.createdAt)),c=l.filter(d=>ax.has(d.status)).length;return i.jsxs(tn,{variant:"default",padding:"md","data-testid":"request-open-items",children:[i.jsxs("h2",{className:"text-sm font-semibold text-text-secondary-dark uppercase tracking-wider mb-3",children:["Open items ",c>0?`(${c} open)`:""]}),r&&i.jsx("p",{className:"text-xs text-red-400 mb-2",role:"alert",children:r}),i.jsx("ul",{className:"flex flex-col gap-3",children:l.map(d=>{const u=vBe[d.status]??{label:d.status,variant:"default"};return i.jsxs("li",{className:"flex flex-col gap-1","data-testid":"request-open-item",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx(mn,{variant:d.type==="commitment"?"info":"warning",size:"sm",children:d.type==="commitment"?"Promise":"Question"}),i.jsx(mn,{variant:u.variant,size:"sm",children:u.label}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:d.agent}),d.type==="commitment"&&d.due&&ax.has(d.status)&&i.jsxs("span",{className:"text-xs text-text-secondary-dark",children:["due ",Uz(d.due)]}),d.decisionId&&i.jsx("span",{className:"text-xs text-text-secondary-dark font-mono",children:d.decisionId}),e&&ax.has(d.status)&&i.jsx(ue,{size:"sm",variant:"ghost",className:"ml-auto min-h-8",disabled:n===d.id,onClick:()=>void o(d.id),title:d.type==="commitment"?"Drop this promise and cancel its follow-up":"Skip this question — the agent won't ask again",children:"Skip"})]}),i.jsx("p",{className:"text-sm text-text-primary-dark break-words",children:d.text}),d.answer&&i.jsxs("p",{className:"text-xs text-text-secondary-dark",children:["Answer: ",d.answer]}),d.status==="ready"&&d.readyAt&&i.jsxs("p",{className:"text-xs text-amber-400",children:["The work was ready at ",Uz(d.readyAt),"; the agent was asked to deliver it."]})]},d.id)})})]})},_Be="/api/traces";class gX extends Error{constructor(e,n){super(e),this.status=n,this.name="TraceApiError"}}async function xX(t){const e=await fetch(`${_Be}${t}`);let n={};try{n=await e.json()}catch{n={}}if(!e.ok||n.success===!1)throw new gX(n.error||`HTTP ${e.status}`,e.status);return n.data}function SBe(t){return t?`?stallMinutes=${encodeURIComponent(String(t))}`:""}async function wBe(t,e){try{return await xX(`/by-ref?${t}=${encodeURIComponent(e)}`)}catch(n){if(n instanceof gX&&n.status===404)return null;throw n}}function EBe(t,e){return xX(`/${encodeURIComponent(t)}/timeline${SBe(e)}`)}function CBe(t){return t==="done"?"success":t==="failed"?"danger":t==="waiting_on_owner"?"attention":t==="in_progress"?"primary":"neutral"}function zz(t,e){return e>0?`${Math.round(t/e*100)}% of the time`:void 0}function kBe(t){const e=t.time,n=t.stalls.items.some(a=>a.ongoing),s=t.ownerTouches,r=t.rework;return[{id:"wall",label:"Wall time",value:Bi(e.wallMs)},{id:"active",label:"Agents working",value:Bi(e.activeMs),hint:zz(e.activeMs,e.wallMs),title:e.activeSource==="inferred"?"Estimated from agent activity":void 0},{id:"owner-wait",label:"Waiting on you",value:Bi(e.waitingOwnerMs),hint:zz(e.waitingOwnerMs,e.wallMs),attention:e.waitingOwnerMs>0},{id:"touches",label:"Your touches",value:String(s.total),title:`Answered ${s.answered}, approved ${s.approved}, sent back ${s.sentBack}, corrected ${s.corrected}`},{id:"rework",label:"Rework",value:String(r.total),title:`Send-backs ${r.sendBacks}, retries ${r.retries}, failed verifications ${r.failedVerifications}, subagent send-backs ${r.subagentSendBacks}`,attention:r.total>0},{id:"stalls",label:"Stalls",value:String(t.stalls.count),hint:t.stalls.count>0?n?"one still going":Bi(t.stalls.totalMs):void 0,attention:t.stalls.count>0},{id:"cost",label:"Cost",value:Tc(t.usage.costUsd),hint:`${S0(t.usage.totalTokens)} tokens`}]}function Hz(t,e){return t.length===0?"none":t.map(n=>`${e(n.key)} ${S0(n.totalTokens)} ${Tc(n.costUsd)}`).join(" · ")}const yX=({metrics:t,nameOf:e=n=>n})=>{var o;const n=kBe(t),s=t,r=Object.entries(s.stalls.byCause).filter(([,l])=>l>0).map(([l,c])=>`${QR[l]} ${c}`).join(" · "),a=s.interventions;return i.jsxs("section",{"aria-label":"Run metrics","data-testid":"trace-metrics-strip",children:[i.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] text-text-2",children:[i.jsx(sn,{tone:CBe(s.outcome.state),"data-testid":"trace-outcome",children:Zce[s.outcome.state]}),((o=s.outcome.experiment)==null?void 0:o.verdict)&&i.jsxs("span",{children:["Experiment: ",s.outcome.experiment.verdict==="didnt"?"didn't work":s.outcome.experiment.verdict]}),s.outcome.workItems.total>0&&i.jsxs("span",{children:[s.outcome.workItems.done," of ",s.outcome.workItems.total," runs done",s.outcome.workItems.failed>0?` · ${s.outcome.workItems.failed} failed`:""]})]}),i.jsx("dl",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap sm:gap-3",children:n.map(l=>i.jsxs("div",{title:l.title,className:`min-w-0 rounded-2xl px-3 py-2 sm:min-w-[7.5rem] ${l.attention?"bg-attention-soft":"bg-surface"}`,"data-testid":`trace-metric-${l.id}`,children:[i.jsx("dt",{className:"truncate text-[12px] text-text-2",children:l.label}),i.jsx("dd",{className:`text-[15px] font-bold leading-snug ${l.attention?"text-attention":"text-text"}`,children:l.value}),l.hint&&i.jsx("dd",{className:"truncate text-[12px] text-text-3",children:l.hint})]},l.id))}),i.jsx(ti,{className:"mt-2",unmountWhenClosed:!0,title:"Details",summary:"Touches, rework, interventions, cost by agent and model","data-testid":"trace-metrics-details",children:i.jsxs("dl",{className:"grid grid-cols-1 gap-x-6 gap-y-1.5 text-[13px] sm:grid-cols-[auto_1fr]",children:[i.jsx("dt",{className:"text-text-2",children:"Your touches"}),i.jsxs("dd",{className:"text-text",children:["answered ",s.ownerTouches.answered," · approved ",s.ownerTouches.approved," · sent back ",s.ownerTouches.sentBack," · corrected ",s.ownerTouches.corrected]}),i.jsx("dt",{className:"text-text-2",children:"Rework"}),i.jsxs("dd",{className:"text-text",children:["send-backs ",s.rework.sendBacks," · retries ",s.rework.retries," · failed verifications ",s.rework.failedVerifications," · subagent send-backs ",s.rework.subagentSendBacks]}),i.jsx("dt",{className:"text-text-2",children:"Crewly stepped in"}),i.jsxs("dd",{className:"text-text",children:["nudges ",a.nudges," · redeliveries ",a.redeliveries," · wakes ",a.wakes," · corrections ",a.corrections," · guard blocks ",a.guardBlocks," · misroutes ",a.misroutes]}),i.jsx("dt",{className:"text-text-2",children:"Time"}),i.jsxs("dd",{className:"text-text",children:["working ",Bi(s.time.activeMs)," · waiting on you ",Bi(s.time.waitingOwnerMs)," · waiting on agents ",Bi(s.time.waitingAgentMs)," · idle ",Bi(s.time.idleMs)]}),i.jsx("dt",{className:"text-text-2",children:"Stalls"}),i.jsx("dd",{className:"text-text",children:s.stalls.count===0?`none longer than ${s.stalls.thresholdMinutes}m`:`${r} (longer than ${s.stalls.thresholdMinutes}m)`}),i.jsx("dt",{className:"text-text-2",children:"By agent"}),i.jsx("dd",{className:"text-text",children:Hz(s.usage.byAgent,e)}),i.jsx("dt",{className:"text-text-2",children:"By model"}),i.jsx("dd",{className:"break-words text-text",children:Hz(s.usage.byModel,l=>l)})]})})]})};yX.displayName="MetricsStrip";function ABe(t,e){if(t.kind==="stall"&&t.stall)return`Stalled ${Bi(t.stall.ms)}${t.stall.ongoing?" and counting":""} — ${QR[t.stall.cause]}`;if(t.kind==="owner")return"You";if(t.kind==="system")return"Crewly";const n=t.session;if(!n)return t.title;const s=e(n);if(t.title===`${n} working`)return`${s} working`;if(t.title===`Harness → ${n}`)return`Crewly → ${s}`;const r=t.title.lastIndexOf(" → "),a=r>=0?t.title.slice(0,r):t.title;return`${a==="Owner"?"You":a} → ${s}`}function Gz(t,e){var o;const n=w0(t.start,e),s=w0(t.end,e),r=n===s?n:`${n}–${s}`;if(t.kind==="stall")return(o=t.stall)!=null&&o.ongoing?`since ${n}`:r;const a=[r,`${t.counts.events} ${t.counts.events===1?"event":"events"}`];return t.counts.skillCalls>0&&a.push(`${t.counts.skillCalls} skill ${t.counts.skillCalls===1?"call":"calls"}`),t.tokens>0&&a.push(`${S0(t.tokens)} tokens ${Tc(t.costUsd)}`),a.join(" · ")}const TBe=({event:t,nameOf:e,now:n})=>{const s=t.actor.kind==="agent"&&t.actor.session?e(t.actor.session):tde(t);return i.jsxs("li",{className:"flex min-w-0 gap-3 py-1.5 text-[13px]","data-testid":"trace-event",children:[i.jsx("span",{className:"w-12 shrink-0 font-mono text-[12px] text-text-3",children:w0(t.ts,n)}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"font-semibold text-text",children:ede(t.type)}),i.jsxs("span",{className:"text-text-3",children:[" · ",s]}),(t.outcome==="failed"||t.outcome==="blocked")&&i.jsx(sn,{className:"ml-2",size:"sm",tone:t.outcome==="failed"?"danger":"attention",children:t.outcome==="failed"?"Failed":"Blocked"}),i.jsx("span",{className:"block break-words text-text-2",children:t.summary})]})]})},vX=({group:t,nameOf:e=s=>s,now:n})=>{var h,f;const[s,r]=_.useState(!1),[a,o]=_.useState(!1),l=t.kind==="stall",c=t.events.filter(p=>SB.has(p.type)),d=a?t.events:t.events.filter(p=>!SB.has(p.type)),u=l||t.outcome==="blocked"?"bg-attention":t.outcome==="failed"?"bg-danger":t.kind==="owner"?"bg-primary":"bg-muted-dot";return i.jsxs("li",{className:`list-none border-b border-border-soft last:border-b-0 ${l?"bg-attention-soft":""}`,"data-testid":`trace-group-${t.id}`,"data-kind":t.kind,children:[i.jsx(Ts,{className:"border-b-0",primary:i.jsx("span",{className:l?"text-attention":void 0,children:ABe(t,e)}),meta:l?`${Gz(t,n)} · ${((h=t.stall)==null?void 0:h.detail)??""}`:Gz(t,n),leading:i.jsx("span",{"aria-hidden":"true",className:`h-2.5 w-2.5 rounded-full ${u}${(f=t.stall)!=null&&f.ongoing?" animate-pulse":""}`}),trailing:t.kind!=="stall"&&(t.counts.errors>0||t.counts.blocks>0)?i.jsxs("span",{className:"text-[12px]",children:[t.counts.errors>0&&i.jsxs("span",{className:"text-danger",children:[t.counts.errors," failed"]}),t.counts.errors>0&&t.counts.blocks>0&&" · ",t.counts.blocks>0&&i.jsxs("span",{className:"text-attention",children:[t.counts.blocks," blocked"]})]}):void 0,onClick:l?void 0:()=>r(p=>!p),"data-testid":`trace-group-row-${t.id}`}),s&&!l&&i.jsxs("div",{className:"px-4 pb-3 sm:pl-12","data-testid":`trace-group-events-${t.id}`,children:[i.jsx("ul",{className:"divide-y divide-border-soft",children:d.map((p,x)=>i.jsx(TBe,{event:p,nameOf:e,now:n},`${p.ts}-${x}`))}),c.length>0&&i.jsx(ue,{variant:"link",size:"xs",onClick:()=>o(p=>!p),"data-testid":`trace-group-show-all-${t.id}`,children:a?"Hide routine events":`Show all ${t.events.length} events (${c.length} routine)`})]})]})};vX.displayName="TimelineGroupRow";const NBe=3e4,MBe=5*6e4,jBe=new Set(["done","cancelled","failed"]),rC=({traceId:t,refParam:e,refId:n,nameOf:s,pollMs:r=NBe,now:a,onLoaded:o})=>{const[l,c]=_.useState({kind:"loading"}),[d,u]=_.useState(!1),h=_.useRef(t??null),f=_.useRef(null),p=_.useRef(0),x=_.useRef(o);x.current=o;const v=_.useCallback(async y=>{var b;y&&u(!0);try{let S=t??h.current;if(!S&&e&&n){const T=await wBe(e,n);S=(T==null?void 0:T.traceId)??null}if(!S){c({kind:"none"});return}h.current=S;const E=await EBe(S),k=`${E.metrics.eventCount}|${E.metrics.window.end}`;k===f.current?p.current+=1:(f.current=k,p.current=0),c({kind:"ready",data:E}),(b=x.current)==null||b.call(x,E)}catch(S){y||c({kind:"error",message:S instanceof Error?S.message:"Failed to load the timeline"})}finally{u(!1)}},[t,e,n]);_.useEffect(()=>{h.current=t??null,f.current=null,p.current=0,c({kind:"loading"}),v(!1)},[v,t]);const m=l.kind==="ready"&&jBe.has(l.data.metrics.outcome.state);if(_.useEffect(()=>{if(!r||l.kind!=="ready"||m)return;let y,b=!1;const S=()=>{if(b||document.hidden)return;const k=Math.max(r,Math.min(r*2**p.current,MBe));y=setTimeout(()=>{v(!0).then(S)},k)},E=()=>{clearTimeout(y),!document.hidden&&!b&&v(!0).then(S)};return S(),document.addEventListener("visibilitychange",E),()=>{b=!0,clearTimeout(y),document.removeEventListener("visibilitychange",E)}},[r,l.kind,m,v]),l.kind==="loading")return i.jsx("div",{className:"flex justify-center py-10","data-testid":"trace-timeline-loading",children:i.jsx(zt,{})});if(l.kind==="none")return i.jsx(is,{icon:lu,title:"No timeline for this yet",description:"A timeline is recorded for work started after run traces were turned on.",compact:!0,"data-testid":"trace-timeline-none"});if(l.kind==="error")return i.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center","data-testid":"trace-timeline-error",children:[i.jsx("p",{className:"text-sm text-danger",children:l.message}),i.jsx(ue,{variant:"secondary",size:"sm",icon:$t,onClick:()=>void v(!1),children:"Retry"})]});const{data:g}=l;return i.jsxs("div",{className:"flex flex-col gap-4","data-testid":"trace-timeline",children:[i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx(yX,{metrics:g.metrics,nameOf:s})}),i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh timeline",onClick:()=>void v(!0),loading:d,"data-testid":"trace-timeline-refresh"})]}),g.groups.length===0?i.jsx("p",{className:"py-6 text-[13px] text-text-3","data-testid":"trace-timeline-empty",children:"Nothing has happened in this run yet."}):i.jsx("ol",{className:"overflow-hidden rounded-2xl bg-surface","aria-label":"Run timeline","data-testid":"trace-timeline-groups",children:g.groups.map(y=>i.jsx(vX,{group:y,nameOf:s,now:a},y.id))}),g.truncated&&i.jsx("p",{className:"text-[12px] text-text-3",children:"This run hit the trace size limit; later events were not recorded."})]})};rC.displayName="TraceTimeline";const RBe={overview:"Overview",timeline:"Timeline"},$z={open:"text-primary-text",in_progress:"text-primary-text",blocked:"text-danger",waiting_confirmation:"text-attention",awaiting_followup:"text-attention",done:"text-success",cancelled:"text-text-2"};function X2(t){return{open:"Open",in_progress:"In Progress",blocked:"Blocked",waiting_confirmation:"Waiting Confirmation",awaiting_followup:"Awaiting Follow-up",done:"Completed",cancelled:"Cancelled"}[t]??t}const Wz=["open","in_progress","done"],IBe=({currentStatus:t})=>{const e=Wz.indexOf(t),n=t==="cancelled"||t==="blocked";return i.jsxs("ol",{className:"flex flex-wrap items-center gap-1.5 text-[13px]","aria-label":"Progress","data-testid":"request-progress-rail",children:[Wz.map((s,r)=>{const a=s===t,o=e>=0&&r<=e;return i.jsxs(an.Fragment,{children:[r>0&&i.jsx("li",{"aria-hidden":"true",className:`h-px w-6 ${o?"bg-success":"bg-border"}`}),i.jsxs("li",{"aria-current":a?"step":void 0,className:`inline-flex items-center gap-1 ${a?`font-semibold ${$z[s]??"text-text"}`:o?"text-success":"text-text-3"}`,children:[o&&!a&&i.jsx(vo,{className:"h-3 w-3","aria-hidden":"true"}),X2(s)]})]},s)}),n&&i.jsxs(i.Fragment,{children:[i.jsx("li",{"aria-hidden":"true",className:"h-px w-6 bg-border"}),i.jsx("li",{"aria-current":"step",className:`font-semibold ${$z[t]??"text-text-2"}`,children:X2(t)})]})]})},LBe=({workItems:t,onItemClick:e,names:n})=>{const[s,r]=_.useState(null);return t.length===0?i.jsx("p",{className:"py-6 text-[13px] text-text-3","data-testid":"request-workitems-empty",children:"No runs for this request yet."}):i.jsx("ul",{className:"overflow-hidden rounded-2xl bg-surface","data-testid":"request-workitems-list",children:t.map(a=>{const o=s===a.id,l=Xd(a.target,n,!0);return i.jsxs("li",{className:"list-none border-b border-border-soft last:border-b-0","data-testid":`request-workitem-${a.id}`,children:[i.jsx(Ts,{className:"border-b-0",primary:a.title,meta:[nP(a.type),l,sC(a.createdAt)].filter(Boolean).join(" · "),trailing:i.jsx(sn,{tone:a.status==="cancelled"||a.status==="queued"||a.status==="scheduled"?"neutral":eE(a.status),children:tP(a.status)}),onClick:()=>r(o?null:a.id),actions:[i.jsx(ue,{variant:"link",size:"xs",onClick:()=>e(a.id),"data-testid":`request-workitem-detail-link-${a.id}`,children:"Details"},"details")],"data-testid":`request-workitem-row-${a.id}`}),o&&i.jsx("div",{className:"border-t border-border-soft px-4 py-3","data-testid":`request-workitem-timeline-${a.id}`,children:i.jsx(sP,{events:hX(a)})})]},a.id)})})},bX=()=>{const{id:t}=Ic(),e=cs(),{names:n}=Pm(),[s,r]=cu(vh),a=_.useCallback(A=>Xd(A,n)??A,[n]),[o,l]=_.useState(null),[c,d]=_.useState([]),[u,h]=_.useState(!0),[f,p]=_.useState(null),[x,v]=_.useState(!1),m=_.useCallback(async(A=!0)=>{if(t){A?h(!0):v(!0),p(null);try{const[N,M]=await Promise.all([dt.getRequest(t),dt.getWorkItemsByRequest(t)]);l(N),d(M.sort((L,j)=>new Date(j.createdAt).getTime()-new Date(L.createdAt).getTime()))}catch(N){const M=N instanceof Error?N.message:"Failed to load request";p(M)}finally{h(!1),v(!1)}}},[t]);_.useEffect(()=>{m(!0)},[m]),_.useEffect(()=>{if(!o||o.status==="done"||o.status==="cancelled")return;const A=setInterval(()=>{m(!1)},15e3);return()=>clearInterval(A)},[o==null?void 0:o.status,m]);const g=_.useCallback(()=>{e(qt.requests())},[e]),y=_.useCallback(A=>{e(qt.run(A))},[e]),b=_.useCallback(()=>{m(!1)},[m]),S=_.useCallback(async A=>{if(t)try{const N=A==="confirmed"?"done":"cancelled";await dt.updateRequest(t,{status:N}),m(!1)}catch(N){const M=N instanceof Error?N.message:"Failed to update request";p(M)}},[t,m]),E=_.useMemo(()=>o?o.totalInputTokens+o.totalOutputTokens:0,[o]),k=_.useMemo(()=>{if(!o)return"";const A=new Date(o.createdAt).getTime(),M=(o.completedAt?new Date(o.completedAt).getTime():Date.now())-A,L=Math.floor(M/6e4),j=Math.floor(L/60);return L<1?"< 1m":j<1?`${L}m`:`${j}h ${L%60}m`},[o]);if(u)return i.jsx("div",{className:"flex items-center justify-center h-64","data-testid":"request-detail-loading",children:i.jsx(zt,{})});if(f)return i.jsxs("div",{className:"p-6","data-testid":"request-detail-error",children:[i.jsx(ue,{variant:"ghost",size:"sm",icon:Ba,onClick:g,className:"mb-6",children:"Back to Requests"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsxs("div",{className:"flex flex-col items-center text-center py-8",children:[i.jsx("p",{className:"text-danger text-lg font-medium mb-2",children:"Failed to load Request"}),i.jsx("p",{className:"text-text-2 text-sm mb-4",children:f}),i.jsx(ue,{variant:"secondary",size:"sm",icon:$t,onClick:()=>m(!0),children:"Retry"})]})})]});if(!o)return i.jsxs("div",{className:"p-6","data-testid":"request-detail-not-found",children:[i.jsx(ue,{variant:"ghost",size:"sm",icon:Ba,onClick:g,className:"mb-6",children:"Back to Requests"}),i.jsx(tn,{variant:"default",padding:"lg",children:i.jsx(is,{icon:El,title:"Request not found.",compact:!0})})]});const T=[`Created ${sC(o.createdAt)}`,o.intentCategory?o.intentCategory.replace(/_/g," "):null,o.intentLevel?`Intent level ${o.intentLevel}`:null,o.priority&&o.priority!=="normal"?`${o.priority.charAt(0).toUpperCase()}${o.priority.slice(1)} priority`:null].filter(Boolean);return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-6","data-testid":"request-detail",children:[i.jsx(_r,{className:"mb-0",eyebrow:i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:qt.ticketsBoard(),className:"text-text-2 hover:text-text",children:"Tickets"}),i.jsx("span",{className:"text-text-3",children:"/"}),i.jsx(hs,{to:qt.requests(),className:"text-text-2 hover:text-text","data-testid":"request-detail-back",children:"Requests"})]}),title:o.title,subtitle:i.jsx(i.Fragment,{children:T.map((A,N)=>i.jsxs(an.Fragment,{children:[N>0&&" · ",A]},N))}),actions:i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:b,loading:x,"data-testid":"request-detail-refresh"}),tabs:i.jsx(Dc,{"aria-label":"Request views",idPrefix:"request",value:s,onChange:A=>r(A),tabs:vh.map(A=>({value:A,label:RBe[A]}))}),"data-testid":"request-detail-header"}),s==="timeline"?i.jsx("div",{role:"tabpanel",id:"request-panel-timeline","aria-labelledby":"request-tab-timeline","data-testid":"request-panel-timeline",children:i.jsx(rC,{traceId:o.traceId,refParam:"requestId",refId:o.id,nameOf:a})}):i.jsxs("div",{role:"tabpanel",id:"request-panel-overview","aria-labelledby":"request-tab-overview",className:"flex flex-col gap-6","data-testid":"request-panel-overview",children:[i.jsxs("div",{className:"-mt-2 flex flex-wrap items-center gap-x-4 gap-y-2 text-[13px] text-text-2",children:[i.jsx(sn,{tone:PBe(o.status),children:X2(o.status)}),o.requiresConfirmation&&i.jsx("span",{className:"font-semibold text-attention",children:"Requires confirmation"}),typeof o.ticketNumber=="number"&&i.jsxs("span",{children:["TKT-",String(o.ticketNumber).padStart(3,"0")]}),i.jsx(IBe,{currentStatus:o.status})]}),o.requiresConfirmation&&o.status==="waiting_confirmation"&&i.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-2xl bg-attention-soft px-4 py-3","data-testid":"request-action-area",children:[i.jsx("span",{className:"mr-auto text-sm text-text",children:"This request needs your confirmation before it completes"}),i.jsx(ue,{variant:"secondary",size:"sm",onClick:()=>S("rejected"),children:"Reject"}),i.jsx(ue,{variant:"primary",size:"sm",onClick:()=>S("confirmed"),children:"Approve"})]}),o.openItems&&o.openItems.length>0&&i.jsx(bBe,{items:o.openItems,onSkip:async A=>{await lre(o.id,A),await m(!1)}}),i.jsxs("section",{"aria-labelledby":"request-message-heading",children:[i.jsx("h2",{id:"request-message-heading",className:"mb-2 text-[15px] font-bold text-text",children:"Original message"}),o.description?i.jsx("p",{className:"whitespace-pre-wrap text-sm leading-relaxed text-text",children:o.description}):i.jsx("p",{className:"text-sm italic text-text-3",children:"No description provided."}),(o.sourceConversationItemId||o.tags.length>0)&&i.jsxs("p",{className:"mt-3 flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] text-text-3",children:[o.sourceConversationItemId&&i.jsxs("span",{children:["Source: ",i.jsx("span",{className:"font-mono",children:o.sourceConversationItemId})]}),o.tags.map(A=>i.jsx("span",{className:"rounded-full bg-surface-2 px-2 py-0.5 text-text-2",children:A},A))]})]}),i.jsxs("section",{"data-testid":"request-detail-workitems","aria-labelledby":"request-runs-heading",children:[i.jsxs("h2",{id:"request-runs-heading",className:"mb-2 text-[15px] font-bold text-text",children:["Runs ",i.jsx("span",{className:"text-[13px] font-normal text-text-2",children:c.length})]}),i.jsx(LBe,{workItems:c,onItemClick:y,names:n})]}),i.jsx(ti,{title:"Statistics",summary:"Tokens, cost, elapsed time, runs",children:i.jsxs("dl",{className:"grid max-w-md grid-cols-[1fr_auto] gap-x-6 gap-y-2 text-sm","data-testid":"request-detail-stats",children:[i.jsxs("dt",{className:"flex items-center gap-1.5 text-text-2",children:[i.jsx(g0,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Total tokens"]}),i.jsx("dd",{className:"text-right font-semibold text-text",children:qx(E)}),i.jsx("dt",{className:"pl-5 text-text-3",children:"Input"}),i.jsx("dd",{className:"text-right text-text-2",children:qx(o.totalInputTokens)}),i.jsx("dt",{className:"pl-5 text-text-3",children:"Output"}),i.jsx("dd",{className:"text-right text-text-2",children:qx(o.totalOutputTokens)}),i.jsxs("dt",{className:"flex items-center gap-1.5 text-text-2",children:[i.jsx(Qj,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Total cost"]}),i.jsx("dd",{className:"text-right font-semibold text-text",children:uX(o.totalCost)}),i.jsxs("dt",{className:"flex items-center gap-1.5 text-text-2",children:[i.jsx(jr,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Elapsed time"]}),i.jsx("dd",{className:"text-right font-semibold text-text",children:k}),i.jsxs("dt",{className:"flex items-center gap-1.5 text-text-2",children:[i.jsx(lM,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Runs"]}),i.jsx("dd",{className:"text-right font-semibold text-text",children:c.length})]})})]})]})};function PBe(t){return t==="open"||t==="in_progress"||t==="awaiting_followup"?"primary":t==="cancelled"?"neutral":eE(t)}bX.displayName="RequestDetail";const DBe="/api/experiments";class _X extends Error{constructor(e,n){super(e),this.status=n,this.name="ExperimentsApiError"}}async function SX(t){const e=await fetch(`${DBe}${t}`);let n={};try{n=await e.json()}catch{n={}}if(!e.ok||n.success===!1)throw new _X(n.error||`HTTP ${e.status}`,e.status);return n.data}function OBe(){return SX("")}function BBe(t){return SX(`/${encodeURIComponent(t)}`)}function wX(t){return t.status==="done"?t.verdict==="worked"?{label:"Worked",tone:"success"}:t.verdict==="didnt"?{label:"Didn't work",tone:"danger"}:{label:"Inconclusive",tone:"attention"}:t.status==="running"?{label:"Measuring",tone:"primary"}:t.status==="cancelled"?{label:"Cancelled",tone:"neutral"}:{label:"Not shipped",tone:"neutral"}}function EX(t){if(t.metric.label)return t.metric.label;const e=t.metric.page??t.metric.query??t.metric.event;return`${t.metric.source.toUpperCase()} ${t.metric.measure}${e?` · ${e}`:""}`}const FBe=()=>{const t=cs(),[e,n]=_.useState(null),[s,r]=_.useState(null),[a,o]=_.useState(!1),l=_.useCallback(async()=>{r(null),o(!1);try{const c=await OBe();n([...c].sort((d,u)=>u.updatedAt.localeCompare(d.updatedAt)))}catch(c){c instanceof _X&&c.status===503?o(!0):r(c instanceof Error?c.message:"Failed to load experiments")}},[]);return _.useEffect(()=>{l()},[l]),a?i.jsx(is,{icon:Qp,title:"Experiments are not running",description:"Experiment cards are switched off on this machine, or Crewly is still starting. Nothing to show yet.",action:i.jsx(ue,{variant:"secondary",size:"sm",icon:$t,onClick:()=>void l(),children:"Check again"}),"data-testid":"experiments-off"}):s?i.jsxs("div",{className:"flex flex-col items-center gap-3 py-10 text-center","data-testid":"experiments-error",children:[i.jsx("p",{className:"text-sm text-danger",children:s}),i.jsx(ue,{variant:"secondary",size:"sm",icon:$t,onClick:()=>void l(),children:"Retry"})]}):e?e.length===0?i.jsx(is,{icon:Qp,title:"No experiments yet",description:"An agent attaches an experiment to a ticket that should move a number; it is measured automatically after the change ships.","data-testid":"experiments-empty"}):i.jsx("ul",{className:"overflow-hidden rounded-2xl bg-surface","data-testid":"experiments-list",children:e.map(c=>{const d=wX(c),u=[c.id,EX(c),c.ticket?c.ticket.id:null,`${c.windowDays}-day window`].filter(Boolean).join(" · ");return i.jsx("li",{className:"list-none",children:i.jsx(Ts,{primary:c.title,meta:u,trailing:i.jsx(sn,{tone:d.tone,children:d.label}),onClick:()=>t(qt.experiment(c.id)),"data-testid":`experiment-row-${c.id}`})},c.id)})}):i.jsx("div",{className:"flex justify-center py-10","data-testid":"experiments-loading",children:i.jsx(zt,{})})},UBe={overview:"Overview",timeline:"Timeline"};function m1(t){return!t||t.total===null?"—":`${Number.isInteger(t.total)?t.total.toLocaleString():t.total.toFixed(3)} (${t.start} – ${t.end})`}function Vz(t){return t?[`${t.ticketsShipped} shipped (${t.ticketsStarted} started)`,t.ownerTouchesPerTicket===null?`${t.ownerTouches} owner touches`:`${t.ownerTouchesPerTicket} owner touches per ticket`,`stalls ${t.stalls===0?"none":Bi(t.stallMs)}`,t.costPerShippedTicket===null?`${Tc(t.costUsd)} spent`:`${Tc(t.costPerShippedTicket)} per shipped ticket`].join(" · "):"Not measured yet"}const zBe=({scope:t})=>{var e;return i.jsxs("section",{"aria-labelledby":"experiment-autopilot-heading","data-testid":"experiment-autopilot",children:[i.jsxs("h2",{id:"experiment-autopilot-heading",className:"mb-2 text-[15px] font-bold text-text",children:["Autopilot: ",t.projectName,t.label?` · ${t.label}`:""]}),i.jsxs("dl",{className:"grid max-w-xl grid-cols-[auto_1fr] gap-x-6 gap-y-2 text-sm",children:[t.processBaseline&&!t.processBaseline.noData&&i.jsxs(i.Fragment,{children:[i.jsx("dt",{className:"text-text-2",children:"Before"}),i.jsx("dd",{className:"text-text",children:Vz(t.processBaseline)})]}),i.jsx("dt",{className:"text-text-2",children:"During"}),i.jsx("dd",{className:"text-text",children:(e=t.processResult)!=null&&e.noData?"No autopilot work recorded":Vz(t.processResult)}),t.outcomes.map((n,s)=>i.jsxs(an.Fragment,{children:[i.jsx("dt",{className:"text-text-2",children:n.metric.label??`${n.metric.source} ${n.metric.measure}${n.metric.page?` ${n.metric.page}`:""}`}),i.jsx("dd",{className:"break-words text-text",children:n.verdictReason??(n.lastError?`Fetch failed: ${n.lastError}`:`${m1(n.baseline)} → ${m1(n.result)}`)})]},s))]})]})},CX=()=>{const{id:t=""}=Ic(),[e,n]=cu(vh),[s,r]=_.useState(null),[a,o]=_.useState(null),[l,c]=_.useState(!0),d=_.useCallback(async()=>{c(!0),o(null);try{r(await BBe(t))}catch(p){o(p instanceof Error?p.message:"Failed to load the experiment")}finally{c(!1)}},[t]);_.useEffect(()=>{d()},[d]);const u=i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:qt.ticketsBoard(),className:"text-text-2 hover:text-text",children:"Tickets"}),i.jsx("span",{className:"text-text-3",children:"/"}),i.jsx(hs,{to:qt.experiments(),className:"text-text-2 hover:text-text","data-testid":"experiment-detail-back",children:"Experiments"})]});if(l&&!s)return i.jsx("div",{className:"flex h-64 items-center justify-center","data-testid":"experiment-detail-loading",children:i.jsx(zt,{})});if(a||!s)return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-4 sm:p-6","data-testid":"experiment-detail-error",children:[i.jsx(_r,{className:"mb-0",eyebrow:u,title:"Experiment"}),i.jsx(is,{icon:Qp,title:"Experiment not found",description:a??void 0,action:i.jsx(ue,{variant:"secondary",size:"sm",icon:$t,onClick:()=>void d(),children:"Retry"})})]});const h=wX(s),f=s.traceId.startsWith("tr-")?s.traceId:null;return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-4 sm:p-6","data-testid":"experiment-detail",children:[i.jsx(_r,{className:"mb-0",eyebrow:u,title:s.title,subtitle:`${s.id} · ${EX(s)} · ${s.windowDays}-day window · by ${s.createdBy}`,actions:i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:()=>void d(),loading:l}),tabs:i.jsx(Dc,{"aria-label":"Experiment views",idPrefix:"experiment",value:e,onChange:p=>n(p),tabs:vh.map(p=>({value:p,label:UBe[p]}))})}),e==="timeline"?i.jsx("div",{role:"tabpanel",id:"experiment-panel-timeline","aria-labelledby":"experiment-tab-timeline","data-testid":"experiment-panel-timeline",children:i.jsx(rC,{traceId:f,refParam:"experimentId",refId:s.id})}):i.jsxs("div",{role:"tabpanel",id:"experiment-panel-overview","aria-labelledby":"experiment-tab-overview",className:"flex flex-col gap-6","data-testid":"experiment-panel-overview",children:[i.jsxs("div",{className:"-mt-2 flex flex-wrap items-center gap-x-4 gap-y-2 text-[13px] text-text-2",children:[i.jsx(sn,{tone:h.tone,children:h.label}),s.ticket&&i.jsxs("span",{children:["Ticket ",s.ticket.id]}),s.dueAt&&s.status==="running"&&i.jsxs("span",{children:["Measured after ",s.dueAt.slice(0,10)]})]}),i.jsxs("section",{"aria-labelledby":"experiment-hypothesis-heading",children:[i.jsx("h2",{id:"experiment-hypothesis-heading",className:"mb-2 text-[15px] font-bold text-text",children:"Hypothesis"}),i.jsx("p",{className:"whitespace-pre-wrap text-sm leading-relaxed text-text",children:s.hypothesis})]}),i.jsxs("dl",{className:"grid max-w-xl grid-cols-[auto_1fr] gap-x-6 gap-y-2 text-sm","data-testid":"experiment-results",children:[i.jsx("dt",{className:"text-text-2",children:"Baseline"}),i.jsx("dd",{className:"text-text",children:m1(s.baseline)}),i.jsx("dt",{className:"text-text-2",children:"Result"}),i.jsx("dd",{className:"text-text",children:m1(s.result)}),i.jsx("dt",{className:"text-text-2",children:"Verdict"}),i.jsx("dd",{className:"text-text",children:s.verdict?`${h.label}${s.verdictReason?` — ${s.verdictReason}`:""}`:"Not measured yet"}),s.lastError&&i.jsxs(i.Fragment,{children:[i.jsx("dt",{className:"text-text-2",children:"Last error"}),i.jsx("dd",{className:"break-words text-danger",children:s.lastError})]})]}),s.autopilot&&i.jsx(zBe,{scope:s.autopilot}),i.jsxs("section",{"aria-labelledby":"experiment-log-heading",children:[i.jsx("h2",{id:"experiment-log-heading",className:"mb-2 text-[15px] font-bold text-text",children:"Card log"}),i.jsx("ol",{className:"flex flex-col gap-1.5 text-[13px]","data-testid":"experiment-card-log",children:[...s.timeline].reverse().map((p,x)=>i.jsxs("li",{className:"flex gap-3",children:[i.jsx("span",{className:"w-28 shrink-0 text-text-3",children:w0(p.at)}),i.jsxs("span",{className:"min-w-0 break-words text-text",children:[i.jsx("span",{className:"font-semibold",children:p.event.replace(/_/g," ")}),p.detail?i.jsxs("span",{className:"text-text-2",children:[" — ",p.detail]}):null]})]},`${p.at}-${x}`))})]})]})]})};CX.displayName="ExperimentDetail";const HBe={request:"Request",goal:"Goal",experiment:"Experiment",owner_message:"Your message",autopilot:"Autopilot run",ticket:"Ticket",triage:"Autopilot triage"},kX=()=>{const{traceId:t=""}=Ic(),{names:e}=Pm(),[n,s]=_.useState(null),r=_.useCallback(o=>Xd(o,e)??o,[e]),a=_.useCallback(o=>s(o.root),[]);return i.jsxs("div",{className:"mx-auto flex max-w-[1200px] flex-col gap-6 p-4 sm:p-6","data-testid":"trace-detail",children:[i.jsx(_r,{className:"mb-0",eyebrow:i.jsxs("nav",{"aria-label":"Breadcrumb",className:"flex items-center gap-1.5",children:[i.jsx(hs,{to:qt.ticketsBoard(),className:"text-text-2 hover:text-text",children:"Tickets"}),i.jsx("span",{className:"text-text-3",children:"/"}),i.jsx("span",{className:"text-text-2",children:"Run timeline"})]}),title:(n==null?void 0:n.summary)??"Run timeline",subtitle:n?`${HBe[n.kind]} · started ${w0(n.createdAt)}`:void 0}),i.jsx(rC,{traceId:t,nameOf:r,onLoaded:a})]})};kX.displayName="TraceDetail";const GBe=t=>i.jsx(p$,{...t});function $Be(t){return{active:"Active",blocked:"Blocked",waiting_confirmation:"Waiting Confirmation",done:"Done"}[t]??t}function Kz(t){return t.charAt(0).toUpperCase()+t.slice(1)}function WBe(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 VBe(t){return t===0?"$0.00":t<.01?`$${t.toFixed(4)}`:`$${t.toFixed(2)}`}function KBe(t){return{total:t.length,active:t.filter(e=>e.status==="active").length,blocked:t.filter(e=>e.status==="blocked").length,waitingConfirmation:t.filter(e=>e.status==="waiting_confirmation").length,done:t.filter(e=>e.status==="done").length,totalCost:t.reduce((e,n)=>e+(n.totalCost||0),0)}}function qBe(t){switch(t){case"open":case"ready":case"running":case"awaiting_followup":return"active";case"blocked":return"blocked";case"waiting_confirmation":return"waiting_confirmation";case"done":case"cancelled":return"done";default:return typeof console<"u"&&t&&console.warn("[RequestList] Unknown backend Request status:",t),"active"}}function XBe(t){switch(t){case"high":return"high";case"low":return"low";default:return"medium"}}const YBe=new Set(["open","waiting_owner","ready","overdue"]);function JBe(t){return Array.isArray(t)?t.filter(e=>e&&typeof e=="object"&&YBe.has(String(e.status))).length:0}function ZBe(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:qBe(e.status||""),priority:XBe(e.priority||""),source:(e.tags||[]).includes("slack")?"slack":"api",requester:"user",category:s&&s.length>0?s:void 0,workItemCount:n.length,updatedAt:e.updatedAt||e.createdAt||new Date().toISOString(),missionLink:e.missionId?`Mission: ${e.missionId.slice(0,8)}`:void 0,totalInputTokens:e.totalInputTokens||0,totalOutputTokens:e.totalOutputTokens||0,totalCost:e.totalCost||0,ownerAgent:e.ownerAgent||void 0,openItemCount:JBe(e.openItems)}}).sort((e,n)=>new Date(n.updatedAt).getTime()-new Date(e.updatedAt).getTime())}const QBe=25,eFe=300,tFe={slack:Cc,email:BH,chat:FH,api:sR,manual:zH},nFe={active:"primary",blocked:"danger",waiting_confirmation:"attention",done:"success"},ox={active:"Active",blocked:"Blocked",waiting_confirmation:"Waiting",done:"Done"},sFe={status:["active"],only:[]},rFe=()=>{const t=cs(),{names:e}=Pm(),[n,s]=_.useState([]),[r,a]=_.useState(!0),[o,l]=_.useState(null),[c,d]=_.useState(sFe),[u,h]=_.useState(""),[f,p]=_.useState("");_.useEffect(()=>{const y=setTimeout(()=>p(u),eFe);return()=>clearTimeout(y)},[u]);const x=_.useCallback(async()=>{a(!0),l(null);try{const y=await dt.getRequests();s(Array.isArray(y)?ZBe(y):[])}catch(y){l(y instanceof Error?y.message:"Failed to load requests"),s([])}finally{a(!1)}},[]);_.useEffect(()=>{x()},[x]);const v=_.useMemo(()=>KBe(n),[n]),m=_.useMemo(()=>[{id:"status",label:"Status",single:!0,options:[{value:"active",label:ox.active,count:v.active},{value:"blocked",label:ox.blocked,count:v.blocked},{value:"waiting_confirmation",label:ox.waiting_confirmation,count:v.waitingConfirmation},{value:"done",label:ox.done,count:v.done}]},{id:"only",label:"Only",options:[{value:"assigned_to_me",label:"Assigned to me"},{value:"urgent",label:"Urgent"}]}],[v]),g=_.useMemo(()=>{var E;const y=(E=c.status)==null?void 0:E[0],b=c.only??[],S=f.trim().toLowerCase();return n.filter(k=>!(y&&k.status!==y||b.includes("urgent")&&k.priority!=="critical"&&k.priority!=="high"||b.includes("assigned_to_me")&&k.requester!=="user"||S&&!(k.title.toLowerCase().includes(S)||k.requester.toLowerCase().includes(S)||(k.missionLink??"").toLowerCase().includes(S))))},[n,c,f]);return i.jsxs("div",{className:"flex min-w-0 flex-col gap-4","data-testid":"requests-page",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(Jo,{groups:m,value:c,onChange:d}),i.jsx(YR,{value:u,onChange:h,placeholder:"Search requests…","data-testid":"request-search-input"}),i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:()=>void x(),className:"ml-auto"})]}),r?i.jsx("div",{"data-testid":"request-list-loading",children:i.jsx(Q1,{count:4})}):o?i.jsxs("div",{className:"flex flex-col items-center gap-3 py-16 text-text-2","data-testid":"request-list-error",children:[i.jsx("span",{className:"text-sm text-danger",children:o}),i.jsx(ue,{variant:"link",onClick:()=>void x(),children:"Retry"})]}):g.length===0?i.jsxs("div",{className:"flex flex-col items-center gap-3 py-16 text-text-2","data-testid":"request-list-empty",children:[i.jsx($S,{className:"h-10 w-10 opacity-40","aria-hidden":"true"}),i.jsx("span",{className:"text-sm",children:n.length===0?"No requests yet. They appear here when you ask for something in Slack or chat.":"No requests match the current filters."})]}):i.jsx("div",{className:"overflow-hidden rounded-2xl bg-surface","data-testid":"request-list",children:i.jsx(fs,{limit:QBe,as:"ul","data-testid":"request-list-rows",children:g.map(y=>{const b=tFe[y.source]??$S,S=Xd(y.ownerAgent,e),E=[y.category?y.category.replace(/_/g," "):null,S?`via ${S}`:null,y.priority==="high"||y.priority==="critical"?"Urgent":null,y.workItemCount>0?`${y.workItemCount} run${y.workItemCount===1?"":"s"}`:null,y.missionLink?y.missionLink.replace(/^Mission:/,"Goal:"):null,WBe(y.updatedAt)].filter(Boolean),k=y.openItemCount??0;return i.jsx("li",{className:"list-none border-b border-border-soft last:border-b-0","data-testid":`request-row-${y.id}`,children:i.jsx(Ts,{leading:i.jsx("span",{title:Kz(y.source),children:i.jsx(b,{className:"h-4 w-4 text-text-3","aria-label":Kz(y.source)})}),primary:i.jsx("span",{title:y.title,children:XR(y.title)}),meta:i.jsxs(i.Fragment,{children:[k>0&&i.jsxs("span",{className:"font-semibold text-attention",title:"Promises or questions the agent still owes you",children:[k," open item",k===1?"":"s",E.length>0?" · ":""]}),E.join(" · ")]}),trailing:i.jsx(sn,{tone:nFe[y.status],title:$Be(y.status),children:ox[y.status]}),onClick:()=>t(qt.request(y.id)),className:"border-b-0","data-testid":`request-row-${y.id}-row`})},y.id)})})}),!r&&!o&&n.length>0&&i.jsxs("p",{className:"text-[13px] text-text-3","data-testid":"requests-total",children:[v.total," request",v.total===1?"":"s"," · total cost ",VBe(v.totalCost)]})]})},iFe=25,aFe=300,oFe=[{value:"running",label:"Running"},{value:"queued",label:"Queued"},{value:"done",label:"Completed"},{value:"failed",label:"Failed"},{value:"blocked",label:"Blocked"},{value:"cancelled",label:"Cancelled"}],qz={running:0,blocked:1,failed:2,done:3,completed:3,cancelled:4,queued:5,scheduled:5},AX=()=>{const t=cs(),{names:e}=Pm(),n=pX(),[s,r]=_.useState([]),[a,o]=_.useState(!0),[l,c]=_.useState(null),[d,u]=_.useState({status:[]}),[h,f]=_.useState(""),[p,x]=_.useState(""),v=_.useRef(),m=_.useCallback(E=>{f(E),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>x(E),aFe)},[]);_.useEffect(()=>()=>{v.current&&clearTimeout(v.current)},[]);const g=_.useCallback(async()=>{o(!0),c(null);try{const E=await dt.getWorkItems();r(Array.isArray(E)?E:[])}catch(E){c(E instanceof Error?E.message:"Failed to load runs")}finally{o(!1)}},[]);_.useEffect(()=>{g()},[g]);const y=_.useMemo(()=>{const E={};for(const k of s){const T=k.status==="scheduled"?"queued":k.status;E[T]=(E[T]||0)+1}return E},[s]),b=_.useMemo(()=>[{id:"status",label:"Status",single:!0,options:oFe.map(E=>({...E,count:y[E.value]??0}))}],[y]),S=_.useMemo(()=>{var T;const E=(T=d.status)==null?void 0:T[0],k=p.trim().toLowerCase();return s.filter(A=>!(E&&A.status!==E&&!(E==="queued"&&A.status==="scheduled")||k&&!(A.title.toLowerCase().includes(k)||A.id.toLowerCase().includes(k)||(A.target??"").toLowerCase().includes(k)||(Xd(A.target,e)??"").toLowerCase().includes(k)||A.type.toLowerCase().includes(k)))).sort((A,N)=>{const M=qz[A.status]??5,L=qz[N.status]??5;return M!==L?M-L:new Date(N.createdAt).getTime()-new Date(A.createdAt).getTime()})},[s,d,p,e]);return i.jsxs("div",{className:"flex min-w-0 flex-col gap-4","data-testid":"workitems-page",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(Jo,{groups:b,value:d,onChange:u}),i.jsx(YR,{value:h,onChange:m,placeholder:"Search by title, ID, agent…","data-testid":"workitems-search"}),i.jsx(Zt,{icon:$t,variant:"ghost","aria-label":"Refresh",onClick:()=>void g(),className:"ml-auto","data-testid":"workitems-refresh"})]}),a&&i.jsx("div",{"data-testid":"workitems-loading",children:i.jsx(Q1,{count:4})}),l&&!a&&i.jsxs(Ye,{variant:"error",title:"Failed to load runs",onClose:()=>c(null),"data-testid":"workitems-error",children:[l,i.jsx(ue,{variant:"ghost",size:"sm",onClick:()=>void g(),className:"mt-2",children:"Retry"})]}),!a&&!l&&S.length===0&&i.jsxs("div",{className:"flex flex-col items-center gap-3 py-16 text-text-2","data-testid":"workitems-empty",children:[i.jsx($S,{className:"h-10 w-10 opacity-40","aria-hidden":"true"}),i.jsx("span",{className:"text-sm",children:s.length===0?"No runs yet.":"No runs match the current filters."})]}),!a&&!l&&S.length>0&&i.jsx("div",{className:"overflow-hidden rounded-2xl bg-surface","data-testid":"workitems-list",children:i.jsx(fs,{limit:iFe,as:"ul",children:S.map(E=>{const k=h$(E.title,n),T=Xd(E.target,e,!0),A=[nP(E.type),T,k,sC(E.createdAt)].filter(Boolean).join(" · ");return i.jsx("li",{className:"list-none border-b border-border-soft last:border-b-0",children:i.jsx(Ts,{primary:i.jsx("span",{title:`${E.title} (${E.id.slice(0,8)})`,children:E.title}),meta:A,trailing:i.jsx(sn,{tone:eE(E.status==="cancelled"||E.status==="queued"||E.status==="scheduled"?"neutral":E.status),children:tP(E.status)}),onClick:()=>t(qt.run(E.id)),className:"border-b-0","data-testid":`workitem-row-${E.id}`})},E.id)})})}),!a&&!l&&s.length>0&&i.jsxs("p",{className:"text-[13px] text-text-3","data-testid":"workitems-total",children:[s.length," run",s.length===1?"":"s"," in the pool"]})]})};AX.displayName="WorkItems";const lFe=({onCreated:t})=>{const[e,n]=_.useState(!1),[s,r]=_.useState([]),[a,o]=_.useState([]),l=()=>{n(!0),Promise.resolve().then(()=>dt.getProjects()).then(c=>r((c??[]).map(d=>({id:d.id,name:d.name})))).catch(()=>r([])),Promise.resolve().then(()=>dt.getTeams()).then(c=>o(c??[])).catch(()=>o([]))};return i.jsxs(i.Fragment,{children:[i.jsx(ue,{size:"sm",icon:qn,onClick:l,"data-testid":"tickets-new-ticket",children:ui.NEW_TICKET}),i.jsx(f$,{open:e,ticket:null,projects:s,teams:a,onClose:()=>n(!1),onSaved:t})]})},cFe={board:"Board",requests:"Requests",runs:"Runs",experiments:"Experiments"},dFe={board:"Everything your crew is working on",requests:"Everything you asked for, from every channel",runs:"What the agents actually ran",experiments:"Changes that should move a number, and whether they did"},uFe=()=>{const[t,e]=cu(CO),[n,s]=_.useState(0),[r,a]=_.useState(null),o=_.useCallback(l=>a(l.toReview),[]);return i.jsxs("div",{children:[i.jsx(_r,{title:"Tickets",subtitle:dFe[t],actions:i.jsx(lFe,{onCreated:()=>s(l=>l+1)}),tabs:i.jsx(Dc,{"aria-label":"Tickets views",idPrefix:"tickets",value:t,onChange:l=>e(l),tabs:CO.map(l=>({value:l,label:cFe[l],...l==="board"&&r?{count:r,attention:!0}:{}}))})}),i.jsxs("div",{role:"tabpanel",id:`tickets-panel-${t}`,"aria-labelledby":`tickets-tab-${t}`,"data-testid":`tickets-panel-${t}`,children:[t==="board"&&i.jsx(GBe,{showNewTicket:!1,refreshKey:n,onCountsChange:o}),t==="requests"&&i.jsx(rFe,{}),t==="runs"&&i.jsx(AX,{}),t==="experiments"&&i.jsx(FBe,{})]})]})},hFe=({member:t,teamId:e,onClose:n})=>{const[s,r]=_.useState(null),[a,o]=_.useState(!1),[l,c]=_.useState(null),[d,u]=_.useState(!1),[h,f]=_.useState(null),[p,x]=_.useState(!1),[v,m]=_.useState("prompt"),g=_.useRef(null);_.useEffect(()=>(y(),()=>{S()}),[t.id,e]);const y=async()=>{if(!t.sessionName){c("No active session for this team member");return}try{o(!0),c(null),jt.isConnected()||await jt.connect(),b(),jt.subscribeToSession(t.sessionName),await E()}catch(L){console.error("Error initializing terminal:",L),c("Failed to connect to terminal"),x(!1)}finally{o(!1)}},b=()=>{if(!t.sessionName)return;const L=G=>{G.sessionName===t.sessionName&&(r(K=>({...K,memberId:t.id,memberName:t.name,sessionName:t.sessionName,output:G.content,timestamp:G.timestamp})),setTimeout(()=>{g.current&&(g.current.scrollTop=g.current.scrollHeight)},10))},j=G=>{G.sessionName===t.sessionName&&(r({memberId:t.id,memberName:t.name,sessionName:t.sessionName,output:G.content,timestamp:G.timestamp}),x(!0),c(null))},D=G=>{G.sessionName===t.sessionName&&(console.log("Successfully subscribed to session:",G.sessionName),x(!0),c(null))},U=G=>{G.sessionName===t.sessionName&&(console.error("WebSocket error for session:",G),c(G.error||"WebSocket error occurred"),x(!1))},$=()=>{x(!0)};return jt.on("terminal_output",L),jt.on("initial_terminal_state",j),jt.on("subscription_confirmed",D),jt.on("error",U),jt.on("connected",$),()=>{jt.off("terminal_output",L),jt.off("initial_terminal_state",j),jt.off("subscription_confirmed",D),jt.off("error",U),jt.off("connected",$)}},S=()=>{h&&clearInterval(h),t.sessionName&&jt.isConnected()&&jt.unsubscribeFromSession(t.sessionName)};_.useEffect(()=>{if(d){const L=setInterval(()=>{E()},15e3);f(L)}else h&&(clearInterval(h),f(null));return()=>{h&&clearInterval(h)}},[d]);const E=async()=>{if(!t.sessionName){c("No active session for this team member");return}o(!0),c(null);try{const L=await fetch(`/api/teams/${e}/members/${t.id}/session?lines=100`);if(L.ok){const j=await L.json();j.success?r(j.data):c(j.error||"Failed to fetch session data")}else{const j=await L.json();c(j.error||"Failed to fetch session data")}}catch(L){c("Network error while fetching session data"),console.error("Error fetching session data:",L)}finally{o(!1)}},k=L=>({orchestrator:"text-primary",pm:"text-blue-400",developer:"text-emerald-400",qa:"text-amber-400",tester:"text-red-400",designer:"text-pink-400"})[L]||"text-text-secondary-dark",T=L=>({activating:"warning",active:"success"})[L]||"default",A=L=>L==="in_progress"?"success":"default",N=L=>new Date(L).toLocaleString(),M=i.jsxs("span",{className:"flex flex-col gap-2",children:[i.jsx("span",{children:t.name}),i.jsxs("span",{className:"flex flex-wrap items-center gap-1.5",children:[i.jsx(mn,{className:k(t.role),children:t.role}),i.jsxs(mn,{variant:T(t.agentStatus),children:["Agent: ",t.agentStatus]}),i.jsxs(mn,{variant:A(t.workingStatus),children:["Work: ",t.workingStatus]})]})]});return i.jsx(Lr,{isOpen:!0,onClose:n,title:M,size:"xxl",children:i.jsxs(Y1,{value:v,onValueChange:L=>m(L),children:[i.jsxs(J1,{"aria-label":"Member details",children:[i.jsx(Oh,{value:"prompt",children:"System Prompt"}),i.jsx(Oh,{value:"terminal",children:"Terminal Output"})]}),i.jsx(b0,{value:"prompt",children:i.jsx("pre",{className:"max-h-[55vh] overflow-auto whitespace-pre-wrap rounded-2xl border border-border-dark bg-background-dark p-4 text-xs font-mono text-text-primary-dark",children:t.systemPrompt})}),i.jsxs(b0,{value:"terminal",className:"space-y-3",children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[i.jsx("div",{className:"text-xs text-text-secondary-dark",children:t.sessionName&&i.jsxs("span",{children:["Session: ",t.sessionName]})}),i.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[i.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-text-secondary-dark",children:[i.jsx(ER,{status:p?"online":"offline",size:"sm"}),p?"Live":"Offline"]}),i.jsx(Gi,{size:"sm",label:"Auto-refresh (fallback)",checked:d,onChange:L=>u(L.target.checked),disabled:p}),i.jsx(ue,{onClick:E,disabled:p,loading:a,variant:"secondary",size:"sm",children:a?"Loading...":"Manual Refresh"})]})]}),a&&!s&&i.jsx(zt,{size:"md",text:"Loading session data...",className:"py-8"}),l&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs(Ye,{variant:"error",children:["Error: ",l]}),i.jsx(ue,{onClick:E,variant:"outline",size:"sm",children:"Retry"})]}),s&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs("p",{className:"text-xs text-text-secondary-dark",children:["Last updated: ",N(s.timestamp)]}),i.jsx("pre",{className:"max-h-[50vh] overflow-auto whitespace-pre-wrap rounded-2xl border border-border-dark bg-background-dark p-4 text-xs font-mono text-text-primary-dark",ref:g,children:s.output||"No output available"})]}),!a&&!l&&!s&&i.jsx(is,{compact:!0,title:"No session data available"})]})]})})},fFe={xs:"w-6 h-6 text-xs",sm:"w-8 h-8 text-sm",md:"w-10 h-10 text-base",lg:"w-12 h-12 text-lg",xl:"w-16 h-16 text-xl"},pFe={active:"bg-green-500",inactive:"bg-text-secondary-dark",activating:"bg-yellow-500"},mFe=({name:t,avatar:e,size:n="md",className:s="",showStatus:r=!1,status:a,ringClass:o=""})=>{const l=fFe[n],c=()=>{if(e&&(e.startsWith("http")||e.startsWith("data:")))return i.jsx("img",{src:e,alt:`${t}'s avatar`,title:t,className:`${l} rounded-full object-cover ${o} ${s}`});if(e)return i.jsx("div",{className:`${l} rounded-full bg-background-dark border border-border-dark flex items-center justify-center ${o} ${s}`,title:t,children:i.jsx("span",{children:e})});const d=t?t.charAt(0).toUpperCase():"";return i.jsx("div",{className:`${l} rounded-full bg-background-dark border border-border-dark flex items-center justify-center ${o} ${s}`,title:t,children:d})};return i.jsxs("div",{className:"relative inline-block",children:[c(),r&&a&&i.jsx("span",{className:`absolute bottom-0 right-0 w-3 h-3 ${pFe[a]} rounded-full border-2 border-surface-dark`,title:a})]})};function gFe(t){const e=new Map;for(const n of t)if(n.parentTeamId){const s=e.get(n.parentTeamId)||[];s.push(n),e.set(n.parentTeamId,s)}return e}const TX=({team:t,depth:e,childrenMap:n,projectMap:s,onTeamClick:r})=>{var f;const a=n.get(t.id)||[],[o,l]=_.useState(!0),c=a.length>0,d=t.members||[],u=d.some(p=>p.agentStatus==="active"),h=(f=t.projectIds)!=null&&f[0]?s[t.projectIds[0]]:void 0;return i.jsxs("div",{"data-testid":`tree-node-${t.id}`,children:[i.jsxs("div",{className:"flex items-center gap-2 py-2 px-3 rounded-lg hover:bg-background-dark cursor-pointer transition-colors group",style:{paddingLeft:`${e*24+12}px`},onClick:()=>r(t.id),children:[c?i.jsx("button",{onClick:p=>{p.stopPropagation(),l(!o)},className:"p-0.5 text-text-secondary-dark hover:text-text-primary-dark","data-testid":`toggle-${t.id}`,"aria-label":o?"Collapse":"Expand","aria-expanded":o,children:o?i.jsx(wo,{className:"w-4 h-4"}):i.jsx(cr,{className:"w-4 h-4"})}):i.jsx("span",{className:"w-5"}),i.jsx("span",{className:"font-medium text-sm truncate",children:t.name}),u&&i.jsx("span",{className:"shrink-0 px-1.5 py-0.5 text-[10px] font-medium rounded-full bg-green-500/10 text-green-400",children:"Active"}),i.jsxs("span",{className:"text-xs text-text-secondary-dark ml-auto flex items-center gap-1",children:[i.jsx(vr,{className:"w-3 h-3"}),d.length]}),h&&i.jsxs("span",{className:"text-xs text-text-secondary-dark flex items-center gap-1 ml-2",children:[i.jsx(qo,{className:"w-3 h-3"}),h]}),i.jsx("div",{className:"flex items-center ml-2",children:d.slice(0,3).map((p,x)=>i.jsx("div",{style:{marginLeft:x===0?0:-4},children:i.jsx(mFe,{name:p.name,avatar:p.avatar,size:"xs",ringClass:"ring-1 ring-surface-dark"})},p.id))})]}),c&&o&&i.jsx("div",{"data-testid":`children-${t.id}`,children:a.map(p=>i.jsx(TX,{team:p,depth:e+1,childrenMap:n,projectMap:s,onTeamClick:r},p.id))})]})},xFe=({teams:t,projectMap:e,onTeamClick:n})=>{const s=_.useMemo(()=>gFe(t),[t]),r=_.useMemo(()=>t.filter(a=>!a.parentTeamId),[t]);return r.length===0?i.jsx("div",{className:"text-center py-8 text-text-secondary-dark text-sm",children:"No teams to display"}):i.jsx("div",{className:"bg-surface-dark border border-border-dark rounded-xl p-2","data-testid":"teams-tree-view",children:r.map(a=>i.jsx(TX,{team:a,depth:0,childrenMap:s,projectMap:e,onTeamClick:n},a.id))})};function yFe(t){return(t.members??[]).reduce((e,n)=>{const s=n.readyAt||n.updatedAt;return s?e?new Date(s)>new Date(e)?s:e:s:e},null)}function vFe(t,e,n){var a;const s=t.members??[];return(((a=t.projectIds)==null?void 0:a.length)??0)>0?{label:e??"Project",needsProject:!1}:s.some(o=>o.role==="orchestrator"||o.role==="auditor")?{label:"System team",needsProject:!1}:t.parentTeamId||(n??0)>0?{label:"Parent team",needsProject:!1}:{label:"No project yet",needsProject:!0}}const bFe=({team:t,projectName:e,subTeamCount:n,onOpen:s,onEdit:r,onStart:a,onStop:o,onOpenChat:l,onOpenWiki:c,onDelete:d,isPinned:u=!1,onTogglePin:h,onPause:f,onResume:p})=>{const[x,v]=_.useState(null),m=t.members??[],g=m.some(M=>M.agentStatus==="active"),y=m.filter(M=>M.loginRequired),b=vFe(t,e,n),S=S$(t),E=yFe(t),k=(n??0)>0?`${n} sub-team${n===1?"":"s"} · ${m.length} member${m.length===1?"":"s"}`:m.length===0?"No members":m.map(M=>M.name).join(", "),T=i.jsxs(i.Fragment,{children:[i.jsx("span",{className:b.needsProject?"text-attention":void 0,"data-testid":b.needsProject?"assign-project-cta":void 0,children:b.label}),i.jsx("span",{className:"text-text-3",children:" · "}),i.jsx("span",{children:k}),E&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-text-3",children:" · "}),i.jsx("span",{title:`Last activity: ${new Date(E).toLocaleString()}`,children:Nl(E)})]})]}),A=[{label:"View team",onClick:()=>s(t.id)},...r?[{label:"Edit team",onClick:()=>r(t.id)}]:[],...l?[{label:"Open chat",onClick:()=>l(t.id)}]:[],...c?[{label:"Open wiki",onClick:()=>c(t.id)}]:[],...h?[{label:u?"Unpin from favorites":"Pin to favorites",onClick:h}]:[],...!S&&f?[{label:"Pause team…",onClick:()=>f(t.id)}]:[],...S&&p?[{label:"Resume team",onClick:()=>p(t.id)}]:[],...d?[{label:"Delete team",danger:!0,separator:!0,onClick:()=>v("delete")}]:[]],N=S&&p?i.jsx(ue,{variant:"secondary",size:"xs",onClick:()=>p(t.id),"data-testid":`resume-btn-${t.id}`,children:"Resume"},"resume"):g?o&&i.jsx(ue,{variant:"secondary",size:"xs",onClick:()=>v("stop"),"data-testid":`stop-btn-${t.id}`,children:"Stop"},"stop"):a&&i.jsx(ue,{variant:"secondary",size:"xs",onClick:()=>a(t.id),"data-testid":`start-btn-${t.id}`,children:"Start"},"start");return i.jsxs(i.Fragment,{children:[i.jsx(Ts,{"data-testid":`team-row-${t.id}`,onClick:()=>s(t.id),primary:i.jsxs("span",{className:"inline-flex min-w-0 items-center gap-2",children:[i.jsx("span",{className:"truncate",children:t.name}),u&&i.jsx(ty,{className:"h-3.5 w-3.5 shrink-0 text-text-3","aria-label":"Pinned"})]}),meta:T,trailing:i.jsxs("span",{className:"flex items-center gap-2",children:[y.length>0&&i.jsx("span",{className:"flex items-center gap-1","data-testid":"team-sign-in-needed",children:y.map(M=>i.jsx(DR,{loginRequired:M.loginRequired,agentLabel:M.name,runtimeType:M.runtimeType},M.id))}),S?i.jsx("span",{title:w$(t),"data-testid":`team-paused-${t.id}`,children:i.jsx(sn,{tone:"attention",children:"Paused"})}):i.jsx(sn,{tone:g?"success":"neutral",children:g?"Active":"Idle"})]}),actions:N?[N]:void 0,overflow:A,overflowLabel:`More actions for ${t.name}`}),i.jsx(B0,{isOpen:x==="stop",onCancel:()=>v(null),onConfirm:()=>{v(null),o==null||o(t.id)},title:"Stop Team",message:`Are you sure you want to stop all agents in "${t.name}"? Active work will be interrupted.`,confirmLabel:"Stop Team",confirmVariant:"danger"}),i.jsx(B0,{isOpen:x==="delete",onCancel:()=>v(null),onConfirm:()=>{v(null),d==null||d(t.id)},title:"Delete Team",message:`Delete team "${t.name}"? Its members and terminal sessions are removed. This cannot be undone.`,confirmLabel:"Delete",confirmVariant:"danger"})]})},Xz=3e4,_Fe=3e5,SFe=2;function wFe(t,e,n,s){const[r,a]=_.useState([]),[o,l]=_.useState(!1),[c,d]=_.useState(null),u=_.useRef(null),h=_.useRef(!0),f=_.useRef(0),p=_.useRef(null),x=_.useRef(!1),v=_.useRef(t),m=_.useRef(n),g=_.useRef(s),y=_.useRef(e);v.current=t,m.current=n,g.current=s,y.current=e;const b=_.useCallback(()=>f.current===0?Xz:Math.min(Xz*Math.pow(SFe,f.current),_Fe),[]),S=_.useCallback(()=>{if(!h.current||!y.current)return;u.current&&clearTimeout(u.current);const A=b();u.current=setTimeout(()=>{k()},A)},[b]),E=_.useCallback(async()=>{var A;if(!x.current){x.current=!0;try{const M=await(await fetch("/api/cloud/device-id")).json();M.success&&((A=M.data)!=null&&A.deviceId)&&(p.current=M.data.deviceId)}catch{}}},[]),k=_.useCallback(async()=>{const A=v.current;if(!A||!h.current)return;await E();const N={"Content-Type":"application/json",Authorization:`Bearer ${A}`};try{const M={deviceName:g.current,teams:m.current};p.current&&(M.deviceId=p.current),await fetch(`${BM}/devices/heartbeat`,{method:"POST",headers:N,body:JSON.stringify(M)});const j=await(await fetch(`${BM}/devices`,{headers:N})).json();h.current&&j.success&&(a(j.data||[]),d(null),f.current=0)}catch(M){h.current&&(f.current=Math.min(f.current+1,10),d(M instanceof Error?M.message:"Heartbeat failed"))}S()},[S,E]),T=_.useCallback(async()=>{l(!0),f.current=0,await k(),h.current&&l(!1)},[k]);return _.useEffect(()=>{if(h.current=!0,!e||!t){a([]),f.current=0;return}return l(!0),k().finally(()=>{h.current&&l(!1)}),()=>{h.current=!1,u.current&&(clearTimeout(u.current),u.current=null)}},[e,t,k]),{devices:r,isLoading:o,error:c,refresh:T}}function EFe(){const[t,e]=_.useState(null),[n,s]=_.useState(!0),[r,a]=_.useState(!1),[o,l]=_.useState(null),c=_.useRef(!0),d=_.useCallback(async()=>{try{const p=await dt.getCloudStatus();c.current&&(e(p),l(null))}catch{c.current&&e({connected:!1,tier:null,cloudUrl:null,status:"disconnected"})}},[]);_.useEffect(()=>(c.current=!0,(async()=>{await d(),c.current&&s(!1)})(),()=>{c.current=!1}),[d]);const u=_.useCallback(async(p,x)=>{a(!0),l(null);try{const v=await dt.connectToCloud(p,x);return c.current&&e({connected:v.connected,tier:v.tier,cloudUrl:v.cloudUrl,status:"connected"}),!0}catch(v){return c.current&&l(v instanceof Error?v.message:"Connection failed"),!1}finally{c.current&&a(!1)}},[]),h=_.useCallback(async()=>{a(!0),l(null);try{return await dt.disconnectFromCloud(),c.current&&e({connected:!1,tier:null,cloudUrl:null,status:"disconnected"}),!0}catch(p){return c.current&&l(p instanceof Error?p.message:"Disconnect failed"),!1}finally{c.current&&a(!1)}},[]),f=_.useCallback(async()=>{await d()},[d]);return{isConnected:(t==null?void 0:t.connected)??!1,tier:(t==null?void 0:t.tier)??null,isLoading:n,isActioning:r,error:o,connect:u,disconnect:h,refresh:f}}const CFe=6,Yz=t=>{var e;return((e=t.members)==null?void 0:e.some(n=>n.agentStatus==="active"))??!1},kFe=({createOpen:t,onCreateOpenChange:e,onCount:n})=>{var Ie,se;const s=cs(),{isPinned:r,togglePin:a}=q1(),[o,l]=_.useState([]),[c,d]=_.useState(""),[u,h]=_.useState({status:[],project:[]}),f=((Ie=u.status)==null?void 0:Ie[0])??"all",p=((se=u.project)==null?void 0:se[0])??"all",[x,v]=_.useState(!1),m=t??x,g=_.useCallback(W=>{e?e(W):v(W)},[e]),[y,b]=_.useState(null),[S,E]=_.useState(""),[k,T]=_.useState(!0),[A,N]=_.useState("list"),[M,L]=_.useState([]),{showError:j,AlertComponent:D}=Yh(),U=Object.fromEntries(M.map(W=>[W.id,W.name])),{isConnected:$,tier:G}=EFe(),{getAccessToken:K}=Tm(),P=$&&G==="pro"?K():null,B=_.useMemo(()=>o.map(W=>({id:W.id,name:W.name,memberCount:W.members.length})),[o]),I=$&&G==="pro",{devices:F,isLoading:q,refresh:H}=wFe(P,I,B,typeof window<"u"&&window.location.hostname||"My Device"),re=_.useMemo(()=>{let W=o;return c&&(W=W.filter(ae=>{var Q;return ae.name.toLowerCase().includes(c.toLowerCase())||ae.description&&ae.description.toLowerCase().includes(c.toLowerCase())||((Q=ae.projectIds)==null?void 0:Q.length)>0&&ae.projectIds.some(ce=>ce.toLowerCase().includes(c.toLowerCase()))||ae.members.some(ce=>ce.name.toLowerCase().includes(c.toLowerCase())||ce.role.toLowerCase().includes(c.toLowerCase()))})),f!=="all"&&(W=W.filter(ae=>f==="active"?ae.members.some(Q=>Q.agentStatus==="active"):f==="inactive"?!ae.members.some(Q=>Q.agentStatus==="active"):!0)),p!=="all"&&(W=W.filter(ae=>{var Q;return(Q=ae.projectIds)==null?void 0:Q.includes(p)})),W=W.filter(ae=>!ae.parentTeamId),W},[o,c,f,p]),ne=_.useMemo(()=>{const W=new Map;for(const ae of o)ae.parentTeamId&&W.set(ae.parentTeamId,(W.get(ae.parentTeamId)||0)+1);return W},[o]),Y=_.useCallback(W=>{l(ae=>ae.map(Q=>Q.id===W.teamId?{...Q,members:Q.members.map(ce=>ce.id===W.memberId||ce.sessionName===W.sessionName?{...ce,agentStatus:W.agentStatus}:ce)}:Q))},[]);_.useEffect(()=>{X(),z()},[]),_.useEffect(()=>(jt.on("team_member_status_changed",Y),()=>{jt.off("team_member_status_changed",Y)}),[Y]);const z=async()=>{try{const W=await dt.getProjects();L(W.map(ae=>({id:ae.id,name:ae.name})))}catch(W){Ta(W,{context:"Loading projects for filter"})}},X=async()=>{try{const ae=(await dt.getTeams()).map(Q=>({...Q,members:GR(Q.members)}));l(ae)}catch(W){Ta(W,{context:"fetchTeams"}),l([])}finally{T(!1)}},Z=async W=>{try{const ae=await dt.createTeam(W);l(Q=>[...Q,ae]),g(!1)}catch(ae){Ta(ae,{context:"handleCreateTeam"}),j("Error creating team: "+(ae instanceof Error?ae.message:"Unknown error"))}},le=async W=>{try{await dt.startTeam(W)}catch(ae){Ta(ae,{context:"handleStartTeam"}),j("Failed to start team: "+(ae instanceof Error?ae.message:"Unknown error"))}},ye=async W=>{try{await dt.stopTeam(W)}catch(ae){Ta(ae,{context:"handleStopTeam"}),j("Failed to stop team: "+(ae instanceof Error?ae.message:"Unknown error"))}},[te,ke]=_.useState(null),[ie,xe]=_.useState(!1),oe=async W=>{if(te){xe(!0);try{await dt.pauseTeam(te.id,W),ke(null),await X()}catch(ae){j("Failed to pause team: "+(ae instanceof Error?ae.message:"Unknown error"))}finally{xe(!1)}}},be=async W=>{try{await dt.resumeTeam(W),await X()}catch(ae){j("Failed to resume team: "+(ae instanceof Error?ae.message:"Unknown error"))}},J=async W=>{try{await dt.deleteTeam(W),l(ae=>ae.filter(Q=>Q.id!==W))}catch(ae){j("Failed to delete team: "+(ae instanceof Error?ae.message:"Unknown error"))}},Me=_.useMemo(()=>o.filter(W=>!W.parentTeamId),[o]);_.useEffect(()=>{k||n==null||n(Me.length)},[k,Me.length,n]);const Se=()=>{b(null),E("")};if(k)return i.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:i.jsx(zt,{size:"xl",text:"Loading teams..."})});const we=!!c||f!=="all"||p!=="all";return i.jsxs("div",{"data-testid":"teams-list-page",children:[i.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2","data-testid":"teams-toolbar",children:[i.jsx(Jo,{value:u,onChange:h,groups:[{id:"status",label:"Status",single:!0,options:[{value:"active",label:"Active",count:Me.filter(Yz).length},{value:"inactive",label:"Idle",count:Me.filter(W=>!Yz(W)).length}]},...M.length>0?[{id:"project",label:"Project",single:!0,options:M.map(W=>({value:W.id,label:W.name}))}]:[]]}),i.jsx(WR,{label:"Search teams",value:c,onChange:d}),i.jsxs("div",{className:"ml-auto flex items-center gap-1",role:"group","aria-label":"View",children:[i.jsx(Zt,{icon:uee,size:"xs","aria-label":"List view",title:"List view","aria-pressed":A==="list",className:A==="list"?"text-primary-text bg-primary-soft":"text-text-2",onClick:()=>N("list")}),i.jsx(Zt,{icon:x0,size:"xs","aria-label":"Tree view",title:"Tree view (parent and sub-teams)","aria-pressed":A==="tree",className:A==="tree"?"text-primary-text bg-primary-soft":"text-text-2",onClick:()=>N("tree")})]})]}),A==="tree"?o.length>0&&i.jsx(xFe,{teams:o,projectMap:U,onTeamClick:W=>s(qt.team(W))}):re.length>0?i.jsx("div",{className:"rounded-2xl border border-border-soft","data-testid":"teams-list",children:i.jsx(fs,{limit:CFe,"data-testid":"teams-show-all",children:re.map(W=>{var ae;return i.jsx(bFe,{team:W,projectName:((ae=W.projectIds)==null?void 0:ae.length)>0?U[W.projectIds[0]]:void 0,subTeamCount:ne.get(W.id),onOpen:Q=>s(qt.team(Q)),onEdit:Q=>s(`${qt.team(Q)}?edit=true`),onStart:le,onStop:ye,onOpenChat:Q=>s(`${Yt.chat}?${Hd}=${Q}`),onOpenWiki:Q=>s(`${Yt.wiki}?${Hd}=${Q}`),onDelete:J,isPinned:r(W.id),onTogglePin:()=>a({id:W.id,name:W.name,type:"team"}),onPause:()=>ke(W),onResume:be},W.id)})})}):i.jsx(is,{icon:vr,title:"No teams found",description:we?"Try adjusting your search or filters":"Create your first team to get started",action:we?void 0:i.jsx(ue,{variant:"primary",icon:qn,onClick:()=>g(!0),children:"Create Team"}),className:"py-16"}),I&&i.jsxs(ti,{title:`Online devices (${F.length})`,summary:"Other machines on your account and their teams",className:"mt-8","data-testid":"online-devices",children:[i.jsx("div",{className:"mb-3 flex justify-end",children:i.jsx(Zt,{icon:$t,size:"xs",onClick:H,title:"Refresh devices","aria-label":"Refresh devices"})}),q?i.jsx(zt,{size:"sm",text:"Discovering devices..."}):F.length===0?i.jsx(is,{compact:!0,icon:Q0,title:"No other devices online",description:"Other Pro users will appear here when they are online"}):i.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:F.map(W=>i.jsxs(tn,{padding:"md",children:[i.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[i.jsx(ER,{status:"online",size:"sm",pulse:!0}),i.jsx("span",{className:"truncate text-sm font-semibold text-text",children:W.deviceName})]}),i.jsx("p",{className:"mb-3 truncate text-xs text-text-2",children:W.email}),W.teams.length>0&&i.jsx("ul",{className:"space-y-1 text-[13px]",children:W.teams.map(ae=>i.jsxs("li",{className:"flex items-center justify-between gap-2",children:[i.jsx("span",{className:"truncate text-text",children:ae.name}),i.jsxs("span",{className:"shrink-0 text-text-2",children:[ae.memberCount," member",ae.memberCount!==1?"s":""]})]},ae.id))})]},W.deviceId))})]}),i.jsx(R$,{isOpen:m,onClose:()=>g(!1),onSubmit:Z}),y&&S&&i.jsx(hFe,{member:y,teamId:S,onClose:Se}),i.jsx(E$,{isOpen:!!te,teamName:(te==null?void 0:te.name)??"",issueRepo:te==null?void 0:te.issueRepo,busy:ie,onCancel:()=>ke(null),onConfirm:oe}),i.jsx(D,{})]})},AFe={teams:"Teams",goals:"Goals"},TFe={teams:"Your crews and the goals they work toward",goals:"Company → team → project goals and their key results"},NFe=()=>{const[t,e]=cu(kO),[n,s]=Lc(),[r,a]=_.useState(!1),[o,l]=_.useState(!1),[c,d]=_.useState(0),[u,h]=_.useState(null),[f,p]=_.useState(null);_.useEffect(()=>{if(n.get("create")!=="true")return;t==="goals"?l(!0):a(!0);const g=new URLSearchParams(n);g.delete("create"),s(g,{replace:!0})},[n,s,t]);const x=_.useCallback(g=>h(g),[]),v=_.useCallback(g=>p(g),[]),m=t==="teams"?i.jsx(ue,{variant:"primary",icon:qn,onClick:()=>a(!0),"data-testid":"teams-new",children:"New team"}):i.jsxs(i.Fragment,{children:[i.jsx(ue,{variant:"primary",icon:qn,onClick:()=>l(!0),"data-testid":"missions-new",children:"New goal"}),i.jsx(Eo,{icon:fa,label:"More goal actions",buttonClassName:"inline-flex h-10 w-10 items-center justify-center rounded-2xl border border-border-soft text-text-2 transition-colors hover:bg-surface-hover hover:text-text",items:[{label:"Refresh",onClick:()=>d(g=>g+1)}]})]});return i.jsxs("div",{className:"p-6 max-w-5xl mx-auto",children:[i.jsx(_r,{title:"Teams",subtitle:TFe[t],actions:m,tabs:i.jsx(Dc,{"aria-label":"Teams views",idPrefix:"teams",value:t,onChange:g=>e(g),tabs:kO.map(g=>({value:g,label:AFe[g],count:g==="teams"?u:f?f.pending>0?f.pending:f.total:null,attention:g==="goals"&&((f==null?void 0:f.pending)??0)>0}))})}),i.jsxs("div",{role:"tabpanel",id:`teams-panel-${t}`,"aria-labelledby":`teams-tab-${t}`,"data-testid":`teams-panel-${t}`,children:[t==="teams"&&i.jsx(kFe,{createOpen:r,onCreateOpenChange:a,onCount:x}),t==="goals"&&i.jsx(lX,{createOpen:o,onCreateOpenChange:l,refreshKey:c,onCounts:v})]})]})},Y2="connector",MFe=[{label:"Skills",value:"skill"},{label:"3D Models",value:"model"},{label:"Roles",value:"role"},{label:"MCP Tools",value:"mcp_tool"},{label:"Connectors",value:Y2}],jFe=[{label:"Popular",value:"popular"},{label:"Highest Rated",value:"rating"},{label:"Newest",value:"newest"}],NX=5;function Jz({view:t="browse",onPendingCount:e}={}){const{toasts:n,addToast:s,dismissToast:r}=fK();return i.jsxs(i.Fragment,{children:[t==="browse"?i.jsx(RFe,{addToast:s}):i.jsx(DFe,{addToast:s,onPendingCount:e}),i.jsx(pK,{toasts:n,onDismiss:r})]})}function RFe({addToast:t}){var A,N;const e=cs(),[n,s]=_.useState([]),[r,a]=_.useState(!0),[o,l]=_.useState(null),[c,d]=_.useState({}),[u,h]=_.useState(""),[f,p]=_.useState(null),x=((A=c.type)==null?void 0:A[0])??"all",v=((N=c.sort)==null?void 0:N[0])??"popular",m=_.useCallback(async()=>{try{a(!0),l(null);const M=await ANe({type:x==="all"||x===Y2?void 0:x,search:u||void 0,sort:v});s(M)}catch{l("Failed to load marketplace items")}finally{a(!1)}},[x,u,v]);_.useEffect(()=>{m()},[m]);const g=async(M,L,j,D)=>{p(M);try{const U=await L(M);t(U.message||`${j} ${M}`,U.success?"success":"error"),await m()}catch(U){t(U instanceof Error?U.message:D,"error")}p(null)},y=M=>g(M,cK,"Installed","Install failed"),b=M=>g(M,dK,"Uninstalled","Uninstall failed"),S=M=>g(M,NNe,"Updated","Update failed"),E=async()=>{try{await uK(),t("Registry refreshed","success"),await m()}catch{t("Failed to refresh registry","error")}},k=M=>e(`${Yt.marketplace}/${encodeURIComponent(M)}`),T=M=>AL.filter(L=>L.group===M).filter(L=>!u.trim()||`${L.name} ${L.description}`.toLowerCase().includes(u.trim().toLowerCase()));return i.jsxs("div",{className:"space-y-5","data-testid":"marketplace-browse",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx("label",{htmlFor:"marketplace-search",className:"sr-only",children:"Search marketplace"}),i.jsxs("div",{className:"relative min-w-0 flex-1 basis-56",children:[i.jsx(Al,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-3","aria-hidden":"true"}),i.jsx("input",{id:"marketplace-search",type:"text",placeholder:"Search...",value:u,onChange:M=>h(M.target.value),className:"h-9 w-full rounded-2xl border border-border bg-surface pl-9 pr-3 text-sm text-text placeholder:text-text-3 focus:border-primary focus:outline-none"})]}),i.jsx(Jo,{value:c,onChange:d,groups:[{id:"type",label:"Type",single:!0,options:MFe},{id:"sort",label:"Sort",single:!0,options:jFe}]}),i.jsx(Zt,{icon:$t,variant:"outline",onClick:()=>void E(),"aria-label":"Refresh marketplace",title:"Refresh marketplace"})]}),x===Y2?i.jsxs("div",{className:"space-y-6","data-testid":"marketplace-connectors",children:[i.jsxs("p",{className:"text-[13px] text-text-2",children:["Connectors are not installed — you authorise them against your own account, and can revoke them at any time. Manage them on"," ",i.jsx(hs,{to:Yt.connections,className:"font-semibold text-primary-text hover:underline",children:"Connections"}),"."]}),aK.map(M=>{const L=T(M.id);return L.length===0?null:i.jsxs("section",{"aria-label":M.title,className:"space-y-2",children:[i.jsx("h2",{className:"px-1 text-[15px] font-semibold text-text",children:M.title}),i.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-soft bg-surface",children:L.map(j=>i.jsx(Ts,{"data-testid":`marketplace-connector-${j.id}`,leading:i.jsx(sR,{className:"h-4 w-4 text-text-3","aria-hidden":"true"}),primary:j.name,meta:j.description,actions:[i.jsx(hs,{to:`${Yt.connections}?platform=${j.id}`,className:"inline-flex h-8 items-center rounded-2xl bg-primary-soft px-3 text-sm font-semibold text-primary-text transition-colors hover:bg-primary/20",children:"Connect →"},"connect")]},j.id))})]},M.id)})]}):r?i.jsx(zt,{size:"md",text:"Loading marketplace...",className:"py-16"}):o?i.jsx(Ye,{variant:"error",children:o}):n.length===0?i.jsx(is,{icon:nR,title:"No items found."}):i.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-soft bg-surface",children:i.jsx(fs,{limit:NX,children:n.map(M=>i.jsx(IFe,{item:M,busy:f===M.id,onOpen:()=>k(M.id),onInstall:()=>void y(M.id),onUninstall:()=>void b(M.id),onUpdate:()=>void S(M.id)},M.id))})})]})}function IFe({item:t,busy:e,onOpen:n,onInstall:s,onUninstall:r,onUpdate:a}){const o=[{label:"View details",icon:UH,onClick:n}];let l,c=null;return t.installStatus==="not_installed"?l=[i.jsx(ue,{variant:"primary",size:"sm",icon:nR,onClick:s,loading:e,children:e?"Installing...":"Install"},"install")]:t.installStatus==="installed"?(c=i.jsx(sn,{tone:"success",size:"sm",children:"Installed"}),l=[i.jsx(ue,{variant:"outline",size:"sm",onClick:r,loading:e,children:e?"Removing...":"Uninstall"},"uninstall")]):t.installStatus==="update_available"&&(c=i.jsx(sn,{tone:"attention",size:"sm",children:"Update available"}),l=[i.jsx(ue,{variant:"primary",size:"sm",icon:D1,onClick:a,loading:e,children:e?"Updating...":"Update"},"update"),i.jsx(ue,{variant:"outline",size:"sm",onClick:r,disabled:e,children:"Remove"},"remove")]),i.jsx(Ts,{"data-testid":`marketplace-item-${t.id}`,primary:t.name,meta:i.jsxs(i.Fragment,{children:[i.jsx("span",{children:mK[t.type]??t.type}),i.jsx("span",{"aria-hidden":"true",children:" · "}),i.jsxs("span",{children:["by ",t.author]}),t.description&&i.jsxs(i.Fragment,{children:[i.jsx("span",{"aria-hidden":"true",children:" · "}),i.jsx("span",{title:t.description,children:t.description})]})]}),onClick:n,trailing:c,actions:l,overflow:o,overflowLabel:`More actions for ${t.name}`})}const LFe={pending:"attention",approved:"success",rejected:"danger"},PFe={pending:"Pending review",approved:"Approved",rejected:"Rejected"};function DFe({addToast:t,onPendingCount:e}){const[n,s]=_.useState([]),[r,a]=_.useState(!0),[o,l]=_.useState(null),[c,d]=_.useState(null),[u,h]=_.useState(null),f=_.useCallback(async()=>{try{a(!0),l(null);const x=await hK();s(x),e==null||e(x.filter(v=>v.status==="pending").length)}catch{l("Failed to load submissions")}finally{a(!1)}},[e]);_.useEffect(()=>{f()},[f]);const p=async(x,v)=>{d(x);try{const m=await MNe(x,v);t(m.message||`${v==="approve"?"Approved":"Rejected"}`,m.success?"success":"error"),await f(),v==="approve"&&await uK()}catch(m){t(m instanceof Error?m.message:"Review failed","error")}d(null)};return i.jsxs("div",{className:"space-y-5","data-testid":"marketplace-submissions",children:[i.jsxs("p",{className:"text-[13px] text-text-2",children:["Submit skills via CLI:"," ",i.jsx("code",{className:"rounded bg-surface-2 px-2 py-0.5 font-mono text-xs text-text",children:"crewly publish path/to/skill --submit"})]}),r?i.jsx(zt,{size:"md",text:"Loading submissions...",className:"py-16"}):o?i.jsx(Ye,{variant:"error",children:o}):n.length===0?i.jsx(is,{icon:JH,title:"No submissions yet."}):i.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-soft bg-surface",children:i.jsx(fs,{limit:NX,children:n.map(x=>{const v=c===x.id,m=u===x.id;return i.jsxs("div",{className:"border-b border-border-soft last:border-b-0","data-testid":`submission-${x.id}`,children:[i.jsx(Ts,{className:"border-b-0",primary:x.name,meta:`by ${x.author} · ${x.category} · ${ow(x.submittedAt)||new Date(x.submittedAt).toLocaleDateString()}`,onClick:()=>h(m?null:x.id),selected:m,trailing:i.jsx(sn,{tone:LFe[x.status]??"danger",size:"sm",children:PFe[x.status]??x.status}),actions:x.status==="pending"?[i.jsx(ue,{variant:"success",size:"sm",onClick:()=>void p(x.id,"approve"),loading:v,children:v?"...":"Approve"},"approve"),i.jsx(ue,{variant:"outline",size:"sm",onClick:()=>void p(x.id,"reject"),disabled:v,children:"Reject"},"reject")]:void 0}),m&&i.jsxs("div",{className:"space-y-2 px-4 pb-4 text-sm","data-testid":`submission-detail-${x.id}`,children:[i.jsx("p",{className:"text-text-2",children:x.description}),i.jsxs("p",{className:"text-[13px] text-text-3",children:["Version ",x.version," · submitted ",new Date(x.submittedAt).toLocaleString()]}),x.reviewNotes&&i.jsxs("p",{className:"text-[13px] italic text-text-2",children:["Review: ",x.reviewNotes]})]})]},x.id)})})})]})}const MX=[{value:"",label:"All Categories"},...Ide.map(t=>({value:t,label:T$(t)}))],OFe=5,BFe=({skill:t,onSave:e,onClose:n})=>{const s=(t==null?void 0:t.isBuiltin)??!1,[r,a]=_.useState({name:(t==null?void 0:t.name)||"",displayName:(t==null?void 0:t.name)||"",description:(t==null?void 0:t.description)||"",category:(t==null?void 0:t.category)||"development",promptContent:(t==null?void 0:t.promptContent)||"",triggers:[],tags:[]}),[o,l]=_.useState(!1),[c,d]=_.useState(null),u=async f=>{if(f.preventDefault(),d(null),!r.displayName.trim()){d("Display Name is required");return}if(!r.name.trim()){d("ID is required");return}if(!r.description.trim()){d("Description is required");return}l(!0);try{await e(r)}catch(p){d(p instanceof Error?p.message:"Failed to save skill")}finally{l(!1)}},h=i.jsxs(i.Fragment,{children:[i.jsx(ue,{variant:"secondary",onClick:n,type:"button",children:"Cancel"}),i.jsx(ue,{type:"submit",onClick:u,disabled:o,loading:o,children:o?"Saving...":"Save Skill"})]});return i.jsx(qi,{isOpen:!0,onClose:n,title:t?"Edit Skill":"Create Skill",subtitle:t?"Modify skill configuration":"Configure a new skill for your agents",size:"lg",footer:h,children:i.jsxs("div",{className:"-m-6 max-h-[65vh] overflow-y-auto",children:[s&&t&&i.jsxs(Ye,{variant:"info",className:"mx-6 mt-4",children:[i.jsx("strong",{children:"Built-in Skill:"})," Changes will be saved as a user override. You can reset to defaults anytime."]}),c&&i.jsx("div",{className:"mx-6 mt-4",children:i.jsx(Ye,{variant:"error",children:c})}),i.jsxs("form",{onSubmit:u,className:"p-6 space-y-4",children:[i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-display-name",required:!0,children:"Display Name"}),i.jsx(Dt,{id:"skill-display-name",type:"text",value:r.displayName,onChange:f=>a({...r,displayName:f.target.value}),placeholder:"Code Review",required:!0})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-name",required:!0,children:"ID"}),i.jsx(Dt,{id:"skill-name",type:"text",value:r.name,onChange:f=>a({...r,name:f.target.value}),placeholder:"code-review",required:!0,disabled:!!t}),i.jsx("p",{className:"text-xs text-text-2 mt-1",children:"Lowercase letters, numbers, and hyphens only"})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-description",required:!0,children:"Description"}),i.jsx(er,{id:"skill-description",value:r.description,onChange:f=>a({...r,description:f.target.value}),placeholder:"Describe what this skill does...",rows:3,required:!0})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-category",children:"Category"}),i.jsx(vn,{id:"skill-category",value:r.category,onChange:f=>a({...r,category:f.target.value}),children:MX.filter(f=>f.value).map(f=>i.jsx("option",{value:f.value,children:f.label},f.value))})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"skill-prompt",children:"Instructions (Markdown)"}),i.jsx(er,{id:"skill-prompt",value:r.promptContent,onChange:f=>a({...r,promptContent:f.target.value}),placeholder:`# Skill Instructions
4953
4953
 
4954
4954
  Provide detailed instructions for this skill...`,rows:8,className:"font-mono text-sm"})]})]})]})})},FFe=({skillName:t,onConfirm:e,onCancel:n})=>i.jsx(Nte,{isOpen:!0,onClose:n,onConfirm:e,title:"Delete Skill",confirmText:"Delete",confirmVariant:"danger",message:i.jsxs("p",{className:"text-text-2",children:["Are you sure you want to delete ",i.jsx("strong",{className:"text-text",children:t}),"? This action cannot be undone."]})});function UFe(t){var n,s;if(!t.enableBrowserAutomation)return"Off";const e=["On"];return(n=t.browserProfile)!=null&&n.headless&&e.push("headless"),(s=t.browserProfile)!=null&&s.stealth&&e.push("stealth"),e.join(" · ")}const zFe=()=>{const{settings:t,updateSettings:e}=bL(),[n,s]=_.useState(null),[r,a]=_.useState(!1),[o,l]=_.useState("idle");if(_.useEffect(()=>{t&&(s(t.skills),a(!1))},[t]),!n)return null;const c=(h,f)=>{s({...n,[h]:f}),a(!0),l("idle")},d=(h,f)=>{s({...n,browserProfile:{...n.browserProfile,[h]:f}}),a(!0),l("idle")},u=async()=>{l("saving");try{await e({skills:n}),l("saved"),a(!1),setTimeout(()=>l("idle"),2e3)}catch{l("error")}};return i.jsx(ti,{title:i.jsxs("span",{className:"inline-flex items-center gap-2",children:[i.jsx(Q0,{className:"h-4 w-4 text-text-3","aria-hidden":"true"}),"Browser Automation"]}),summary:UFe(n),"data-testid":"browser-automation-settings",children:i.jsxs("div",{className:"space-y-5 pt-2",children:[i.jsx(Gi,{id:"enableBrowserAutomation",label:"Enable Browser Automation",description:"Allow agents to use Playwright for browser tasks (navigate, click, screenshot, etc.)",checked:n.enableBrowserAutomation,onChange:h=>c("enableBrowserAutomation",h.target.checked)}),n.enableBrowserAutomation&&n.browserProfile&&i.jsxs("div",{className:"space-y-4 border-l-2 border-border-soft pl-4",children:[i.jsx(Gi,{id:"headless",label:"Headless Mode",description:"Run browser invisibly in the background (recommended)",checked:n.browserProfile.headless,onChange:h=>d("headless",h.target.checked)}),i.jsx(Gi,{id:"stealth",label:"Stealth Mode",description:"Use anti-detection features to avoid bot blocking (uses community fork)",checked:n.browserProfile.stealth,onChange:h=>d("stealth",h.target.checked)}),i.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"humanDelayMin",children:"Min Delay (ms)"}),i.jsx(Dt,{id:"humanDelayMin",type:"number",min:0,max:n.browserProfile.humanDelayMaxMs,value:n.browserProfile.humanDelayMinMs,onChange:h=>d("humanDelayMinMs",parseInt(h.target.value,10)||0)}),i.jsx("p",{className:"mt-1 text-xs text-text-2",children:"Minimum delay between actions"})]}),i.jsxs("div",{children:[i.jsx(_t,{htmlFor:"humanDelayMax",children:"Max Delay (ms)"}),i.jsx(Dt,{id:"humanDelayMax",type:"number",min:n.browserProfile.humanDelayMinMs,max:1e4,value:n.browserProfile.humanDelayMaxMs,onChange:h=>d("humanDelayMaxMs",parseInt(h.target.value,10)||0)}),i.jsx("p",{className:"mt-1 text-xs text-text-2",children:"Maximum delay between actions"})]})]})]}),i.jsxs("div",{className:"flex items-center justify-end gap-3",children:[o==="saved"&&i.jsxs("span",{className:"flex items-center gap-1 text-sm text-success",children:[i.jsx(rs,{className:"h-4 w-4","aria-hidden":"true"})," Saved"]}),o==="error"&&i.jsxs("span",{className:"flex items-center gap-1 text-sm text-danger",children:[i.jsx($i,{className:"h-4 w-4","aria-hidden":"true"})," Save failed"]}),i.jsx(ue,{onClick:u,disabled:!r||o==="saving",icon:Kd,size:"sm",children:o==="saving"?"Saving...":"Save"})]})]})})},Zz={info:{icon:Rh,text:"text-primary-text"},warning:{icon:Vd,text:"text-attention"},requirement:{icon:$i,text:"text-danger"}};function HFe(t){const e=T$(t.category),n=[e.charAt(0).toUpperCase()+e.slice(1),t.isBuiltin?"Built-in":"Custom"];return t.skillType==="web-page"&&n.push(Lde("web-page")),n.join(" · ")}const GFe=({onCountChange:t})=>{var I,F;const[e,n]=_.useState({}),[s,r]=_.useState(""),[a,o]=_.useState(null),[l,c]=_.useState(!1),[d,u]=_.useState(null),[h,f]=_.useState(null),[p,x]=_.useState(null),[v,m]=_.useState(null),g=((I=e.category)==null?void 0:I[0])??"",y=_.useMemo(()=>({category:g||void 0,search:s||void 0}),[g,s]),{skills:b,loading:S,error:E,refresh:k,create:T,update:A,remove:N,selectSkill:M,selectedSkill:L,clearSelection:j}=oE(y),D=!!(s||g);_.useEffect(()=>{!D&&!S&&(t==null||t(b.length))},[D,S,b.length,t]);const U=b.filter(q=>!q.isEnabled).length,$=_.useCallback(()=>{u(null),c(!0)},[]),G=_.useCallback(async q=>{u(q),await M(q.id),c(!0)},[M]),K=_.useCallback(async q=>{try{d!=null&&d.id?await A(d.id,q):await T(q),c(!1),u(null)}catch(H){console.error("Failed to save skill:",H)}},[d,A,T]),P=_.useCallback(async q=>{try{await N(q),f(null)}catch(H){console.error("Failed to delete skill:",H)}},[N]),B=_.useCallback(async(q,H)=>{x(q.id),m(null);try{await A(q.id,{isEnabled:H})}catch(re){m(re instanceof Error?re.message:`Could not ${H?"enable":"disable"} ${q.name}`)}finally{x(null)}},[A]);return i.jsxs("div",{className:"space-y-6","data-testid":"installed-skills",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx("label",{htmlFor:"search-filter",className:"sr-only",children:"Search skills"}),i.jsxs("div",{className:"relative min-w-0 flex-1 basis-56",children:[i.jsx(Al,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-3","aria-hidden":"true"}),i.jsx("input",{id:"search-filter",type:"text",placeholder:"Search skills...",value:s,onChange:q=>r(q.target.value),className:"h-9 w-full rounded-2xl border border-border bg-surface pl-9 pr-3 text-sm text-text placeholder:text-text-3 focus:border-primary focus:outline-none"})]}),i.jsx(Jo,{value:e,onChange:n,groups:[{id:"category",label:"Category",single:!0,options:MX.filter(q=>q.value).map(q=>({value:q.value,label:q.label}))}]}),i.jsx(Zt,{icon:$t,variant:"outline",onClick:()=>void k(),loading:S,disabled:S,"aria-label":"Refresh skills",title:"Refresh skills"}),i.jsx(ue,{onClick:$,icon:qn,size:"sm",children:"New Skill"})]}),!S&&b.length>0&&i.jsxs("p",{className:"-mt-3 px-1 text-[13px] text-text-2","data-testid":"installed-summary",children:[b.length," ",D?"shown":"installed",U>0?` · ${U} disabled`:" · all enabled"]}),E&&i.jsx(Ye,{variant:"error",children:i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsxs("span",{children:["Error: ",E]}),i.jsx(ue,{variant:"outline",size:"sm",onClick:()=>void k(),children:"Retry"})]})}),v&&i.jsx(Ye,{variant:"error",children:v}),S&&b.length===0&&i.jsx("div",{className:"flex justify-center py-16",children:i.jsx(zt,{text:"Loading skills..."})}),!S&&b.length===0&&!E&&i.jsxs("div",{className:"py-12 text-center",children:[i.jsx(ny,{className:"mx-auto mb-3 h-10 w-10 text-text-3","aria-hidden":"true"}),i.jsx("h3",{className:"mb-1 text-[15px] font-semibold text-text",children:"No Skills Found"}),i.jsx("p",{className:"mb-5 text-sm text-text-2",children:D?"Try adjusting your filters":"Create your first skill to get started"}),!D&&i.jsx(ue,{onClick:$,icon:qn,size:"sm",children:"Create Skill"})]}),b.length>0&&i.jsx("div",{className:"overflow-hidden rounded-2xl border border-border-soft bg-surface",children:i.jsx(fs,{limit:OFe,children:b.map(q=>i.jsx($Fe,{skill:q,open:a===q.id,busy:p===q.id,onOpen:()=>o(H=>H===q.id?null:q.id),onEdit:()=>void G(q),onDelete:()=>f(q.id),onToggle:H=>void B(q,H)},q.id))})}),i.jsx(zFe,{}),l&&i.jsx(BFe,{skill:L||d,onSave:K,onClose:()=>{c(!1),u(null),j()}}),h&&i.jsx(FFe,{skillId:h,skillName:((F=b.find(q=>q.id===h))==null?void 0:F.name)||"",onConfirm:()=>void P(h),onCancel:()=>f(null)})]})},$Fe=({skill:t,open:e,busy:n,onOpen:s,onEdit:r,onDelete:a,onToggle:o})=>{var u,h;const l=(u=t.notices)==null?void 0:u.some(f=>f.type==="requirement"),c=t.isEnabled?l?i.jsx(sn,{tone:"attention",size:"sm",children:"Needs setup"}):null:i.jsx(sn,{tone:"neutral",size:"sm",children:"Disabled"}),d=t.isBuiltin?i.jsx("span",{className:"hidden text-xs text-text-3 sm:inline",title:"Built-in skills are always available",children:"Built-in"}):i.jsx(Gi,{size:"sm",checked:t.isEnabled,disabled:n,onChange:f=>o(f.target.checked),"aria-label":`Enable ${t.name}`});return i.jsxs("div",{className:"border-b border-border-soft last:border-b-0","data-testid":`installed-skill-${t.id}`,children:[i.jsx(Ts,{className:"border-b-0",primary:t.name,meta:HFe(t),onClick:s,selected:e,trailing:c,actions:[d,i.jsx(Zt,{icon:Ih,onClick:r,variant:"ghost",size:"sm","aria-label":`Edit ${t.name}`,title:"Edit"},"edit")],overflow:[{label:"Edit",icon:Ih,onClick:r},...t.isBuiltin?[]:[{label:"Delete",icon:Qs,danger:!0,separator:!0,onClick:a}]],overflowLabel:`More actions for ${t.name}`}),e&&i.jsxs("div",{className:"space-y-3 px-4 pb-4 pl-4 sm:pl-6","data-testid":`installed-skill-detail-${t.id}`,children:[i.jsx("p",{className:"text-sm text-text-2",children:t.description}),(h=t.notices)==null?void 0:h.map((f,p)=>{const x=Zz[f.type]??Zz.info,v=x.icon;return i.jsxs("div",{className:"flex gap-2 text-[13px]",children:[i.jsx(v,{className:`mt-0.5 h-4 w-4 shrink-0 ${x.text}`,"aria-hidden":"true"}),i.jsxs("div",{children:[i.jsx("span",{className:"block font-semibold text-text",children:f.title}),i.jsx("span",{className:"block text-text-2",children:f.message}),f.link&&i.jsxs("a",{href:f.link,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-primary-text hover:underline",children:[f.linkText||"Learn more",i.jsx(zs,{className:"h-3 w-3","aria-hidden":"true"})]})]})]},p)}),!t.isBuiltin&&i.jsx(ue,{variant:"ghost",size:"xs",icon:Qs,className:"text-danger",onClick:a,children:"Delete skill"})]})]})},WFe={browse:"Browse",installed:"Installed",submissions:"Submissions"},VFe=()=>{const[t,e]=cu(AO),[n,s]=_.useState(void 0),[r,a]=_.useState(void 0);_.useEffect(()=>{let l=!1;return hK("pending").then(c=>{l||a(c.filter(d=>d.status==="pending").length)}).catch(()=>{}),()=>{l=!0}},[]);const o=l=>l==="installed"&&n!==void 0?{count:n}:l==="submissions"&&r?{count:r,attention:!0}:{};return i.jsxs("div",{className:"max-w-5xl",children:[i.jsx(_r,{title:"Marketplace",subtitle:"Browse and install skills, roles, tools and models, and manage the ones you have",tabs:i.jsx(Dc,{"aria-label":"Marketplace views",idPrefix:"marketplace",value:t,onChange:l=>e(l),tabs:AO.map(l=>({value:l,label:WFe[l],...o(l)}))})}),i.jsxs("div",{role:"tabpanel",id:`marketplace-panel-${t}`,"aria-labelledby":`marketplace-tab-${t}`,"data-testid":`marketplace-panel-${t}`,children:[t==="browse"&&i.jsx(Jz,{view:"browse"}),t==="installed"&&i.jsx(GFe,{onCountChange:s}),t==="submissions"&&i.jsx(Jz,{view:"submissions",onPendingCount:a})]})]})},KFe=({rule:t})=>{const e=Ic(),{search:n,hash:s}=bi();return i.jsx(CH,{to:ere(t.to(e),n,s),replace:!0})},qFe=()=>{},XFe=({onSaved:t})=>{const[e,n]=_.useState(!1),[s,r]=_.useState(""),[a,o]=_.useState(!1);_.useEffect(()=>{const c=()=>{o(!!dy()),n(!0)};return window.addEventListener(MM,c),()=>window.removeEventListener(MM,c)},[]);const l=_.useCallback(c=>{c.preventDefault();const d=s.trim();d&&(k9(d),n(!1),t?t():window.location.reload())},[s,t]);return e?i.jsx("div",{className:"relative z-[100]",children:i.jsx(Lr,{isOpen:!0,onClose:qFe,closable:!1,title:"Access token required",size:"md","data-testid":"api-token-prompt",children:i.jsxs("form",{onSubmit:l,className:"space-y-4",children:[i.jsxs("p",{className:"text-sm text-text-secondary-dark leading-relaxed",children:[a?"The stored access token was rejected. Paste the current token to continue.":"This dashboard is being opened from another machine. Paste the access token to continue."," ","Run ",i.jsx("code",{className:"font-mono",children:"crewly token"})," on the server to print it (or ",i.jsx("code",{className:"font-mono",children:"crewly token --url"})," for a ready-to-open link)."]}),i.jsx(ss,{id:"api-token-input",label:"Access token",type:"password",value:s,onChange:c=>r(c.target.value),placeholder:"paste token",autoComplete:"off",autoFocus:!0,fullWidth:!0,className:"font-mono","data-testid":"api-token-input"}),i.jsx("div",{className:"flex justify-end",children:i.jsx(ue,{type:"submit",icon:Z0,disabled:!s.trim(),"data-testid":"api-token-submit",children:"Save and reload"})})]})})}):null};function YFe(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 Qz(t){return!pae.some(e=>t===e||t.startsWith(`${e}/`))}function e6(){try{return window.localStorage.getItem(LM)==="1"}catch{return!1}}function JFe(t){try{t?window.localStorage.setItem(LM,"1"):window.localStorage.removeItem(LM)}catch{}}const ZFe=()=>{const t=bi(),e=cs(),n=_.useRef(t.pathname);return n.current=t.pathname,_.useEffect(()=>{if(e6()||!Qz(n.current))return;let s=!1;return fo.getStatus().then(r=>{s||e6()||!Qz(n.current)||YFe(r)&&e(LR,{replace:!0})}).catch(()=>{}),()=>{s=!0}},[]),null},QFe=({steps:t,currentStep:e})=>i.jsx("div",{className:"flex items-center justify-center gap-0","data-testid":"step-indicator",children:t.map((n,s)=>{const r=s<e,a=s===e,o=s===t.length-1;return i.jsxs(an.Fragment,{children:[i.jsxs("div",{className:"flex flex-col items-center","data-testid":`step-${s}`,children:[i.jsx("div",{className:Nr("flex items-center justify-center w-8 h-8 rounded-full text-xs font-bold transition-colors duration-200",r&&"bg-primary text-white",a&&"bg-primary/20 text-primary border-2 border-primary",!r&&!a&&"bg-surface-dark text-text-secondary-dark border border-border-dark"),"aria-current":a?"step":void 0,children:r?i.jsx(rs,{className:"w-4 h-4"}):s+1}),i.jsx("span",{className:Nr("mt-1.5 text-[10px] font-medium uppercase tracking-wide",a?"text-primary":"text-text-secondary-dark"),children:n})]}),!o&&i.jsx("div",{className:Nr("h-0.5 w-12 mx-1 mt-[-12px] transition-colors duration-200",r?"bg-primary":"bg-border-dark")})]},n)})});function t6(t){return t.status!=="running"}function e4e(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 t4e(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 n4e=({questions:t,submitLabel:e,submitting:n=!1,error:s=null,serverProblems:r=[],onSubmit:a})=>{const[o,l]=_.useState(()=>e4e(t)),[c,d]=_.useState([]),u=new Set([...c,...r]),h=(x,v)=>{l(m=>({...m,[x]:v})),d(m=>m.filter(g=>g!==x))},f=(x,v)=>{const m=o[x],g=Array.isArray(m)?m:[];h(x,g.includes(v)?g.filter(y=>y!==v):[...g,v])},p=x=>{x.preventDefault();const v=t4e(t,o);d(v),v.length===0&&a(o)};return i.jsxs("form",{className:"space-y-4",onSubmit:p,noValidate:!0,"data-testid":"bundle-questions",children:[t.map(x=>{const v=`bundle-q-${x.id}`,m=o[x.id],g=u.has(x.id);return i.jsxs(hi,{children:[i.jsx(_t,{id:`${v}-label`,htmlFor:x.type==="multiselect"?void 0:v,required:x.required,children:x.label}),x.type==="text"&&i.jsx(Dt,{id:v,value:typeof m=="string"?m:"",placeholder:x.placeholder,error:g,onChange:y=>h(x.id,y.target.value)}),x.type==="textarea"&&i.jsx(er,{id:v,rows:3,value:typeof m=="string"?m:"",placeholder:x.placeholder,error:g,onChange:y=>h(x.id,y.target.value)}),x.type==="select"&&i.jsxs(vn,{id:v,value:typeof m=="string"?m:"",error:g,onChange:y=>h(x.id,y.target.value),children:[!x.required&&x.default===""&&i.jsx("option",{value:"",children:"—"}),x.required&&i.jsx("option",{value:"",children:"Select…"}),(x.options??[]).map(y=>i.jsx("option",{value:y.value,children:y.label??y.value},y.value))]}),x.type==="multiselect"&&i.jsx("div",{role:"group","aria-labelledby":`${v}-label`,className:"flex flex-wrap gap-2",id:v,children:(x.options??[]).map(y=>{const b=Array.isArray(m)&&m.includes(y.value);return i.jsx(ue,{type:"button",size:"sm",variant:b?"primary":"secondary","aria-pressed":b,"data-testid":`bundle-option-${x.id}-${y.value}`,onClick:()=>f(x.id,y.value),children:y.label??y.value},y.value)})}),x.help&&i.jsx(kc,{children:x.help}),g&&i.jsx("p",{className:"mt-1 text-xs text-red-400",role:"alert","data-testid":`bundle-missing-${x.id}`,children:x.type==="multiselect"?"Pick at least one":"This field is required"})]},x.id)}),s&&i.jsx(Ye,{variant:"error",size:"sm",children:s}),i.jsx(ue,{type:"submit",fullWidth:!0,loading:n,"data-testid":"bundle-deploy",children:e})]})},aN={LIST:"/api/bundles",detail:t=>`/api/bundles/${encodeURIComponent(t)}`,APPLY:"/api/bundles/apply",job:t=>`/api/bundles/apply/${encodeURIComponent(t)}`},s4e=1500,r4e={queued:"Waiting",running:"In progress",done:"Done",failed:"Failed",pending:"Finishes automatically later",skipped:"Skipped"},i4e={"crewly-agent":"Crewly Agent (DeepSeek)","claude-code":"Claude Code","codex-cli":"Codex","gemini-cli":"Gemini CLI","opencode-cli":"OpenCode","antigravity-cli":"Antigravity CLI"},a4e={entry:"Entry (2 vCPU, 4 GB)",standard:"Standard (4 vCPU, 8 GB)",advanced:"Advanced (8 vCPU, 16 GB)"};class fS extends Error{constructor(e,n=null,s=[],r=[]){super(e),this.code=n,this.missing=s,this.invalid=r,this.name="BundleRequestError"}}async function oN(t,e){var s;let n;try{n=(await t()).data}catch(r){if(Pc(r)){const a=((s=r.response)==null?void 0:s.data)??{};throw new fS(a.error||r.message||e,a.code??null,a.missing??[],a.invalid??[])}throw r instanceof Error?r:new fS(e)}if(!(n!=null&&n.success)||n.data===void 0||n.data===null)throw new fS((n==null?void 0:n.error)||e);return n.data}class o4e{async getBundle(e){return oN(()=>Ue.get(aN.detail(e)),"Couldn't load this bundle")}async apply(e,n,s){return(await oN(()=>Ue.post(aN.APPLY,{templateId:e,answers:n,...s?{runtime:s}:{}}),"Deploy failed")).deployment}async getJob(e){return oN(()=>Ue.get(aN.job(e)),"Couldn't load deploy progress")}}const N_=new o4e,l4e=({status:t})=>t==="done"?i.jsx(vo,{className:"h-4 w-4 shrink-0 text-emerald-400","aria-hidden":!0}):t==="failed"?i.jsx(qd,{className:"h-4 w-4 shrink-0 text-red-400","aria-hidden":!0}):t==="running"?i.jsx(VS,{className:"h-4 w-4 shrink-0 animate-spin text-primary","aria-hidden":!0}):t==="pending"?i.jsx(jr,{className:"h-4 w-4 shrink-0 text-amber-400","aria-hidden":!0}):i.jsx(Zj,{className:"h-4 w-4 shrink-0 text-text-secondary-dark","aria-hidden":!0}),c4e=({templateId:t,onBack:e,onDone:n,pollIntervalMs:s=s4e})=>{const[r,a]=_.useState(null),[o,l]=_.useState(null),[c,d]=_.useState(null),[u,h]=_.useState(!1),[f,p]=_.useState(null),[x,v]=_.useState([]),m=_.useRef(null),g=_.useCallback(async()=>{l(null);try{const E=await N_.getBundle(t);a(E.bundle),E.deployment&&d(E.deployment)}catch(E){l(E instanceof Error?E.message:String(E))}},[t]);_.useEffect(()=>{g()},[g]),_.useEffect(()=>{if(!(!c||t6(c)))return m.current=setTimeout(()=>{N_.getJob(c.jobId).then(d).catch(E=>p(E instanceof Error?E.message:String(E)))},s),()=>{m.current&&clearTimeout(m.current)}},[c,s]);const y=async E=>{h(!0),p(null),v([]);try{d(await N_.apply(t,E))}catch(k){k instanceof fS&&v([...k.missing,...k.invalid].map(T=>T.id)),p(k instanceof Error?k.message:String(k))}finally{h(!1)}},b=async()=>{h(!0),p(null);try{d(await N_.apply(t,{}))}catch(E){p(E instanceof Error?E.message:String(E))}finally{h(!1)}},S=()=>{const E=(c==null?void 0:c.teams[0])??null;n({starterId:t,teamId:(E==null?void 0:E.teamId)??null,teamName:(E==null?void 0:E.name)??null,suggestions:[],bundle:!0})};if(o)return i.jsx(Ye,{variant:"error",title:"Couldn't load this bundle",children:i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{children:o}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ue,{type:"button",size:"sm",variant:"secondary",icon:$t,onClick:()=>void g(),children:"Retry"}),i.jsx(ue,{type:"button",size:"sm",variant:"ghost",icon:Ba,onClick:e,children:"Choose another"})]})]})});if(!r)return i.jsx(zt,{centered:!0,text:"Loading bundle…"});if(c){const E=t6(c),k=c.steps.some(A=>A.status==="failed"),T=c.connectors.filter(A=>A.status!=="connected");return i.jsxs("div",{className:"space-y-4","data-testid":"bundle-progress",children:[i.jsx("p",{className:"text-sm text-text-secondary-dark",children:E?`"${r.label}" is deployed.`:`Deploying "${r.label}"…`}),i.jsx("ul",{className:"space-y-2",children:c.steps.map(A=>i.jsxs("li",{className:"flex items-start gap-2 text-sm","data-testid":`bundle-step-${A.id}`,children:[i.jsx(l4e,{status:A.status}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("span",{className:"text-text-primary-dark",children:A.label})," ",i.jsxs("span",{className:"text-xs text-text-secondary-dark",children:["· ",r4e[A.status]]}),(A.error??A.message)&&i.jsx("p",{className:"text-xs text-text-secondary-dark",children:A.error??A.message})]})]},A.id))}),T.length>0&&i.jsx(Ye,{variant:"info",size:"sm",title:"Connect these services too (you can do it from your phone)",children:i.jsx("ul",{className:"space-y-1","data-testid":"bundle-connect-list",children:T.map(A=>i.jsxs("li",{children:[i.jsxs("a",{className:"text-primary underline",href:A.connectPath,children:[A.id,A.products.length>0?` (${A.products.join(", ")})`:""]}),A.required?"":" (optional)",": ",A.why]},A.id))})}),f&&i.jsx(Ye,{variant:"error",size:"sm",children:f}),E&&i.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[k&&i.jsx(ue,{type:"button",variant:"secondary",icon:$t,loading:u,onClick:()=>void b(),"data-testid":"bundle-retry",children:"Retry failed steps"}),i.jsx(ue,{type:"button",fullWidth:!0,onClick:S,"data-testid":"bundle-finish",children:"Next"})]})]})}return i.jsxs("div",{className:"space-y-4","data-testid":"bundle-deploy-step",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx("h3",{className:"font-semibold text-text-primary-dark",children:r.label}),i.jsx(mn,{variant:"primary",children:i4e[r.recommendedRuntime]??r.recommendedRuntime}),i.jsx(mn,{children:a4e[r.serverTier]??r.serverTier})]}),i.jsx("p",{className:"mt-2 whitespace-pre-line text-sm text-text-secondary-dark",children:r.ownerSummary}),r.ownerDoes.length>0&&i.jsxs("div",{className:"mt-2 text-sm text-text-secondary-dark",children:[i.jsx("p",{className:"font-medium text-text-primary-dark",children:"What you need to do:"}),i.jsx("ul",{className:"list-disc pl-5",children:r.ownerDoes.map(E=>i.jsx("li",{children:E},E))})]}),i.jsxs("p",{className:"mt-2 text-xs text-text-secondary-dark",children:["Members: ",r.teams.flatMap(E=>E.members.map(k=>`${k.name} (${k.title})`)).join(", ")]})]}),i.jsx(n4e,{questions:r.questions,submitLabel:`Deploy "${r.label}"`,submitting:u,error:f,serverProblems:x,onSubmit:E=>void y(E)}),i.jsx(ue,{type:"button",variant:"ghost",icon:Ba,onClick:e,children:"Choose another"})]})},d4e=({onDone:t})=>{const[e,n]=_.useState(null),[s,r]=_.useState(null),[a,o]=_.useState(null),[l,c]=_.useState(null),[d,u]=_.useState(!1),[h,f]=_.useState(null),p=async()=>{o(null);try{const m=await Ac.getStarters();n(m),r(g=>{var y;return g??((y=m.find(b=>b.recommended)??m[0])==null?void 0:y.id)??null})}catch(m){o(m instanceof Error?m.message:String(m))}};_.useEffect(()=>{p()},[]);const x=async()=>{var g,y;const m=e==null?void 0:e.find(b=>b.id===s);if(m){if(m.kind==="bundle"){f(m.id);return}u(!0),c(null);try{const b=await Ac.createStarterTeam(m.id);t({starterId:m.id,teamId:((g=b.team)==null?void 0:g.id)??null,teamName:((y=b.team)==null?void 0:y.name)??null,suggestions:m.suggestions})}catch(b){c(b instanceof Error?b.message:String(b))}finally{u(!1)}}};if(a)return i.jsx(Ye,{variant:"error",title:"Couldn't load team templates",children:i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{children:a}),i.jsx(ue,{type:"button",size:"sm",variant:"secondary",icon:$t,onClick:()=>void p(),children:"Retry"})]})});if(!e)return i.jsx(zt,{centered:!0,text:"Loading team templates…"});if(h)return i.jsx(c4e,{templateId:h,onBack:()=>f(null),onDone:t});const v=e.find(m=>m.id===s)??null;return i.jsxs("div",{className:"space-y-3","data-testid":"starter-team-step",children:[i.jsx("div",{role:"radiogroup","aria-label":"First team",className:"space-y-3",children:e.map(m=>{const g=m.id===s;return i.jsx(tn,{role:"radio","aria-checked":g,tabIndex:0,interactive:!0,padding:"md","data-testid":`starter-${m.id}`,className:g?"border-primary ring-1 ring-primary cursor-pointer":"cursor-pointer",onClick:()=>r(m.id),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),r(m.id))},children:i.jsxs("div",{className:"flex items-start justify-between gap-3",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx("span",{className:"font-semibold text-text-primary-dark",children:m.label}),i.jsx("span",{className:"text-xs text-text-secondary-dark",children:m.name}),m.recommended&&i.jsx(mn,{variant:"primary",children:"Recommended"}),m.kind==="bundle"&&i.jsx(mn,{variant:"info",children:"Bundle"})]}),i.jsx("p",{className:"mt-1 text-sm text-text-secondary-dark",children:m.tagline}),m.members.length>0&&i.jsxs("p",{className:"mt-2 flex items-center gap-1 text-xs text-text-secondary-dark",children:[i.jsx(vr,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),m.members.map(y=>y.name).join(", ")]})]}),g&&i.jsx(rs,{className:"h-5 w-5 shrink-0 text-primary","aria-hidden":!0})]})},m.id)})}),l&&i.jsx(Ye,{variant:"error",size:"sm",children:l}),i.jsx(ue,{type:"button",fullWidth:!0,loading:d,disabled:!v,onClick:()=>void x(),"data-testid":"starter-create",children:(v==null?void 0:v.members.length)===0?"Start with just the Orc":(v==null?void 0:v.kind)==="bundle"?`Next: details for "${v.label}"`:`Create "${(v==null?void 0:v.label)??""}"`})]})},u4e=4e3,h4e=({suggestions:t,teamId:e,teamName:n,onSent:s})=>{const[r,a]=_.useState(""),[o,l]=_.useState(!1),[c,d]=_.useState(null),[u,h]=_.useState(null),f=r.trim(),p=async()=>{if(f){l(!0),d(null);try{const x=await Ac.sendFirstTask(f,e);h(x),s(x)}catch(x){d(x instanceof Error?x.message:String(x))}finally{l(!1)}}};return u?i.jsx(Ye,{variant:"success",title:"Handed to the Orc","data-testid":"first-task-sent",children:u.message?"The Orc starts on it as soon as it is online.":"The Orc will get the team on it and report progress in chat and Slack."}):i.jsxs("div",{className:"space-y-3","data-testid":"first-task-step",children:[i.jsxs("p",{className:"text-sm text-text-secondary-dark",children:[n?`For "${n}"`:"For the Orc",": one sentence is enough."]}),i.jsx(er,{"aria-label":"First task",rows:4,maxLength:u4e,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(ue,{type:"button",size:"sm",variant:"outline",className:"h-auto min-h-9 justify-start whitespace-normal py-2 text-left font-normal",onClick:()=>a(x),children:x},x))})]}),c&&i.jsx(Ye,{variant:"error",size:"sm",children:c}),i.jsx(ue,{type:"button",fullWidth:!0,icon:em,loading:o,disabled:!f,onClick:()=>void p(),"data-testid":"first-task-send",children:"Send it"})]})},f4e=({connected:t,tier:e,tokenPageSignInUrl:n,onConnected:s,navigateTo:r=a=>window.location.assign(a)})=>{const[a,o]=_.useState(!1),[l,c]=_.useState(""),[d,u]=_.useState(""),[h,f]=_.useState(!1),[p,x]=_.useState(null);if(t)return i.jsxs(Ye,{variant:"success",icon:vo,title:"Connected to Crewly Cloud","data-testid":"cloud-connected",children:[e?`Plan: ${e}. `:"","You can use Crewly from your phone now."]});const v=async()=>{f(!0),x(null);try{await Ac.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(VV,{autoStart:!0,labels:wL,onConnected:()=>s()}),i.jsxs("div",{className:"space-y-1 border-t border-border-dark pt-3",children:[i.jsx(ue,{type:"button",variant:"secondary",fullWidth:!0,icon:Zp,onClick:()=>r(Ioe(window.location.origin,HR("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(zs,{className:"h-3 w-3","aria-hidden":!0})]}),". After you sign in it shows two tokens."]}),i.jsx("p",{className:"text-sm text-text-secondary-dark",children:"2. Copy each of them here:"}),i.jsxs("div",{className:"space-y-1",children:[i.jsx(_t,{htmlFor:"cloud-token",children:"Token"}),i.jsx(Dt,{id:"cloud-token",autoComplete:"off",spellCheck:!1,value:l,onChange:m=>c(m.target.value)})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx(_t,{htmlFor:"cloud-refresh-token",children:"Refresh token (keeps you signed in)"}),i.jsx(Dt,{id:"cloud-refresh-token",autoComplete:"off",spellCheck:!1,value:d,onChange:m=>u(m.target.value)})]}),!d.trim()&&l.trim()&&i.jsx("p",{className:"text-xs text-yellow-400",children:"Without a refresh token you will need to sign in again in about an hour."}),p&&i.jsx(Ye,{variant:"error",size:"sm",children:p}),i.jsx(ue,{type:"button",fullWidth:!0,loading:h,disabled:!l.trim(),onClick:()=>void v(),"data-testid":"cloud-paste-save",children:"Connect"})]}):i.jsx(ue,{type:"button",variant:"link",onClick:()=>o(!0),"data-testid":"cloud-show-paste",children:"Didn't come back? Use copy and paste instead"})]})},p4e="/connections?platform=slack",m4e=({connected:t,cloudConnected:e,onGoToCloud:n,onConnected:s,navigateTo:r=a=>window.location.assign(a)})=>{const[a,o]=_.useState(!1),[l,c]=_.useState(null),d=_.useRef(!1);if(_.useEffect(()=>{t||!e||d.current||(d.current=!0,Ac.refreshSlack().then(h=>{h.connected&&s()}).catch(()=>{}))},[t,e,s]),t)return i.jsx(Ye,{variant:"success",icon:vo,title:"Slack connected","data-testid":"slack-connected",children:"DM Crewly in Slack, or @ it in a team channel."});if(!e)return i.jsxs("div",{className:"space-y-3","data-testid":"slack-needs-cloud",children:[i.jsx(Ye,{variant:"info",size:"sm",children:"Slack is installed through Crewly Cloud. Connect Crewly Cloud first."}),i.jsx(ue,{type:"button",variant:"secondary",fullWidth:!0,onClick:n,children:"Connect Crewly Cloud"})]});const u=async()=>{o(!0),c(null);try{const h=await Ac.getSlackInstallUrl(`${window.location.origin}${HR("slack")}`);r(h)}catch(h){c(h instanceof Error?h.message:String(h)),o(!1)}};return i.jsxs("div",{className:"space-y-3","data-testid":"slack-connect-step",children:[i.jsx("p",{className:"text-sm text-text-secondary-dark",children:"Add Crewly to your Slack workspace to hand out work and follow progress from Slack."}),l&&i.jsx(Ye,{variant:"error",size:"sm",children:l}),i.jsx(ue,{type:"button",fullWidth:!0,icon:Cc,loading:a,onClick:()=>void u(),"data-testid":"slack-install",children:"Install Crewly in Slack"}),i.jsxs("a",{href:p4e,className:"inline-flex items-center gap-1 text-xs text-primary underline",children:["More Slack settings ",i.jsx(zs,{className:"h-3 w-3","aria-hidden":!0})]})]})},g4e=({harness:t,selectName:e,selected:n=!1,onSelect:s,onInstallFinished:r})=>{const{job:a,error:o,running:l,start:c}=zV(t.id,r),d=Im[t.loginState],u=!t.installed||t.updateAvailable||(a==null?void 0:a.state)==="failed",h=(a==null?void 0:a.state)==="failed"?"Retry install":t.installed?"Update":"Install",f=i.jsx("span",{className:"font-semibold text-text-primary-dark",children:Rm(t)});return i.jsxs(tn,{padding:"md","data-testid":`harness-card-${t.id}`,className:n?"border-primary":void 0,children:[i.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[i.jsxs("div",{className:"min-w-0",children:[e?i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx("input",{type:"radio",name:e,value:t.id,checked:n,onChange:()=>s==null?void 0:s(t.id),className:"h-4 w-4 accent-[var(--crewly-primary)]"}),f]}):f,i.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[t.installed?i.jsxs(mn,{variant:"success",children:["Installed",t.version?` v${t.version}`:""]}):i.jsx(mn,{variant:"default",children:"Not installed"}),t.installed&&t.updateAvailable&&i.jsxs(mn,{variant:"info",children:["Update available",t.latestVersion?` → v${t.latestVersion}`:""]}),t.installed&&i.jsx(mn,{variant:d.variant,children:d.label}),t.installed&&t.loginSource&&i.jsx("span",{className:"text-xs text-text-secondary-dark",children:t.loginSource})]})]}),u&&i.jsx(ue,{type:"button",variant:t.installed&&(a==null?void 0:a.state)!=="failed"?"secondary":"primary",size:"sm",icon:t.installed?$t:Cm,loading:l,onClick:()=>void c(),className:"shrink-0 self-start",children:l?"Installing…":h})]}),o&&i.jsx(Ye,{variant:"error",size:"sm",className:"mt-3",children:o}),a&&i.jsx(GV,{log:a.log}),(a==null?void 0:a.state)==="succeeded"&&i.jsx(Ye,{variant:"success",size:"sm",className:"mt-3",title:"Installed",children:a.usedUserPrefix?"Installed to your user folder (no admin rights needed).":`${t.displayName} is ready.`}),(a==null?void 0:a.state)==="failed"&&!o&&i.jsx(Ye,{variant:"error",size:"sm",className:"mt-3",title:"Install failed",children:"Check the log above and try again."})]})},x4e="harness-choice",y4e=({harnesses:t,systemTools:e=[],selectedId:n,onSelect:s,onInstallFinished:r})=>{const a=e.filter(o=>!o.installed);return i.jsxs("div",{className:"space-y-3","data-testid":"harness-list",children:[i.jsx("div",{role:s?"radiogroup":void 0,"aria-label":s?"Choose a coding harness":void 0,className:"space-y-3",children:t.map(o=>i.jsx(g4e,{harness:o,selectName:s?x4e:void 0,selected:s?n===o.id:!1,onSelect:s,onInstallFinished:()=>r==null?void 0:r()},o.id))}),a.map(o=>i.jsxs(Ye,{variant:"warning",size:"sm",title:`Missing system tool: ${o.id}`,children:[i.jsx("span",{children:"Some skills need it. Install with:"}),i.jsx("code",{className:"ml-1 rounded bg-background-dark px-1.5 py-0.5 font-mono text-xs",children:o.installHint})]},o.id))]})},v4e=["harness","team","first_task","cloud","slack"];function b4e(t){return typeof t=="string"&&v4e.includes(t)}function pS(t,e){return t==null?void 0:t.steps.find(n=>n.id===e)}const Qn={HARNESS:0,ORC:1,LOGIN:2,TEAM:3,TASK:4,CLOUD:5,SLACK:6,DONE:7},_4e={harness:Qn.HARNESS,team:Qn.TEAM,first_task:Qn.TASK,cloud:Qn.CLOUD,slack:Qn.SLACK};function S4e(t){return b4e(t)?_4e[t]:Qn.HARNESS}function n6(t,e){var r;const n=((r=pS(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 xd=({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})]}),M_=({onBack:t,onNext:e,nextLabel:n,primary:s})=>i.jsxs("div",{className:"mt-6 flex justify-between gap-3",children:[i.jsx(ue,{type:"button",variant:"ghost",icon:Ba,onClick:t,children:"Back"}),i.jsx(ue,{type:"button",variant:s?"primary":"secondary",icon:Lp,iconPosition:"right",onClick:e,children:n})]}),w4e=()=>{const t=cs(),[e]=Lc(),{overview:n,loading:s,error:r,refresh:a,setOrcHarness:o,savingOrc:l,replaceHarness:c}=UV(),{checklist:d,loading:u,refresh:h}=Q9(),[f,p]=_.useState(()=>S4e(e.get(J9))),[x,v]=_.useState(IR),[m,g]=_.useState(null),[y,b]=_.useState(null),[S,E]=_.useState(!1),k=e.get("error"),T=T9((n==null?void 0:n.harnesses)??[],n==null?void 0:n.orcHarness),A=T.some(P=>P.installed),N=T.find(P=>P.id===(n==null?void 0:n.orcHarness))??null;_.useEffect(()=>{if(f!==Qn.TASK||y||u)return;let P=!1;return Ac.getStarters().then(B=>{P||b(n6(d,B))}).catch(()=>{P||b(n6(d,[]))}),()=>{P=!0}},[f,y,d,u]);const M=()=>{JFe(!0),t(PO,{replace:!0})},L=()=>{g(ECe(T,(n==null?void 0:n.orcHarness)??null,x)),p(Qn.ORC)},j=async()=>{m&&(m!==(n==null?void 0:n.orcHarness)&&!await o(m)||p(Qn.LOGIN))},D=P=>{b({teamId:P.teamId,teamName:P.teamName,suggestions:P.suggestions,bundle:P.bundle}),h(),p(Qn.TASK)},U=_.useCallback(()=>{h()},[h]),$=()=>u?i.jsx(zt,{centered:!0}):i.jsx(Ye,{variant:"error",size:"sm",children:i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{children:"Couldn't load the setup checklist."}),i.jsx(ue,{type:"button",size:"sm",variant:"secondary",icon:$t,onClick:U,children:"Retry"})]})}),G=()=>s?i.jsx(zt,{centered:!0,text:"Checking coding harnesses…"}):i.jsx(Ye,{variant:"error",title:"Couldn't load harness status",children:i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{children:r}),i.jsx(ue,{type:"button",size:"sm",variant:"secondary",icon:$t,onClick:()=>void a(),children:"Retry"})]})}),K=()=>{var P;if(f<=Qn.LOGIN&&!n)return G();switch(f){case Qn.HARNESS:return i.jsxs(i.Fragment,{children:[i.jsx(xd,{title:"Pick and install a coding harness",subtitle:"Crewly's AI teammates work through a coding harness. Claude Code is recommended."}),i.jsx(y4e,{harnesses:T,systemTools:(n==null?void 0:n.systemTools)??[],selectedId:x,onSelect:v,onInstallFinished:()=>void a()}),i.jsx("div",{className:"mt-6 flex justify-end",children:i.jsx(ue,{type:"button",icon:Lp,iconPosition:"right",disabled:!A,onClick:L,children:"Next"})}),!A&&i.jsx("p",{className:"mt-2 text-right text-xs text-text-secondary-dark",children:"Install at least one to continue."})]});case Qn.ORC:return i.jsxs(i.Fragment,{children:[i.jsx(xd,{title:"Which harness should the Orc use?",subtitle:"The orchestrator (Orc) coordinates your team. Choose its harness."}),i.jsx($V,{harnesses:T,value:m,onChange:g,disabled:l}),r&&i.jsx(Ye,{variant:"error",size:"sm",className:"mt-3",children:r}),i.jsxs("div",{className:"mt-6 flex justify-between gap-3",children:[i.jsx(ue,{type:"button",variant:"ghost",icon:Ba,onClick:()=>p(Qn.HARNESS),children:"Back"}),i.jsx(ue,{type:"button",icon:Lp,iconPosition:"right",loading:l,disabled:!m,onClick:()=>void j(),children:"Next"})]})]});case Qn.LOGIN:{const B=(N==null?void 0:N.loginState)==="logged_in";return i.jsxs(i.Fragment,{children:[i.jsx(xd,{title:"Sign in",subtitle:"Sign in so the orchestrator can work."}),N?i.jsx(HV,{harness:N,onLoggedIn:()=>void a(),onHarnessUpdated:c}):i.jsx(Ye,{variant:"warning",size:"sm",children:"Go back one step and choose the Orc's harness first."}),i.jsxs("div",{className:"mt-6 flex justify-between gap-3",children:[i.jsx(ue,{type:"button",variant:"ghost",icon:Ba,onClick:()=>p(Qn.ORC),children:"Back"}),i.jsx(ue,{type:"button",variant:B?"primary":"secondary",icon:Lp,iconPosition:"right",onClick:()=>p(Qn.TEAM),children:B?"Next":"Sign in later"})]})]})}case Qn.TEAM:{const B=((P=pS(d,"team"))==null?void 0:P.detail.teams)??[];return i.jsxs(i.Fragment,{children:[i.jsx(xd,{title:"Create your first team",subtitle:"Pick a starter team. You can add more later."}),B.length>0&&i.jsxs(Ye,{variant:"success",size:"sm",className:"mb-3",children:["Existing teams: ",B.map(I=>I.name).join(", "),". You can go straight to the next step or create another."]}),i.jsx(d4e,{onDone:D}),i.jsx(M_,{onBack:()=>p(Qn.LOGIN),onNext:()=>p(Qn.TASK),nextLabel:"Skip",primary:!1})]})}case Qn.TASK:return i.jsxs(i.Fragment,{children:[i.jsx(xd,{title:"Give your team its first task",subtitle:"One sentence is enough."}),(y==null?void 0:y.bundle)&&i.jsx(Ye,{variant:"success",size:"sm",className:"mb-3","data-testid":"setup-bundle-first-week",children:"The first week of work is already planned and the team will start day by day. Want to add something else? Write it below."}),y?i.jsx(h4e,{suggestions:y.suggestions,teamId:y.teamId,teamName:y.teamName,onSent:()=>{E(!0),U()}}):i.jsx(zt,{centered:!0}),i.jsx(M_,{onBack:()=>p(Qn.TEAM),onNext:()=>p(Qn.CLOUD),nextLabel:S?"Next":"Skip",primary:S})]});case Qn.CLOUD:{const B=pS(d,"cloud");return i.jsxs(i.Fragment,{children:[i.jsx(xd,{title:"Connect Crewly Cloud",subtitle:"Manage Crewly from your phone; needed for Slack."}),k&&!(B!=null&&B.done)&&i.jsxs(Ye,{variant:"warning",size:"sm",className:"mb-3",children:["Sign-in didn't finish (",k,"). Try again, or use copy and paste instead."]}),B?i.jsx(f4e,{connected:B.done,tier:B.detail.tier,tokenPageSignInUrl:B.detail.tokenPageSignInUrl,onConnected:U}):$(),i.jsx(M_,{onBack:()=>p(Qn.TASK),onNext:()=>p(Qn.SLACK),nextLabel:B!=null&&B.done?"Next":"Skip",primary:!!(B!=null&&B.done)})]})}case Qn.SLACK:{const B=pS(d,"slack");return i.jsxs(i.Fragment,{children:[i.jsx(xd,{title:"Connect Slack",subtitle:"Talk to your team from Slack."}),B?i.jsx(m4e,{connected:B.done,cloudConnected:B.detail.cloudConnected,onGoToCloud:()=>p(Qn.CLOUD),onConnected:U}):$(),i.jsx(M_,{onBack:()=>p(Qn.CLOUD),onNext:()=>p(Qn.DONE),nextLabel:B!=null&&B.done?"Next":"Skip",primary:!!(B!=null&&B.done)})]})}default:{const B=N?Im[N.loginState]:null;return i.jsxs("div",{className:"space-y-4","data-testid":"setup-done",children:[i.jsxs("div",{className:"text-center",children:[i.jsx(vo,{className:"mx-auto h-12 w-12 text-emerald-400"}),i.jsx(xd,{title:"Setup complete",subtitle:"You're ready to use Crewly."})]}),N&&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:Rm(N)})," ",i.jsx(mn,{variant:B.variant,children:B.label})]}),d&&i.jsx("ul",{className:"space-y-2","data-testid":"setup-done-checklist",children:d.steps.map(I=>i.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[I.done?i.jsx(vo,{className:"h-4 w-4 text-emerald-400","aria-label":"Done"}):i.jsx(Zj,{className:"h-4 w-4 text-text-secondary-dark","aria-label":"Not done"}),i.jsx("span",{className:I.done?"text-text-primary-dark":"text-text-secondary-dark",children:FM[I.id]})]},I.id))}),i.jsx("p",{className:"text-center text-xs text-text-secondary-dark",children:'Unfinished steps stay in the "Get started" card on the dashboard. If a login expires, sign in again under Settings → Runtimes.'}),i.jsx("div",{className:"text-center",children:i.jsx(ue,{type:"button",size:"default",onClick:()=>t(PO,{replace:!0}),children:"Open Crewly"})})]})}}};return i.jsx(kre,{className:"min-h-screen px-4 py-6 sm:py-10",children:i.jsxs("div",{className:"mx-auto w-full max-w-2xl",children:[i.jsxs("header",{className:"mb-6 flex items-center justify-between gap-3",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Crewly setup"}),i.jsx("p",{className:"text-sm text-text-secondary-dark",children:"First-run setup"})]}),f!==Qn.DONE&&i.jsx(ue,{type:"button",variant:"link",onClick:M,"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,"/",Uk.length," · ",Uk[f]]}),i.jsx("div",{className:"mb-6 hidden overflow-x-auto sm:block",children:i.jsx(QFe,{steps:[...Uk],currentStep:f})}),i.jsx(tn,{padding:"none",className:"p-4 sm:p-6",children:K()})]})})};function E4e(){return i.jsx(Dse,{children:i.jsx(woe,{children:i.jsx(ooe,{children:i.jsxs(Iee,{children:[i.jsx(XFe,{}),i.jsxs(UQ,{children:[i.jsx(ZFe,{}),i.jsxs(jQ,{children:[i.jsx(ts,{path:"/auth/callback",element:i.jsx(WOe,{})}),i.jsx(ts,{path:"/auth",element:i.jsx(KOe,{})}),i.jsx(ts,{path:"/setup",element:i.jsx(w4e,{})}),i.jsxs(ts,{path:"/",element:i.jsx(Coe,{}),children:[i.jsx(ts,{index:!0,element:i.jsx(rle,{})}),i.jsx(ts,{path:"projects",element:i.jsx(hle,{})}),i.jsx(ts,{path:"projects/:id",element:i.jsx(yde,{})}),i.jsx(ts,{path:"teams",element:i.jsx(NFe,{})}),i.jsx(ts,{path:"teams/goals/:id",element:i.jsx(dX,{})}),i.jsx(ts,{path:"teams/:id",element:i.jsx(Cue,{})}),i.jsx(ts,{path:"assignments",element:i.jsx(Rue,{})}),i.jsx(ts,{path:"scheduled-checkins",element:i.jsx(Fue,{})}),i.jsx(ts,{path:"triggers",element:i.jsx(lhe,{})}),i.jsx(ts,{path:"factory",element:i.jsx(UEe,{})}),i.jsx(ts,{path:"connections",element:i.jsx(qTe,{})}),i.jsx(ts,{path:"browser",element:i.jsx(kNe,{})}),i.jsx(ts,{path:"marketplace",element:i.jsx(VFe,{})}),i.jsx(ts,{path:"marketplace/:id",element:i.jsx(LNe,{})}),i.jsx(ts,{path:"wiki",element:i.jsx(yOe,{})}),i.jsx(ts,{path:"usage",element:i.jsx($Oe,{})}),i.jsx(ts,{path:"settings",element:i.jsx(pke,{})}),i.jsx(ts,{path:"pricing",element:i.jsx(YOe,{})}),i.jsx(ts,{path:"tickets",element:i.jsx(uFe,{})}),i.jsx(ts,{path:"tickets/requests/:id",element:i.jsx(bX,{})}),i.jsx(ts,{path:"tickets/runs/:id",element:i.jsx(mX,{})}),i.jsx(ts,{path:"tickets/experiments/:id",element:i.jsx(CX,{})}),i.jsx(ts,{path:"tickets/traces/:traceId",element:i.jsx(kX,{})}),i.jsx(ts,{path:"team-chat",element:i.jsx(WAe,{})}),Qse.map(t=>i.jsx(ts,{path:t.path,element:i.jsx(KFe,{rule:t})},t.path))]})]})]})]})})})})}const jX="/api/auth/session",J2="X-Crewly-CSRF",s6="owner_auth_required",C4e=["POST","PUT","PATCH","DELETE"];let lN=null,lx=null,RX=null;function k4e(t){if(!t||!MR(t))return null;try{return new URL(t,window.location.origin).pathname}catch{return null}}function Z2(t){const e=k4e(t);return e!==null&&e.startsWith("/api/")&&e!==jX}function Q2(t){return C4e.includes((t??"GET").toUpperCase())}function IX(t,e){if(t!==401)return!1;const n=e;return(n==null?void 0:n.error)===s6||(n==null?void 0:n.code)===s6}function W0(t=!1){return!t&&lN?Promise.resolve(lN):lx||(lx=(RX??window.fetch.bind(window))(jX,{credentials:"same-origin",cache:"no-store"}).then(async n=>{var a;const s=await n.json().catch(()=>null),r=n.ok&&typeof((a=s==null?void 0:s.data)==null?void 0:a.csrfToken)=="string"?s.data.csrfToken:null;return lN=r,r}).catch(()=>null).finally(()=>{lx=null}),lx)}function A4e(t=window){const e=t.fetch.bind(t);RX=e;const n=async(s,r)=>{var p,x;const a=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!Z2(a))return e(s,r);const o=(r==null?void 0:r.method)??(s instanceof Request?s.method:"GET"),l=Q2(o),c=s instanceof Request?s.clone():s,d=v=>{if(!l||!v)return r;const m=new Headers((r==null?void 0:r.headers)??(s instanceof Request?s.headers:void 0));return m.set(J2,v),{...r,headers:m}},u=await e(s,d(l?await W0():null));if(jR((x=(p=u.headers)==null?void 0:p.get)==null?void 0:x.call(p,A9)),u.status!==401)return u;const h=await u.clone().json().catch(()=>null);if(!IX(u.status,h))return u;const f=await W0(!0);return f?e(c,d(f)):u};t.fetch=n}function T4e(t=Ue){t.interceptors.request.use(async n=>{if(Z2(n.url)&&Q2(n.method)){const s=await W0();s&&n.headers.set(J2,s)}return n});const e=async(n,s,r)=>{if(!n||n.__crewlyOwnerRetry||!Z2(n.url)||!IX(s,r))return null;const a=await W0(!0);return a?(n.__crewlyOwnerRetry=!0,Q2(n.method)&&n.headers.set(J2,a),t.request(n)):null};t.interceptors.response.use(async n=>{var r;const s=(r=n.headers)==null?void 0:r[A9.toLowerCase()];return jR(typeof s=="string"?s:void 0),await e(n.config,n.status,n.data)??n},async n=>{const s=n==null?void 0:n.response,r=s?await e(n.config,s.status,s.data):null;return r||Promise.reject(n)})}function N4e(){A4e(),T4e(),W0()}rae();N4e();cN.createRoot(document.getElementById("root")).render(i.jsx(an.StrictMode,{children:i.jsx(E4e,{})}));
4955
- //# sourceMappingURL=index-2db17f1e.js.map
4955
+ //# sourceMappingURL=index-83188f0b.js.map