@runfusion/fusion 0.26.0 → 0.27.1

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 (174) hide show
  1. package/dist/bin.js +12847 -2514
  2. package/dist/client/assets/AgentDetailView-B7QRcHJH.css +1 -0
  3. package/dist/client/assets/AgentDetailView-shgiiUb4.js +18 -0
  4. package/dist/client/assets/{AgentsView-CV3vm7Qk.css → AgentsView-B3ADnF0D.css} +1 -1
  5. package/dist/client/assets/{AgentsView-D6Zi5zfP.js → AgentsView-CpwqOVDz.js} +12 -7
  6. package/dist/client/assets/ChatView-DyRBOIKL.js +1 -0
  7. package/dist/client/assets/{DevServerView--_WBvIDQ.js → DevServerView-Cdelj9-m.js} +1 -1
  8. package/dist/client/assets/{DirectoryPicker-xedtR-Rd.js → DirectoryPicker-C0kmRv0u.js} +1 -1
  9. package/dist/client/assets/{DocumentsView-Bg2oaZks.js → DocumentsView-B94U9ijs.js} +1 -1
  10. package/dist/client/assets/{EvalsView-B3uOCXfr.js → EvalsView-O_4YWy--.js} +1 -1
  11. package/dist/client/assets/{ExperimentalAgentOnboardingModal-Bx6yXVS5.js → ExperimentalAgentOnboardingModal-CkEiF85-.js} +1 -1
  12. package/dist/client/assets/InsightsView-D-Qe0tRr.js +11 -0
  13. package/dist/client/assets/{MemoryView-xcN_eouf.js → MemoryView-CoRUmRvb.js} +2 -2
  14. package/dist/client/assets/NodesView-DQzXjcLc.js +14 -0
  15. package/dist/client/assets/{PiExtensionsManager-Cc8aAZXg.js → PiExtensionsManager-Dn1LmFbq.js} +2 -2
  16. package/dist/client/assets/PluginManager-Y0fs-6No.js +1 -0
  17. package/dist/client/assets/{ResearchView-CERNf7sJ.js → ResearchView-CjOxKhdS.js} +1 -1
  18. package/dist/client/assets/{SettingsModal-B1r0yASu.js → SettingsModal-Bg1-3JO_.js} +1 -1
  19. package/dist/client/assets/{SettingsModal-Cis-4Lot.css → SettingsModal-Ci0_sqbU.css} +1 -1
  20. package/dist/client/assets/SettingsModal-DL7tjJQa.js +31 -0
  21. package/dist/client/assets/SettingsModal-DWKgRxBA.css +1 -0
  22. package/dist/client/assets/{SetupWizardModal-D1q548_L.js → SetupWizardModal-DuzYPbuJ.js} +1 -1
  23. package/dist/client/assets/{SkillsView-ClLM6u6p.js → SkillsView-BIFoVNUf.js} +1 -1
  24. package/dist/client/assets/{StashRecoveryView-ze0pEZ5U.js → StashRecoveryView-C52KsV7f.js} +1 -1
  25. package/dist/client/assets/{TodoView-CTmIfy2M.js → TodoView-sS_mT0Y7.js} +2 -2
  26. package/dist/client/assets/{dashboard-view-CyWN-d02.js → dashboard-view-BWGH_fAq.js} +1 -1
  27. package/dist/client/assets/dashboard-view-BoTzlP8b.css +1 -0
  28. package/dist/client/assets/dashboard-view-MB-86hAu.js +21 -0
  29. package/dist/client/assets/{folder-open-BZuKESeq.js → folder-open-B9cwJ-OX.js} +1 -1
  30. package/dist/client/assets/index-BOjPRqEk.js +692 -0
  31. package/dist/client/assets/index-BmSEq8Rb.css +1 -0
  32. package/dist/client/assets/{star-D75YKEq-.js → star-BDn04UYV.js} +1 -1
  33. package/dist/client/assets/{upload-BYYTgWFj.js → upload-zdPPycKQ.js} +1 -1
  34. package/dist/client/assets/{users-RS90Aii3.js → users-CPYZjK2g.js} +1 -1
  35. package/dist/client/index.html +2 -2
  36. package/dist/client/version.json +1 -1
  37. package/dist/droid-cli/package.json +1 -1
  38. package/dist/droid-cli/src/__tests__/index.test.ts +228 -0
  39. package/dist/extension.js +7433 -1920
  40. package/dist/pi-claude-cli/package.json +1 -1
  41. package/dist/pi-claude-cli/src/__tests__/provider.test.ts +36 -22
  42. package/dist/pi-claude-cli/src/provider.ts +7 -1
  43. package/dist/plugins/fusion-plugin-cli-printing-press/manifest.json +19 -1
  44. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +20 -2
  45. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/TestRunnerPanel.test.tsx +99 -0
  46. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/config-flow.test.ts +91 -0
  47. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/dashboard-view.test.tsx +40 -0
  48. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/dashboard-views.test.ts +46 -0
  49. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/draft-store.test.ts +50 -0
  50. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/fixtures/exec-mock.ts +80 -0
  51. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/fixtures/fixtures.test.ts +40 -0
  52. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/fixtures/registry.ts +82 -0
  53. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/generator.test.ts +54 -0
  54. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/manage-view.test.tsx +98 -0
  55. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/manifest.test.ts +21 -5
  56. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/registration.test.ts +29 -0
  57. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/run-routes.test.ts +98 -0
  58. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/runner.test.ts +55 -0
  59. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/runtime-availability.test.ts +61 -0
  60. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/validation.test.ts +30 -0
  61. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/wizard-routes.test.ts +61 -0
  62. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/workflow-integration.test.ts +19 -0
  63. package/dist/plugins/fusion-plugin-cli-printing-press/src/dashboard-view.css +43 -0
  64. package/dist/plugins/fusion-plugin-cli-printing-press/src/dashboard-view.tsx +49 -0
  65. package/dist/plugins/fusion-plugin-cli-printing-press/src/generation/generator.ts +95 -0
  66. package/dist/plugins/fusion-plugin-cli-printing-press/src/generation/redact.ts +9 -0
  67. package/dist/plugins/fusion-plugin-cli-printing-press/src/generation/runner.ts +79 -0
  68. package/dist/plugins/fusion-plugin-cli-printing-press/src/generation/types.ts +31 -0
  69. package/dist/plugins/fusion-plugin-cli-printing-press/src/index.ts +46 -2
  70. package/dist/plugins/fusion-plugin-cli-printing-press/src/manage/EditDraftModal.tsx +75 -0
  71. package/dist/plugins/fusion-plugin-cli-printing-press/src/manage/useDrafts.ts +73 -0
  72. package/dist/plugins/fusion-plugin-cli-printing-press/src/manage-view.css +79 -0
  73. package/dist/plugins/fusion-plugin-cli-printing-press/src/manage-view.tsx +122 -0
  74. package/dist/plugins/fusion-plugin-cli-printing-press/src/routes/wizard-routes.ts +272 -0
  75. package/dist/plugins/fusion-plugin-cli-printing-press/src/run/TestRunnerPanel.css +70 -0
  76. package/dist/plugins/fusion-plugin-cli-printing-press/src/run/TestRunnerPanel.tsx +98 -0
  77. package/dist/plugins/fusion-plugin-cli-printing-press/src/run/useRunGeneratedCli.ts +37 -0
  78. package/dist/plugins/fusion-plugin-cli-printing-press/src/runtime/__tests__/executor-runtime-env.test.ts +191 -0
  79. package/dist/plugins/fusion-plugin-cli-printing-press/src/runtime/executor-runtime-env.ts +75 -0
  80. package/dist/plugins/fusion-plugin-cli-printing-press/src/storage/draft-store.ts +85 -0
  81. package/dist/plugins/fusion-plugin-cli-printing-press/src/store/__tests__/cli-press-store.test.ts +128 -0
  82. package/dist/plugins/fusion-plugin-cli-printing-press/src/store/__tests__/credentials.test.ts +62 -0
  83. package/dist/plugins/fusion-plugin-cli-printing-press/src/store/cli-press-store.ts +427 -0
  84. package/dist/plugins/fusion-plugin-cli-printing-press/src/store/cli-press-types.ts +110 -0
  85. package/dist/plugins/fusion-plugin-cli-printing-press/src/store/credentials.ts +95 -0
  86. package/dist/plugins/fusion-plugin-cli-printing-press/src/wizard/steps.tsx +55 -0
  87. package/dist/plugins/fusion-plugin-cli-printing-press/src/wizard/types.ts +33 -0
  88. package/dist/plugins/fusion-plugin-cli-printing-press/src/wizard/validation.ts +63 -0
  89. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  90. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  91. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  92. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  93. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  94. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  95. package/dist/plugins/fusion-plugin-reports/manifest.json +10 -0
  96. package/dist/plugins/fusion-plugin-reports/package.json +18 -2
  97. package/dist/plugins/fusion-plugin-reports/src/__tests__/approval.test.ts +164 -0
  98. package/dist/plugins/fusion-plugin-reports/src/__tests__/manifest.test.ts +14 -0
  99. package/dist/plugins/fusion-plugin-reports/src/__tests__/routes-approval.test.ts +109 -0
  100. package/dist/plugins/fusion-plugin-reports/src/__tests__/scaffold.test.ts +60 -0
  101. package/dist/plugins/fusion-plugin-reports/src/__tests__/share-blocks.test.ts +83 -0
  102. package/dist/plugins/fusion-plugin-reports/src/aggregation.ts +23 -0
  103. package/dist/plugins/fusion-plugin-reports/src/approval.ts +97 -0
  104. package/dist/plugins/fusion-plugin-reports/src/cadence.ts +23 -0
  105. package/dist/plugins/fusion-plugin-reports/src/dashboard/ReportsView.css +82 -0
  106. package/dist/plugins/fusion-plugin-reports/src/dashboard/ReportsView.tsx +24 -0
  107. package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/ReportComparisonDrawer.test.tsx +12 -0
  108. package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/ReportDetailPanel.test.tsx +12 -0
  109. package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/ReportFiltersBar.test.tsx +14 -0
  110. package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/ReportsView.test.tsx +27 -0
  111. package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/api.test.ts +19 -0
  112. package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/useReportSectionDiff.test.ts +11 -0
  113. package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/useReports.test.ts +13 -0
  114. package/dist/plugins/fusion-plugin-reports/src/dashboard/api.ts +85 -0
  115. package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ReportApprovalPanel.css +59 -0
  116. package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ReportApprovalPanel.tsx +58 -0
  117. package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ReportComparisonDrawer.tsx +21 -0
  118. package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ReportDetailPanel.tsx +29 -0
  119. package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ReportEmptyState.tsx +3 -0
  120. package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ReportFiltersBar.tsx +19 -0
  121. package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ReportListItem.tsx +8 -0
  122. package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ShareBlocksPanel.css +29 -0
  123. package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ShareBlocksPanel.tsx +43 -0
  124. package/dist/plugins/fusion-plugin-reports/src/dashboard/components/__tests__/ReportApprovalPanel.test.tsx +38 -0
  125. package/dist/plugins/fusion-plugin-reports/src/dashboard/components/__tests__/ShareBlocksPanel.test.tsx +24 -0
  126. package/dist/plugins/fusion-plugin-reports/src/dashboard/test-setup.ts +18 -0
  127. package/dist/plugins/fusion-plugin-reports/src/dashboard/types.ts +22 -0
  128. package/dist/plugins/fusion-plugin-reports/src/dashboard/useReportPreview.ts +44 -0
  129. package/dist/plugins/fusion-plugin-reports/src/dashboard/useReportSectionDiff.ts +59 -0
  130. package/dist/plugins/fusion-plugin-reports/src/dashboard/useReports.ts +71 -0
  131. package/dist/plugins/fusion-plugin-reports/src/dashboard/useViewportMode.ts +13 -0
  132. package/dist/plugins/fusion-plugin-reports/src/dashboard-view.tsx +6 -0
  133. package/dist/plugins/fusion-plugin-reports/src/index.ts +48 -2
  134. package/dist/plugins/fusion-plugin-reports/src/pipeline.ts +58 -0
  135. package/dist/plugins/fusion-plugin-reports/src/render/__tests__/escape.test.ts +20 -0
  136. package/dist/plugins/fusion-plugin-reports/src/render/__tests__/html-template.test.ts +110 -0
  137. package/dist/plugins/fusion-plugin-reports/src/render/__tests__/standalone-html.test.ts +66 -0
  138. package/dist/plugins/fusion-plugin-reports/src/render/escape.ts +12 -0
  139. package/dist/plugins/fusion-plugin-reports/src/render/html-styles.ts +40 -0
  140. package/dist/plugins/fusion-plugin-reports/src/render/html-template.ts +137 -0
  141. package/dist/plugins/fusion-plugin-reports/src/render/index.ts +4 -0
  142. package/dist/plugins/fusion-plugin-reports/src/render/standalone-html.ts +75 -0
  143. package/dist/plugins/fusion-plugin-reports/src/report-schema.ts +31 -0
  144. package/dist/plugins/fusion-plugin-reports/src/routes/__tests__/report-export-routes.test.ts +104 -0
  145. package/dist/plugins/fusion-plugin-reports/src/routes/report-approval-routes.ts +98 -0
  146. package/dist/plugins/fusion-plugin-reports/src/routes/report-export-routes.ts +77 -0
  147. package/dist/plugins/fusion-plugin-reports/src/routes/report-list-routes.ts +72 -0
  148. package/dist/plugins/fusion-plugin-reports/src/runs-store.ts +69 -0
  149. package/dist/plugins/fusion-plugin-reports/src/share-blocks.ts +82 -0
  150. package/dist/plugins/fusion-plugin-reports/src/store/report-store.ts +51 -2
  151. package/dist/plugins/fusion-plugin-reports/src/store/report-types.ts +6 -1
  152. package/dist/plugins/fusion-plugin-roadmap/bundled.js +1528 -29391
  153. package/dist/plugins/fusion-plugin-roadmap/manifest.json +1 -1
  154. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  155. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  156. package/package.json +1 -1
  157. package/skill/fusion/SKILL.md +1 -1
  158. package/skill/fusion/references/engine-tools.md +2 -2
  159. package/skill/fusion/references/extension-tools.md +4 -3
  160. package/skill/fusion/references/fusion-capabilities.md +1 -1
  161. package/skill/fusion/workflows/task-management.md +3 -1
  162. package/dist/client/assets/AgentDetailView-BwJaLqZh.css +0 -1
  163. package/dist/client/assets/AgentDetailView-Cv-vgOj3.js +0 -18
  164. package/dist/client/assets/ChatView-CAHjY9uO.js +0 -1
  165. package/dist/client/assets/InsightsView-Q1zvtF4F.js +0 -11
  166. package/dist/client/assets/NodesView-RxXg58_Q.js +0 -14
  167. package/dist/client/assets/PluginManager-BEkyBajl.js +0 -1
  168. package/dist/client/assets/SettingsModal-BLsac7CJ.js +0 -31
  169. package/dist/client/assets/SettingsModal-BNSrO1M9.css +0 -1
  170. package/dist/client/assets/dashboard-view-4xAN3yO5.js +0 -21
  171. package/dist/client/assets/dashboard-view-BkTMSZYn.css +0 -1
  172. package/dist/client/assets/index-Bdw6llW6.js +0 -692
  173. package/dist/client/assets/index-CZGlyJuS.css +0 -1
  174. package/dist/plugins/fusion-plugin-roadmap/bundled.css +0 -1093
@@ -0,0 +1,692 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-shgiiUb4.js","assets/vendor-react-K0fH_qHe.js","assets/star-BDn04UYV.js","assets/ExperimentalAgentOnboardingModal-CkEiF85-.js","assets/ExperimentalAgentOnboardingModal-B-APN_lM.css","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/AgentDetailView-B7QRcHJH.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/TodoView-sS_mT0Y7.js","assets/TodoView-Cx9cVhq7.css","assets/SetupWizardModal-DuzYPbuJ.js","assets/DirectoryPicker-C0kmRv0u.js","assets/folder-open-B9cwJ-OX.js","assets/DirectoryPicker-DzKVmxOf.css","assets/projectDetection-G3XuxD2X.js","assets/SetupWizardModal-CGYGKurR.css","assets/SettingsModal-DL7tjJQa.js","assets/SettingsModal-Bg1-3JO_.js","assets/SettingsModal-Ci0_sqbU.css","assets/users-CPYZjK2g.js","assets/SettingsModal-DWKgRxBA.css","assets/dashboard-view-MB-86hAu.js","assets/createLucideIcon-BazL2hk5.js","assets/dashboard-view-BoTzlP8b.css","assets/dashboard-view-BWGH_fAq.js","assets/dashboard-view-DdGlfuu-.css","assets/AgentsView-CpwqOVDz.js","assets/upload-zdPPycKQ.js","assets/AgentsView-B3ADnF0D.css","assets/DocumentsView-B94U9ijs.js","assets/DocumentsView-gv4zG3aT.css","assets/InsightsView-D-Qe0tRr.js","assets/InsightsView-B0J4mhzV.css","assets/ResearchView-CjOxKhdS.js","assets/ResearchView-BEI4ZSGs.css","assets/EvalsView-O_4YWy--.js","assets/EvalsView-CUNJ1TLc.css","assets/NodesView-DQzXjcLc.js","assets/NodesView-DT4pXowv.css","assets/ChatView-DyRBOIKL.js","assets/ChatView-DwJAd5G1.css","assets/SkillsView-BIFoVNUf.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-CoRUmRvb.js","assets/MemoryView-zaXewZzi.css","assets/DevServerView-Cdelj9-m.js","assets/DevServerView-DlZpuAnj.css","assets/StashRecoveryView-C52KsV7f.js","assets/StashRecoveryView-B_8WIQEo.css"])))=>i.map(i=>d[i]);
2
+ import{r as i,j as t,R as Ol,a as Ra,g as Bg,c as dy}from"./vendor-react-K0fH_qHe.js";import"./vendor-xterm-DzcZoU0P.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))a(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&a(l)}).observe(document,{childList:!0,subtree:!0});function s(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function a(r){if(r.ep)return;r.ep=!0;const o=s(r);fetch(r.href,o)}})();/**
3
+ * @license lucide-react v1.7.0 - ISC
4
+ *
5
+ * This source code is licensed under the ISC license.
6
+ * See the LICENSE file in the root directory of this source tree.
7
+ */const Ug=(...e)=>e.filter((n,s,a)=>!!n&&n.trim()!==""&&a.indexOf(n)===s).join(" ").trim();/**
8
+ * @license lucide-react v1.7.0 - ISC
9
+ *
10
+ * This source code is licensed under the ISC license.
11
+ * See the LICENSE file in the root directory of this source tree.
12
+ */const uy=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
13
+ * @license lucide-react v1.7.0 - ISC
14
+ *
15
+ * This source code is licensed under the ISC license.
16
+ * See the LICENSE file in the root directory of this source tree.
17
+ */const my=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,s,a)=>a?a.toUpperCase():s.toLowerCase());/**
18
+ * @license lucide-react v1.7.0 - ISC
19
+ *
20
+ * This source code is licensed under the ISC license.
21
+ * See the LICENSE file in the root directory of this source tree.
22
+ */const Cm=e=>{const n=my(e);return n.charAt(0).toUpperCase()+n.slice(1)};/**
23
+ * @license lucide-react v1.7.0 - ISC
24
+ *
25
+ * This source code is licensed under the ISC license.
26
+ * See the LICENSE file in the root directory of this source tree.
27
+ */var Ic={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
28
+ * @license lucide-react v1.7.0 - ISC
29
+ *
30
+ * This source code is licensed under the ISC license.
31
+ * See the LICENSE file in the root directory of this source tree.
32
+ */const hy=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},py=i.createContext({}),fy=()=>i.useContext(py),gy=i.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:a,className:r="",children:o,iconNode:l,...c},d)=>{const{size:u=24,strokeWidth:m=2,absoluteStrokeWidth:h=!1,color:f="currentColor",className:p=""}=fy()??{},g=a??h?Number(s??m)*24/Number(n??u):s??m;return i.createElement("svg",{ref:d,...Ic,width:n??u??Ic.width,height:n??u??Ic.height,stroke:e??f,strokeWidth:g,className:Ug("lucide",p,r),...!o&&!hy(c)&&{"aria-hidden":"true"},...c},[...l.map(([x,w])=>i.createElement(x,w)),...Array.isArray(o)?o:[o]])});/**
33
+ * @license lucide-react v1.7.0 - ISC
34
+ *
35
+ * This source code is licensed under the ISC license.
36
+ * See the LICENSE file in the root directory of this source tree.
37
+ */const et=(e,n)=>{const s=i.forwardRef(({className:a,...r},o)=>i.createElement(gy,{ref:o,iconNode:n,className:Ug(`lucide-${uy(Cm(e))}`,`lucide-${e}`,a),...r}));return s.displayName=Cm(e),s};/**
38
+ * @license lucide-react v1.7.0 - ISC
39
+ *
40
+ * This source code is licensed under the ISC license.
41
+ * See the LICENSE file in the root directory of this source tree.
42
+ */const by=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],Ys=et("activity",by);/**
43
+ * @license lucide-react v1.7.0 - ISC
44
+ *
45
+ * This source code is licensed under the ISC license.
46
+ * See the LICENSE file in the root directory of this source tree.
47
+ */const xy=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]],vy=et("archive-restore",xy);/**
48
+ * @license lucide-react v1.7.0 - ISC
49
+ *
50
+ * This source code is licensed under the ISC license.
51
+ * See the LICENSE file in the root directory of this source tree.
52
+ */const yy=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],To=et("archive",yy);/**
53
+ * @license lucide-react v1.7.0 - ISC
54
+ *
55
+ * This source code is licensed under the ISC license.
56
+ * See the LICENSE file in the root directory of this source tree.
57
+ */const wy=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Po=et("arrow-down",wy);/**
58
+ * @license lucide-react v1.7.0 - ISC
59
+ *
60
+ * This source code is licensed under the ISC license.
61
+ * See the LICENSE file in the root directory of this source tree.
62
+ */const ky=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Ha=et("arrow-left",ky);/**
63
+ * @license lucide-react v1.7.0 - ISC
64
+ *
65
+ * This source code is licensed under the ISC license.
66
+ * See the LICENSE file in the root directory of this source tree.
67
+ */const jy=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],$o=et("arrow-right",jy);/**
68
+ * @license lucide-react v1.7.0 - ISC
69
+ *
70
+ * This source code is licensed under the ISC license.
71
+ * See the LICENSE file in the root directory of this source tree.
72
+ */const Ny=[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]],Hg=et("arrow-up-down",Ny);/**
73
+ * @license lucide-react v1.7.0 - ISC
74
+ *
75
+ * This source code is licensed under the ISC license.
76
+ * See the LICENSE file in the root directory of this source tree.
77
+ */const Sy=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Ta=et("arrow-up",Sy);/**
78
+ * @license lucide-react v1.7.0 - ISC
79
+ *
80
+ * This source code is licensed under the ISC license.
81
+ * See the LICENSE file in the root directory of this source tree.
82
+ */const Cy=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],Ey=et("book-open",Cy);/**
83
+ * @license lucide-react v1.7.0 - ISC
84
+ *
85
+ * This source code is licensed under the ISC license.
86
+ * See the LICENSE file in the root directory of this source tree.
87
+ */const _y=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],Kn=et("bot",_y);/**
88
+ * @license lucide-react v1.7.0 - ISC
89
+ *
90
+ * This source code is licensed under the ISC license.
91
+ * See the LICENSE file in the root directory of this source tree.
92
+ */const My=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],Gd=et("box",My);/**
93
+ * @license lucide-react v1.7.0 - ISC
94
+ *
95
+ * This source code is licensed under the ISC license.
96
+ * See the LICENSE file in the root directory of this source tree.
97
+ */const Ay=[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]],So=et("brain",Ay);/**
98
+ * @license lucide-react v1.7.0 - ISC
99
+ *
100
+ * This source code is licensed under the ISC license.
101
+ * See the LICENSE file in the root directory of this source tree.
102
+ */const Ry=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],qg=et("calendar",Ry);/**
103
+ * @license lucide-react v1.7.0 - ISC
104
+ *
105
+ * This source code is licensed under the ISC license.
106
+ * See the LICENSE file in the root directory of this source tree.
107
+ */const Iy=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Em=et("check-check",Iy);/**
108
+ * @license lucide-react v1.7.0 - ISC
109
+ *
110
+ * This source code is licensed under the ISC license.
111
+ * See the LICENSE file in the root directory of this source tree.
112
+ */const Ty=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],js=et("check",Ty);/**
113
+ * @license lucide-react v1.7.0 - ISC
114
+ *
115
+ * This source code is licensed under the ISC license.
116
+ * See the LICENSE file in the root directory of this source tree.
117
+ */const Py=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],pn=et("chevron-down",Py);/**
118
+ * @license lucide-react v1.7.0 - ISC
119
+ *
120
+ * This source code is licensed under the ISC license.
121
+ * See the LICENSE file in the root directory of this source tree.
122
+ */const $y=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],lc=et("chevron-left",$y);/**
123
+ * @license lucide-react v1.7.0 - ISC
124
+ *
125
+ * This source code is licensed under the ISC license.
126
+ * See the LICENSE file in the root directory of this source tree.
127
+ */const Dy=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],On=et("chevron-right",Dy);/**
128
+ * @license lucide-react v1.7.0 - ISC
129
+ *
130
+ * This source code is licensed under the ISC license.
131
+ * See the LICENSE file in the root directory of this source tree.
132
+ */const Ly=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Pi=et("chevron-up",Ly);/**
133
+ * @license lucide-react v1.7.0 - ISC
134
+ *
135
+ * This source code is licensed under the ISC license.
136
+ * See the LICENSE file in the root directory of this source tree.
137
+ */const Oy=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],Ws=et("circle-alert",Oy);/**
138
+ * @license lucide-react v1.7.0 - ISC
139
+ *
140
+ * This source code is licensed under the ISC license.
141
+ * See the LICENSE file in the root directory of this source tree.
142
+ */const Fy=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Gn=et("circle-check-big",Fy);/**
143
+ * @license lucide-react v1.7.0 - ISC
144
+ *
145
+ * This source code is licensed under the ISC license.
146
+ * See the LICENSE file in the root directory of this source tree.
147
+ */const zy=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],cc=et("circle-dot",zy);/**
148
+ * @license lucide-react v1.7.0 - ISC
149
+ *
150
+ * This source code is licensed under the ISC license.
151
+ * See the LICENSE file in the root directory of this source tree.
152
+ */const By=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Jd=et("circle-question-mark",By);/**
153
+ * @license lucide-react v1.7.0 - ISC
154
+ *
155
+ * This source code is licensed under the ISC license.
156
+ * See the LICENSE file in the root directory of this source tree.
157
+ */const Uy=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],Hy=et("circle-stop",Uy);/**
158
+ * @license lucide-react v1.7.0 - ISC
159
+ *
160
+ * This source code is licensed under the ISC license.
161
+ * See the LICENSE file in the root directory of this source tree.
162
+ */const qy=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],Do=et("circle-x",qy);/**
163
+ * @license lucide-react v1.7.0 - ISC
164
+ *
165
+ * This source code is licensed under the ISC license.
166
+ * See the LICENSE file in the root directory of this source tree.
167
+ */const Vy=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]],Wy=et("clipboard-list",Vy);/**
168
+ * @license lucide-react v1.7.0 - ISC
169
+ *
170
+ * This source code is licensed under the ISC license.
171
+ * See the LICENSE file in the root directory of this source tree.
172
+ */const Ky=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Ji=et("clock",Ky);/**
173
+ * @license lucide-react v1.7.0 - ISC
174
+ *
175
+ * This source code is licensed under the ISC license.
176
+ * See the LICENSE file in the root directory of this source tree.
177
+ */const Gy=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Vg=et("code",Gy);/**
178
+ * @license lucide-react v1.7.0 - ISC
179
+ *
180
+ * This source code is licensed under the ISC license.
181
+ * See the LICENSE file in the root directory of this source tree.
182
+ */const Jy=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]],_m=et("columns-3",Jy);/**
183
+ * @license lucide-react v1.7.0 - ISC
184
+ *
185
+ * This source code is licensed under the ISC license.
186
+ * See the LICENSE file in the root directory of this source tree.
187
+ */const Yy=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],da=et("copy",Yy);/**
188
+ * @license lucide-react v1.7.0 - ISC
189
+ *
190
+ * This source code is licensed under the ISC license.
191
+ * See the LICENSE file in the root directory of this source tree.
192
+ */const Qy=[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]],Wg=et("cpu",Qy);/**
193
+ * @license lucide-react v1.7.0 - ISC
194
+ *
195
+ * This source code is licensed under the ISC license.
196
+ * See the LICENSE file in the root directory of this source tree.
197
+ */const Xy=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],Zy=et("download",Xy);/**
198
+ * @license lucide-react v1.7.0 - ISC
199
+ *
200
+ * This source code is licensed under the ISC license.
201
+ * See the LICENSE file in the root directory of this source tree.
202
+ */const ew=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],tw=et("ellipsis-vertical",ew);/**
203
+ * @license lucide-react v1.7.0 - ISC
204
+ *
205
+ * This source code is licensed under the ISC license.
206
+ * See the LICENSE file in the root directory of this source tree.
207
+ */const nw=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],Yd=et("ellipsis",nw);/**
208
+ * @license lucide-react v1.7.0 - ISC
209
+ *
210
+ * This source code is licensed under the ISC license.
211
+ * See the LICENSE file in the root directory of this source tree.
212
+ */const sw=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Kg=et("external-link",sw);/**
213
+ * @license lucide-react v1.7.0 - ISC
214
+ *
215
+ * This source code is licensed under the ISC license.
216
+ * See the LICENSE file in the root directory of this source tree.
217
+ */const iw=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],Pu=et("eye-off",iw);/**
218
+ * @license lucide-react v1.7.0 - ISC
219
+ *
220
+ * This source code is licensed under the ISC license.
221
+ * See the LICENSE file in the root directory of this source tree.
222
+ */const aw=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Tr=et("eye",aw);/**
223
+ * @license lucide-react v1.7.0 - ISC
224
+ *
225
+ * This source code is licensed under the ISC license.
226
+ * See the LICENSE file in the root directory of this source tree.
227
+ */const rw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],xi=et("file-code",rw);/**
228
+ * @license lucide-react v1.7.0 - ISC
229
+ *
230
+ * This source code is licensed under the ISC license.
231
+ * See the LICENSE file in the root directory of this source tree.
232
+ */const ow=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M9 17h6",key:"r8uit2"}]],Qd=et("file-diff",ow);/**
233
+ * @license lucide-react v1.7.0 - ISC
234
+ *
235
+ * This source code is licensed under the ISC license.
236
+ * See the LICENSE file in the root directory of this source tree.
237
+ */const lw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}]],cw=et("file-minus",lw);/**
238
+ * @license lucide-react v1.7.0 - ISC
239
+ *
240
+ * This source code is licensed under the ISC license.
241
+ * See the LICENSE file in the root directory of this source tree.
242
+ */const dw=[["path",{d:"M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34",key:"o6klzx"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z",key:"zhnas1"}]],Gg=et("file-pen",dw);/**
243
+ * @license lucide-react v1.7.0 - ISC
244
+ *
245
+ * This source code is licensed under the ISC license.
246
+ * See the LICENSE file in the root directory of this source tree.
247
+ */const uw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],mw=et("file-plus",uw);/**
248
+ * @license lucide-react v1.7.0 - ISC
249
+ *
250
+ * This source code is licensed under the ISC license.
251
+ * See the LICENSE file in the root directory of this source tree.
252
+ */const hw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],pw=et("file-question-mark",hw);/**
253
+ * @license lucide-react v1.7.0 - ISC
254
+ *
255
+ * This source code is licensed under the ISC license.
256
+ * See the LICENSE file in the root directory of this source tree.
257
+ */const fw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],ua=et("file-text",fw);/**
258
+ * @license lucide-react v1.7.0 - ISC
259
+ *
260
+ * This source code is licensed under the ISC license.
261
+ * See the LICENSE file in the root directory of this source tree.
262
+ */const gw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M11 18h2",key:"12mj7e"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M9 13v-.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 .5.5v.5",key:"qbrxap"}]],bw=et("file-type",gw);/**
263
+ * @license lucide-react v1.7.0 - ISC
264
+ *
265
+ * This source code is licensed under the ISC license.
266
+ * See the LICENSE file in the root directory of this source tree.
267
+ */const xw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],Jg=et("file",xw);/**
268
+ * @license lucide-react v1.7.0 - ISC
269
+ *
270
+ * This source code is licensed under the ISC license.
271
+ * See the LICENSE file in the root directory of this source tree.
272
+ */const vw=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],yw=et("flag",vw);/**
273
+ * @license lucide-react v1.7.0 - ISC
274
+ *
275
+ * This source code is licensed under the ISC license.
276
+ * See the LICENSE file in the root directory of this source tree.
277
+ */const ww=[["path",{d:"M18 19a5 5 0 0 1-5-5v8",key:"sz5oeg"}],["path",{d:"M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v5",key:"1w6njk"}],["circle",{cx:"13",cy:"12",r:"2",key:"1j92g6"}],["circle",{cx:"20",cy:"19",r:"2",key:"1obnsp"}]],Xd=et("folder-git-2",ww);/**
278
+ * @license lucide-react v1.7.0 - ISC
279
+ *
280
+ * This source code is licensed under the ISC license.
281
+ * See the LICENSE file in the root directory of this source tree.
282
+ */const kw=[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}],["path",{d:"M12 15v5",key:"11xva1"}]],Mm=et("folder-root",kw);/**
283
+ * @license lucide-react v1.7.0 - ISC
284
+ *
285
+ * This source code is licensed under the ISC license.
286
+ * See the LICENSE file in the root directory of this source tree.
287
+ */const jw=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],Es=et("folder",jw);/**
288
+ * @license lucide-react v1.7.0 - ISC
289
+ *
290
+ * This source code is licensed under the ISC license.
291
+ * See the LICENSE file in the root directory of this source tree.
292
+ */const Nw=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],Fl=et("funnel",Nw);/**
293
+ * @license lucide-react v1.7.0 - ISC
294
+ *
295
+ * This source code is licensed under the ISC license.
296
+ * See the LICENSE file in the root directory of this source tree.
297
+ */const Sw=[["path",{d:"M15 6a9 9 0 0 0-9 9V3",key:"1cii5b"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}]],Fs=et("git-branch",Sw);/**
298
+ * @license lucide-react v1.7.0 - ISC
299
+ *
300
+ * This source code is licensed under the ISC license.
301
+ * See the LICENSE file in the root directory of this source tree.
302
+ */const Cw=[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]],xr=et("git-commit-horizontal",Cw);/**
303
+ * @license lucide-react v1.7.0 - ISC
304
+ *
305
+ * This source code is licensed under the ISC license.
306
+ * See the LICENSE file in the root directory of this source tree.
307
+ */const Ew=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 21V9a9 9 0 0 0 9 9",key:"7kw0sc"}]],Yg=et("git-merge",Ew);/**
308
+ * @license lucide-react v1.7.0 - ISC
309
+ *
310
+ * This source code is licensed under the ISC license.
311
+ * See the LICENSE file in the root directory of this source tree.
312
+ */const _w=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]],si=et("git-pull-request",_w);/**
313
+ * @license lucide-react v1.7.0 - ISC
314
+ *
315
+ * This source code is licensed under the ISC license.
316
+ * See the LICENSE file in the root directory of this source tree.
317
+ */const Mw=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],dc=et("globe",Mw);/**
318
+ * @license lucide-react v1.7.0 - ISC
319
+ *
320
+ * This source code is licensed under the ISC license.
321
+ * See the LICENSE file in the root directory of this source tree.
322
+ */const Aw=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]],uc=et("grid-3x3",Aw);/**
323
+ * @license lucide-react v1.7.0 - ISC
324
+ *
325
+ * This source code is licensed under the ISC license.
326
+ * See the LICENSE file in the root directory of this source tree.
327
+ */const Rw=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],mc=et("grip-vertical",Rw);/**
328
+ * @license lucide-react v1.7.0 - ISC
329
+ *
330
+ * This source code is licensed under the ISC license.
331
+ * See the LICENSE file in the root directory of this source tree.
332
+ */const Iw=[["path",{d:"M10 16h.01",key:"1bzywj"}],["path",{d:"M2.212 11.577a2 2 0 0 0-.212.896V18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5.527a2 2 0 0 0-.212-.896L18.55 5.11A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"18tbho"}],["path",{d:"M21.946 12.013H2.054",key:"zqlbp7"}],["path",{d:"M6 16h.01",key:"1pmjb7"}]],Tw=et("hard-drive",Iw);/**
333
+ * @license lucide-react v1.7.0 - ISC
334
+ *
335
+ * This source code is licensed under the ISC license.
336
+ * See the LICENSE file in the root directory of this source tree.
337
+ */const Pw=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],$w=et("heart",Pw);/**
338
+ * @license lucide-react v1.7.0 - ISC
339
+ *
340
+ * This source code is licensed under the ISC license.
341
+ * See the LICENSE file in the root directory of this source tree.
342
+ */const Dw=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],Pa=et("history",Dw);/**
343
+ * @license lucide-react v1.7.0 - ISC
344
+ *
345
+ * This source code is licensed under the ISC license.
346
+ * See the LICENSE file in the root directory of this source tree.
347
+ */const Lw=[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]],ra=et("inbox",Lw);/**
348
+ * @license lucide-react v1.7.0 - ISC
349
+ *
350
+ * This source code is licensed under the ISC license.
351
+ * See the LICENSE file in the root directory of this source tree.
352
+ */const Ow=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],Qg=et("key",Ow);/**
353
+ * @license lucide-react v1.7.0 - ISC
354
+ *
355
+ * This source code is licensed under the ISC license.
356
+ * See the LICENSE file in the root directory of this source tree.
357
+ */const Fw=[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]],zw=et("keyboard",Fw);/**
358
+ * @license lucide-react v1.7.0 - ISC
359
+ *
360
+ * This source code is licensed under the ISC license.
361
+ * See the LICENSE file in the root directory of this source tree.
362
+ */const Bw=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],$a=et("layers",Bw);/**
363
+ * @license lucide-react v1.7.0 - ISC
364
+ *
365
+ * This source code is licensed under the ISC license.
366
+ * See the LICENSE file in the root directory of this source tree.
367
+ */const Uw=[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]],ma=et("layout-grid",Uw);/**
368
+ * @license lucide-react v1.7.0 - ISC
369
+ *
370
+ * This source code is licensed under the ISC license.
371
+ * See the LICENSE file in the root directory of this source tree.
372
+ */const Hw=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],$i=et("lightbulb",Hw);/**
373
+ * @license lucide-react v1.7.0 - ISC
374
+ *
375
+ * This source code is licensed under the ISC license.
376
+ * See the LICENSE file in the root directory of this source tree.
377
+ */const qw=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],vr=et("link",qw);/**
378
+ * @license lucide-react v1.7.0 - ISC
379
+ *
380
+ * This source code is licensed under the ISC license.
381
+ * See the LICENSE file in the root directory of this source tree.
382
+ */const Vw=[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}]],Ww=et("list-checks",Vw);/**
383
+ * @license lucide-react v1.7.0 - ISC
384
+ *
385
+ * This source code is licensed under the ISC license.
386
+ * See the LICENSE file in the root directory of this source tree.
387
+ */const Kw=[["path",{d:"M11 5h10",key:"1cz7ny"}],["path",{d:"M11 12h10",key:"1438ji"}],["path",{d:"M11 19h10",key:"11t30w"}],["path",{d:"M4 4h1v5",key:"10yrso"}],["path",{d:"M4 9h2",key:"r1h2o0"}],["path",{d:"M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02",key:"xtkcd5"}]],Gw=et("list-ordered",Kw);/**
388
+ * @license lucide-react v1.7.0 - ISC
389
+ *
390
+ * This source code is licensed under the ISC license.
391
+ * See the LICENSE file in the root directory of this source tree.
392
+ */const Jw=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],Yw=et("list-plus",Jw);/**
393
+ * @license lucide-react v1.7.0 - ISC
394
+ *
395
+ * This source code is licensed under the ISC license.
396
+ * See the LICENSE file in the root directory of this source tree.
397
+ */const Qw=[["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"M3 10a2 2 0 0 0 2 2h3",key:"1npucw"}],["path",{d:"M3 5v12a2 2 0 0 0 2 2h3",key:"x1gjn2"}]],hc=et("list-tree",Qw);/**
398
+ * @license lucide-react v1.7.0 - ISC
399
+ *
400
+ * This source code is licensed under the ISC license.
401
+ * See the LICENSE file in the root directory of this source tree.
402
+ */const Xw=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],Zd=et("list",Xw);/**
403
+ * @license lucide-react v1.7.0 - ISC
404
+ *
405
+ * This source code is licensed under the ISC license.
406
+ * See the LICENSE file in the root directory of this source tree.
407
+ */const Zw=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],jt=et("loader-circle",Zw);/**
408
+ * @license lucide-react v1.7.0 - ISC
409
+ *
410
+ * This source code is licensed under the ISC license.
411
+ * See the LICENSE file in the root directory of this source tree.
412
+ */const ek=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],pc=et("lock",ek);/**
413
+ * @license lucide-react v1.7.0 - ISC
414
+ *
415
+ * This source code is licensed under the ISC license.
416
+ * See the LICENSE file in the root directory of this source tree.
417
+ */const tk=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],Da=et("mail",tk);/**
418
+ * @license lucide-react v1.7.0 - ISC
419
+ *
420
+ * This source code is licensed under the ISC license.
421
+ * See the LICENSE file in the root directory of this source tree.
422
+ */const nk=[["path",{d:"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z",key:"169xi5"}],["path",{d:"M15 5.764v15",key:"1pn4in"}],["path",{d:"M9 3.236v15",key:"1uimfh"}]],sk=et("map",nk);/**
423
+ * @license lucide-react v1.7.0 - ISC
424
+ *
425
+ * This source code is licensed under the ISC license.
426
+ * See the LICENSE file in the root directory of this source tree.
427
+ */const ik=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],fc=et("maximize-2",ik);/**
428
+ * @license lucide-react v1.7.0 - ISC
429
+ *
430
+ * This source code is licensed under the ISC license.
431
+ * See the LICENSE file in the root directory of this source tree.
432
+ */const ak=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],rk=et("message-square-plus",ak);/**
433
+ * @license lucide-react v1.7.0 - ISC
434
+ *
435
+ * This source code is licensed under the ISC license.
436
+ * See the LICENSE file in the root directory of this source tree.
437
+ */const ok=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],Ki=et("message-square",ok);/**
438
+ * @license lucide-react v1.7.0 - ISC
439
+ *
440
+ * This source code is licensed under the ISC license.
441
+ * See the LICENSE file in the root directory of this source tree.
442
+ */const lk=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],Lo=et("minimize-2",lk);/**
443
+ * @license lucide-react v1.7.0 - ISC
444
+ *
445
+ * This source code is licensed under the ISC license.
446
+ * See the LICENSE file in the root directory of this source tree.
447
+ */const ck=[["path",{d:"M5 12h14",key:"1ays0h"}]],dk=et("minus",ck);/**
448
+ * @license lucide-react v1.7.0 - ISC
449
+ *
450
+ * This source code is licensed under the ISC license.
451
+ * See the LICENSE file in the root directory of this source tree.
452
+ */const uk=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],yr=et("monitor",uk);/**
453
+ * @license lucide-react v1.7.0 - ISC
454
+ *
455
+ * This source code is licensed under the ISC license.
456
+ * See the LICENSE file in the root directory of this source tree.
457
+ */const mk=[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]],hk=et("move",mk);/**
458
+ * @license lucide-react v1.7.0 - ISC
459
+ *
460
+ * This source code is licensed under the ISC license.
461
+ * See the LICENSE file in the root directory of this source tree.
462
+ */const pk=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],fk=et("network",pk);/**
463
+ * @license lucide-react v1.7.0 - ISC
464
+ *
465
+ * This source code is licensed under the ISC license.
466
+ * See the LICENSE file in the root directory of this source tree.
467
+ */const gk=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],eu=et("package",gk);/**
468
+ * @license lucide-react v1.7.0 - ISC
469
+ *
470
+ * This source code is licensed under the ISC license.
471
+ * See the LICENSE file in the root directory of this source tree.
472
+ */const bk=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],Xg=et("paperclip",bk);/**
473
+ * @license lucide-react v1.7.0 - ISC
474
+ *
475
+ * This source code is licensed under the ISC license.
476
+ * See the LICENSE file in the root directory of this source tree.
477
+ */const xk=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],vi=et("pause",xk);/**
478
+ * @license lucide-react v1.7.0 - ISC
479
+ *
480
+ * This source code is licensed under the ISC license.
481
+ * See the LICENSE file in the root directory of this source tree.
482
+ */const vk=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],qs=et("pencil",vk);/**
483
+ * @license lucide-react v1.7.0 - ISC
484
+ *
485
+ * This source code is licensed under the ISC license.
486
+ * See the LICENSE file in the root directory of this source tree.
487
+ */const yk=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],is=et("play",yk);/**
488
+ * @license lucide-react v1.7.0 - ISC
489
+ *
490
+ * This source code is licensed under the ISC license.
491
+ * See the LICENSE file in the root directory of this source tree.
492
+ */const wk=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Mn=et("plus",wk);/**
493
+ * @license lucide-react v1.7.0 - ISC
494
+ *
495
+ * This source code is licensed under the ISC license.
496
+ * See the LICENSE file in the root directory of this source tree.
497
+ */const kk=[["path",{d:"M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z",key:"w46dr5"}]],jk=et("puzzle",kk);/**
498
+ * @license lucide-react v1.7.0 - ISC
499
+ *
500
+ * This source code is licensed under the ISC license.
501
+ * See the LICENSE file in the root directory of this source tree.
502
+ */const Nk=[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],Zg=et("radio",Nk);/**
503
+ * @license lucide-react v1.7.0 - ISC
504
+ *
505
+ * This source code is licensed under the ISC license.
506
+ * See the LICENSE file in the root directory of this source tree.
507
+ */const Sk=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],bs=et("refresh-cw",Sk);/**
508
+ * @license lucide-react v1.7.0 - ISC
509
+ *
510
+ * This source code is licensed under the ISC license.
511
+ * See the LICENSE file in the root directory of this source tree.
512
+ */const Ck=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],Am=et("rocket",Ck);/**
513
+ * @license lucide-react v1.7.0 - ISC
514
+ *
515
+ * This source code is licensed under the ISC license.
516
+ * See the LICENSE file in the root directory of this source tree.
517
+ */const Ek=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],_k=et("rotate-ccw",Ek);/**
518
+ * @license lucide-react v1.7.0 - ISC
519
+ *
520
+ * This source code is licensed under the ISC license.
521
+ * See the LICENSE file in the root directory of this source tree.
522
+ */const Mk=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],Ak=et("rotate-cw",Mk);/**
523
+ * @license lucide-react v1.7.0 - ISC
524
+ *
525
+ * This source code is licensed under the ISC license.
526
+ * See the LICENSE file in the root directory of this source tree.
527
+ */const Rk=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],eb=et("save",Rk);/**
528
+ * @license lucide-react v1.7.0 - ISC
529
+ *
530
+ * This source code is licensed under the ISC license.
531
+ * See the LICENSE file in the root directory of this source tree.
532
+ */const Ik=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Wi=et("search",Ik);/**
533
+ * @license lucide-react v1.7.0 - ISC
534
+ *
535
+ * This source code is licensed under the ISC license.
536
+ * See the LICENSE file in the root directory of this source tree.
537
+ */const Tk=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],Ia=et("send",Tk);/**
538
+ * @license lucide-react v1.7.0 - ISC
539
+ *
540
+ * This source code is licensed under the ISC license.
541
+ * See the LICENSE file in the root directory of this source tree.
542
+ */const Pk=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],Co=et("server",Pk);/**
543
+ * @license lucide-react v1.7.0 - ISC
544
+ *
545
+ * This source code is licensed under the ISC license.
546
+ * See the LICENSE file in the root directory of this source tree.
547
+ */const $k=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],vo=et("settings",$k);/**
548
+ * @license lucide-react v1.7.0 - ISC
549
+ *
550
+ * This source code is licensed under the ISC license.
551
+ * See the LICENSE file in the root directory of this source tree.
552
+ */const Dk=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]],Lk=et("shield-alert",Dk);/**
553
+ * @license lucide-react v1.7.0 - ISC
554
+ *
555
+ * This source code is licensed under the ISC license.
556
+ * See the LICENSE file in the root directory of this source tree.
557
+ */const Ok=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],Fk=et("shield",Ok);/**
558
+ * @license lucide-react v1.7.0 - ISC
559
+ *
560
+ * This source code is licensed under the ISC license.
561
+ * See the LICENSE file in the root directory of this source tree.
562
+ */const zk=[["path",{d:"m12.5 17-.5-1-.5 1h1z",key:"3me087"}],["path",{d:"M15 22a1 1 0 0 0 1-1v-1a2 2 0 0 0 1.56-3.25 8 8 0 1 0-11.12 0A2 2 0 0 0 8 20v1a1 1 0 0 0 1 1z",key:"1o5pge"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}]],Bk=et("skull",zk);/**
563
+ * @license lucide-react v1.7.0 - ISC
564
+ *
565
+ * This source code is licensed under the ISC license.
566
+ * See the LICENSE file in the root directory of this source tree.
567
+ */const Uk=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],gs=et("sparkles",Uk);/**
568
+ * @license lucide-react v1.7.0 - ISC
569
+ *
570
+ * This source code is licensed under the ISC license.
571
+ * See the LICENSE file in the root directory of this source tree.
572
+ */const Hk=[["path",{d:"M21 10.656V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.344",key:"2acyp4"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],$u=et("square-check-big",Hk);/**
573
+ * @license lucide-react v1.7.0 - ISC
574
+ *
575
+ * This source code is licensed under the ISC license.
576
+ * See the LICENSE file in the root directory of this source tree.
577
+ */const qk=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Ii=et("square",qk);/**
578
+ * @license lucide-react v1.7.0 - ISC
579
+ *
580
+ * This source code is licensed under the ISC license.
581
+ * See the LICENSE file in the root directory of this source tree.
582
+ */const Vk=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],Rs=et("target",Vk);/**
583
+ * @license lucide-react v1.7.0 - ISC
584
+ *
585
+ * This source code is licensed under the ISC license.
586
+ * See the LICENSE file in the root directory of this source tree.
587
+ */const Wk=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Gi=et("terminal",Wk);/**
588
+ * @license lucide-react v1.7.0 - ISC
589
+ *
590
+ * This source code is licensed under the ISC license.
591
+ * See the LICENSE file in the root directory of this source tree.
592
+ */const Kk=[["path",{d:"m16 16-3 3 3 3",key:"117b85"}],["path",{d:"M3 12h14.5a1 1 0 0 1 0 7H13",key:"18xa6z"}],["path",{d:"M3 19h6",key:"1ygdsz"}],["path",{d:"M3 5h18",key:"1u36vt"}]],zl=et("text-wrap",Kk);/**
593
+ * @license lucide-react v1.7.0 - ISC
594
+ *
595
+ * This source code is licensed under the ISC license.
596
+ * See the LICENSE file in the root directory of this source tree.
597
+ */const Gk=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],_n=et("trash-2",Gk);/**
598
+ * @license lucide-react v1.7.0 - ISC
599
+ *
600
+ * This source code is licensed under the ISC license.
601
+ * See the LICENSE file in the root directory of this source tree.
602
+ */const Jk=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Yk=et("trending-up",Jk);/**
603
+ * @license lucide-react v1.7.0 - ISC
604
+ *
605
+ * This source code is licensed under the ISC license.
606
+ * See the LICENSE file in the root directory of this source tree.
607
+ */const Qk=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Oo=et("triangle-alert",Qk);/**
608
+ * @license lucide-react v1.7.0 - ISC
609
+ *
610
+ * This source code is licensed under the ISC license.
611
+ * See the LICENSE file in the root directory of this source tree.
612
+ */const Xk=[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]],Rm=et("unlink",Xk);/**
613
+ * @license lucide-react v1.7.0 - ISC
614
+ *
615
+ * This source code is licensed under the ISC license.
616
+ * See the LICENSE file in the root directory of this source tree.
617
+ */const Zk=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],Ea=et("user",Zk);/**
618
+ * @license lucide-react v1.7.0 - ISC
619
+ *
620
+ * This source code is licensed under the ISC license.
621
+ * See the LICENSE file in the root directory of this source tree.
622
+ */const ej=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],tb=et("webhook",ej);/**
623
+ * @license lucide-react v1.7.0 - ISC
624
+ *
625
+ * This source code is licensed under the ISC license.
626
+ * See the LICENSE file in the root directory of this source tree.
627
+ */const tj=[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]],Bl=et("workflow",tj);/**
628
+ * @license lucide-react v1.7.0 - ISC
629
+ *
630
+ * This source code is licensed under the ISC license.
631
+ * See the LICENSE file in the root directory of this source tree.
632
+ */const nj=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],Im=et("wrench",nj);/**
633
+ * @license lucide-react v1.7.0 - ISC
634
+ *
635
+ * This source code is licensed under the ISC license.
636
+ * See the LICENSE file in the root directory of this source tree.
637
+ */const sj=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],un=et("x",sj);/**
638
+ * @license lucide-react v1.7.0 - ISC
639
+ *
640
+ * This source code is licensed under the ISC license.
641
+ * See the LICENSE file in the root directory of this source tree.
642
+ */const ij=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],as=et("zap",ij),tu="fusion:version-reload",nu="fusion:version-update";let Du=!0;function Tc(e){Du=e}function aj(){try{if(sessionStorage.getItem(nu))return sessionStorage.removeItem(nu),!0}catch{}return!1}function Lu(e){if(sessionStorage.getItem(tu)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(tu,"1"),!Du){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function rj(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|is not a valid JavaScript MIME type|ChunkLoadError|Unable to preload (?:CSS|module) for/i.test(n)}function oj(e){return rj(e)?(Lu(`chunk load error: ${e?.message??e}`),!0):!1}async function lj(){try{const e=await fetch("/version.json",{cache:"no-store",headers:{Accept:"application/json"}});if(!e.ok||!(e.headers.get("content-type")??"").includes("application/json"))return null;const s=await e.json();return typeof s.version=="string"?s.version:null}catch{return null}}async function cj(){try{const e=new AbortController,n=setTimeout(()=>e.abort(),3e3),s=await fetch("/api/settings",{headers:{Accept:"application/json"},signal:e.signal});clearTimeout(n),s.ok&&(await s.json()).autoReloadOnVersionChange===!1&&(Du=!1)}catch{}}const dj=6e4;let Tm=0,Pc=!1;async function $c(){if(!(Pc||document.visibilityState!=="visible")&&!(Date.now()-Tm<dj)){Tm=Date.now(),Pc=!0;try{const e=await lj();if(e&&e!=="3ac619df2-32358675"){try{sessionStorage.setItem(nu,"1")}catch{}Lu(`build version changed: 3ac619df2-32358675 -> ${e}`)}}finally{Pc=!1}}}function uj(){cj(),window.setTimeout(()=>sessionStorage.removeItem(tu),5e3),document.addEventListener("visibilitychange",()=>{$c()}),window.addEventListener("focus",()=>{$c()}),window.setTimeout(()=>void $c(),2e3)}class Fo extends i.Component{constructor(n){super(n),this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,s){console.error("[ErrorBoundary]",n,s),!oj(n)&&this.props.onError?.(n,s)}resetErrorBoundary=()=>{this.setState({hasError:!1,error:null})};render(){if(!this.state.hasError)return this.props.children;if(this.props.fallback)return this.props.fallback;const n=this.props.level??"page",a=n==="modal"?"This section encountered an error":"Something went wrong";return t.jsxs("div",{className:`error-boundary error-boundary--${n}`,children:[t.jsx("div",{className:"error-boundary__icon",children:t.jsx(Oo,{size:40})}),t.jsx("div",{className:"error-boundary__title",children:a}),this.state.error&&t.jsx("pre",{className:"error-boundary__message",children:this.state.error.message}),t.jsxs("div",{className:"error-boundary__actions",children:[t.jsx("button",{className:"btn btn-primary",onClick:this.resetErrorBoundary,children:"Retry"}),t.jsx("button",{className:"btn",onClick:()=>window.location.reload(),children:"Reload page"})]})]})}}function $s({children:e,onError:n}){return t.jsx(Fo,{level:"page",onError:n,children:e})}function _a({children:e,onError:n}){return t.jsx(Fo,{level:"modal",onError:n,children:e})}function mj({children:e,onError:n}){return t.jsx(Fo,{level:"root",onError:n,children:e})}const hj="modulepreload",pj=function(e){return"/"+e},Pm={},Sn=function(n,s,a){let r=Promise.resolve();if(s&&s.length>0){let l=function(u){return Promise.all(u.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=c?.nonce||c?.getAttribute("nonce");r=l(s.map(u=>{if(u=pj(u),u in Pm)return;Pm[u]=!0;const m=u.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":hj,m||(f.as="script"),f.crossOrigin="",f.href=u,d&&f.setAttribute("nonce",d),document.head.appendChild(f),m)return new Promise((p,g)=>{f.addEventListener("load",p),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return n().catch(o)})},Ou="fn.authToken",$m="token",fj="fn_token";let hr,Dm=!1,Ul=!1;const su="fn:auth-token-recovery-required";function gj(){try{const e=window.localStorage.getItem(Ou);return e&&e.length>0?e:void 0}catch{return}}function nb(e){try{window.localStorage.setItem(Ou,e)}catch{}}function bj(){if(!(Dm||typeof window>"u")){Dm=!0;try{const e=new URL(window.location.href),n=e.searchParams.get($m);if(!n)return;nb(n),e.searchParams.delete($m);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function wr(){if(hr!==void 0)return hr;const e=bj();if(e)return hr=e,e;const n=gj();if(n)return hr=n,n}function xj(e){hr=e,Ul=!1,nb(e)}function vj(){hr=void 0,Ul=!1;try{window.localStorage.removeItem(Ou)}catch{}}function Lm(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function yj(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function wj(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!yj(e.protocol))return!1;const s=e.hostname===n.hostname,a=e.port===n.port,r=Lm(e.protocol)===Lm(n.protocol);return s&&a&&r}function kj(e){if(!(typeof window>"u"))try{const n=new URL(e,window.location.origin),s=e.startsWith("/");return{parsed:n,preserveRelativePath:s}}catch{return}}function Di(e){const n=wr();if(!n||typeof window>"u")return e;const s=kj(e);return!s||!wj(s.parsed)?e:(s.parsed.searchParams.set(fj,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function wi(e){const n=wr();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function jj(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Nj(){typeof window>"u"||Ul||(Ul=!0,window.dispatchEvent(new CustomEvent(su)))}async function Sj(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const a=await n.json();jj(a)&&Nj()}catch{}}function Cj(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,wr();const e=window.fetch.bind(window);window.fetch=function(s,a){const r=wr(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const d=new URL(o,window.location.origin);return d.origin!==window.location.origin?!1:d.pathname.startsWith("/api/")||d.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,a);const c=new Headers(a?.headers??(s instanceof Request?s.headers:void 0));return r&&!c.has("Authorization")&&c.set("Authorization",`Bearer ${r}`),e(s,{...a,headers:c}).then(d=>(Sj(d),d))}}class sb extends Error{status;details;constructor(n,s,a){super(n),this.name="ApiRequestError",this.status=s,this.details=a}}function Ej(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Ts(e){return`/api${e}`}async function T(e,n={}){const s=Ts(e),a=wr(),r=(()=>{if(a){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),wi(f)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),d=l.includes("application/json");if(l.includes("text/html")||Ej(c))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!d){const h=c.length>160?`${c.slice(0,160)}...`:c;throw new Error(`API returned ${l||"an unknown content type"} instead of JSON for ${s}. (${o.status} ${o.statusText})${h?` Response: ${h}`:""}`)}let m;try{m=c?JSON.parse(c):null}catch{throw new Error(`API returned invalid JSON for ${s}. (${o.status} ${o.statusText})`)}if(!o.ok){const h=m;throw new sb(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function Qz(){return T("/health")}function Xz(){return T("/updates/check")}function _j(e,n,s,a,r){const o=new URLSearchParams;e!==void 0&&o.set("limit",String(e)),n!==void 0&&o.set("offset",String(n)),s&&o.set("projectId",s),a&&o.set("q",a),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return T(`/tasks${l}`)}async function La(e,n){const a=Ts(V(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(a,{headers:wi({"Content-Type":"application/json"})}),l=await o.json();if(o.ok)return l;if(r===2)throw new Error(l.error||"Request failed")}throw new Error("Request failed")}function ib(e,n,s){const{title:a,description:r,column:o,dependencies:l,breakIntoSubtasks:c,enabledWorkflowSteps:d,assignedAgentId:u,modelPresetId:m,modelProvider:h,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:x,planningModelId:w,thinkingLevel:b,summarize:y,reviewLevel:S,executionMode:j,priority:C,source:v,nodeId:N,branch:I,baseBranch:F,githubTracking:_}=e;return Ho(V("/tasks",n),{method:"POST",nodeId:s?.transportNodeId,localNodeId:s?.localNodeId,body:JSON.stringify({title:a,description:r,column:o,dependencies:l,breakIntoSubtasks:c,enabledWorkflowSteps:d,assignedAgentId:u,modelPresetId:m,modelProvider:h,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:x,planningModelId:w,thinkingLevel:b,summarize:y,reviewLevel:S,executionMode:j,priority:C,source:v,nodeId:N,branch:I,baseBranch:F,githubTracking:_})})}function Hs(e,n,s){return T(V(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Mj(e,n,s,a,r,o,l,c,d){return T(V("/tasks/batch-update-models",d),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:a,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function Aj(e,n,s,a){return T(V(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof a=="object"&&a?.preserveProgress?{preserveProgress:!0}:{}})})}function Rj(e,n,s){const a=new URLSearchParams;s?.removeDependencyReferences&&a.set("removeDependencyReferences","true");const r=a.size>0?`?${a.toString()}`:"";return T(V(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Ij(e,n){return T(V(`/tasks/${e}/merge`,n),{method:"POST"})}function Tj(e,n){return T(V(`/tasks/${e}/retry`,n),{method:"POST"})}function Pj(e,n){return T(V(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function $j(e,n){return T(V(`/tasks/${e}/duplicate`,n),{method:"POST"})}function ab(e,n){return T(V(`/tasks/${e}/pause`,n),{method:"POST"})}function Dj(e,n){return T(V(`/tasks/${e}/unpause`,n),{method:"POST"})}function Lj(e,n){return T(V(`/tasks/${e}/archive`,n),{method:"POST"})}function Oj(e,n){return T(V(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Fj(e){return T(V("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function zj(e,n){return T(V(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Bj(e,n){return T(V(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Uj(e){return T(V("/config",e))}function gc(e){return T(V("/settings",e))}function Xo(e,n){return T(V("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Hj(e){return T(V("/update-check",e))}function Zz(e){return T(V("/remote/settings",e))}function e3(e,n){return T(V("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function t3(e){return T(V("/remote/status",e))}function n3(e){return T(V("/remote/install-cloudflared",e),{method:"POST"})}function s3(e){return T(V("/remote/tunnel/start",e),{method:"POST"})}function i3(e){return T(V("/remote/tunnel/stop",e),{method:"POST"})}function a3(e){return T(V("/remote/tunnel/kill-external",e),{method:"POST"})}function r3(e){return T(V("/remote/token/persistent/regenerate",e),{method:"POST"})}function o3(e,n){return T(V("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function rb(e,n,s){const a=new URLSearchParams;e&&a.set("format",e),a.set("tokenType",n),n==="short-lived"&&typeof s=="number"&&Number.isFinite(s)&&a.set("ttlMs",String(s));const r=a.toString();return r?`?${r}`:""}function l3(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:a}=e,r=rb(null,s,a);return T(V(`/remote/url${r}`,n))}function c3(e="text",n={}){const{projectId:s,tokenType:a="persistent",ttlMs:r}=n,o=rb(e,a,r);return T(V(`/remote/qr${o}`,s))}function d3(e){return T(V("/memory",e))}function u3(e,n){return T(V("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function m3(e){return T(V("/memory/files",e))}function h3(e,n){const s=`path=${encodeURIComponent(e)}`;return T(V(`/memory/file?${s}`,n))}function p3(e,n,s){return T(V("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function f3(e,n){let s,a=n;if(n!==void 0)s=e;else if(typeof e=="string"&&e.trim().length>0){const r=e.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:a=r}return T(V("/memory/compact",a),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function g3(e){return T(V("/memory/dream",e),{method:"POST"})}function b3(e){return T(V("/memory/insights",e))}function x3(e,n){return T(V("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function v3(e){return T(V("/memory/extract",e),{method:"POST"})}function y3(e){return T(V("/memory/audit",e))}function w3(e){return T(V("/memory/stats",e))}function k3(e){return T(V("/memory/backend",e))}function j3(e){return T(V("/memory/install-qmd",e),{method:"POST"})}function N3(e,n){return T(V("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Yi(){return T("/settings/global")}function Dn(e){return T("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function S3(e){return T(V("/settings/scopes",e))}function C3(e){return T(V("/settings/pi-extensions",e))}function E3(e,n){return T(V("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function _3(e,n,s){return T(V("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function M3(){return T("/pi-settings")}async function A3(e){return T("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function R3(e){return T("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function I3(e){return T(V("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function bc(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ts(V(`/tasks/${e}/attachments`,s)),{method:"POST",headers:wi(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function qj(e,n,s){return T(V(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Om(e,n,s){const a=new URLSearchParams;s?.limit!==void 0&&a.set("limit",String(s.limit)),s?.offset!==void 0&&a.set("offset",String(s.offset));const r=a.toString()?`?${a.toString()}`:"",o=V(`/tasks/${e}/logs${r}`,n),l=await fetch(Ts(o),{headers:wi()});if(!l.ok){const m=await l.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(m.error||`HTTP ${l.status}`)}const c=await l.json(),d=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):c.length,u=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:c,total:d,hasMore:u}}function Vj(e,n,s,a){return T(V(`/tasks/${e}/comments/${n}`,a),{method:"PATCH",body:JSON.stringify({text:s})})}function Wj(e,n,s){return T(V(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Kj(e,n){return T(V(`/tasks/${e}/documents`,n))}function Gj(e,n,s){return T(V(`/tasks/${e}/documents/${n}/revisions`,s))}async function T3(e,n){const s=new URLSearchParams;e?.q&&s.set("q",e.q),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));const a=s.toString(),r=`/documents${a?`?${a}`:""}`;return T(V(r,n))}function P3(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const a=s.toString(),r=`/files/markdown-list${a?`?${a}`:""}`;return T(V(r,e))}function Fm(e,n,s,a,r){return T(V(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:a?.author,metadata:a?.metadata})})}function Jj(e,n,s){return T(V(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function Yj(e,n,s){return T(V(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Qj(e,n,s){return T(V(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Xj(e,n){return T(V(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Zj(e,n,s){return T(V(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Ks(){return T("/models")}function eN(){return T("/usage")}function tN(){return T("/providers/claude-cli/status")}function nN(){return T("/system/fn-binary/status")}function sN(){return T("/system/fn-binary/install",{method:"POST"})}function iN(){return T("/providers/droid-cli/status")}function aN(){return T("/providers/cursor-cli/status")}function rN(){return T("/providers/llama-cpp/status")}async function $3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return T(`/providers/hermes/status${n}`)}async function D3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await T(`/providers/hermes/profiles${n}`)).profiles??[]}async function L3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return T(`/providers/openclaw/status${n}`)}async function O3(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),T(`/providers/paperclip/status?${n.toString()}`)}async function F3(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await T(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function z3(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await T(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function B3(e){return T("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function U3(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return T(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function H3(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return(await T(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function q3(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await T(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function V3(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return T(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function oN(e){return T("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function lN(e){return T("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function cN(e){return T("/auth/cursor-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function dN(e){return T("/auth/llama-cpp",{method:"POST",body:JSON.stringify({enabled:e})})}async function uN(){const n=(await T("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(a=>({id:a.id,name:a.name}))}));return Object.assign(n,{providers:n})}function mN(e){return T("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function W3(e,n){const s=n,a={...typeof s.name=="string"?{name:s.name}:{},...typeof s.baseUrl=="string"?{baseUrl:s.baseUrl}:{},...typeof s.apiKey=="string"?{apiKey:s.apiKey}:{},...Array.isArray(s.models)?{models:s.models.map(r=>({id:r.id,name:r.name??r.id}))}:{},...s.api?{apiType:s.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible"}:{},..."apiType"in n?{apiType:n.apiType}:{}};return T(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(a)})}function K3(e){return T(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function hN(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return mN({name:e.name?.trim()||e.id,apiType:n,baseUrl:e.baseUrl,apiKey:e.apiKey,models:e.models?.map(s=>({id:s.id,name:s.name??s.id}))})}function Eo(){return T("/auth/status")}function pN(e){return T("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function fN(e,n){return T("/auth/manual-code",{method:"POST",body:JSON.stringify({provider:e,code:n})})}function gN(e){return T("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function bN(e){return T("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function xN(e,n){return T("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function vN(e){return T("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function yN(e,n,s,a){return T("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:a})})}function wN(e,n,s,a){return T(V("/github/issues/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function kN(e,n,s){return T("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function jN(e,n,s,a){return T(V("/github/pulls/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function NN(e){return T(V("/git/remotes",e))}function SN(e){return T(V("/git/remotes/detailed",e))}function CN(e,n,s){return T(V("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function EN(e,n){return T(V(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function _N(e,n,s){return T(V(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function MN(e,n,s){return T(V(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function AN(e,n,s){return T(V(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function RN(e,n){return T(V(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function IN(e,n){return(await T(V("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function Zo(e,n,s,a){return T(V("/terminal/sessions",a),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function zm(e,n){return T(V(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function TN(e){return T(V("/terminal/sessions",e))}function gi(e){return T(V("/git/status",e))}function PN(e,n){const s=e?`?limit=${e}`:"";return T(V(`/git/commits${s}`,n))}function Hl(e,n){return T(V(`/git/commits/${e}/diff`,n))}function $N(e){return T(V("/git/commits/ahead",e))}function DN(e,n,s,a){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return T(V(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,a))}function Vr(e){return T(V("/git/branches",e))}function LN(e,n,s){const a=`?limit=${n}`;return T(V(`/git/branches/${encodeURIComponent(e)}/commits${a}`,s))}function ON(e){return T(V("/git/worktrees",e))}function FN(e,n,s){return T(V("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function zN(e,n){return T(V(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Bm(e,n,s){const a=n?"?force=true":"";return T(V(`/git/branches/${encodeURIComponent(e)}${a}`,s),{method:"DELETE"})}function BN(e,n){return T(V("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function UN(e,n){const s=typeof e=="string"?void 0:e;return T(V("/git/pull",typeof e=="string"?e:n),{method:"POST",body:JSON.stringify({rebase:s?.rebase??!1})})}function HN(e){return T(V("/git/push",e),{method:"POST"})}function el(e){return T(V("/git/stashes",e))}function qN(e,n){return T(V("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function VN(e,n,s){return T(V(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function WN(e,n){return T(V(`/git/stashes/${e}`,n),{method:"DELETE"})}function KN(e,n){return T(V(`/git/stashes/${e}/diff`,n))}function GN(e,n,s){const a=new URLSearchParams;return a.set("path",e),a.set("staged",String(n)),T(V(`/git/diff/file?${a.toString()}`,s))}function sr(e){return T(V("/git/changes",e))}function Um(e,n){return T(V("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function JN(e,n){return T(V("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Hm(e,n){return T(V("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function YN(e,n){return T(V("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function QN(e){return T(V("/workspaces",e))}function XN(e,n,s){const a=new URLSearchParams({workspace:e});return n&&a.set("path",n),s&&a.set("projectId",s),T(`/files?${a.toString()}`)}function ZN(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),T(`/files/${encodeURIComponent(n)}?${a.toString()}`)}function eS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function tS(e,n,s){const a=new URLSearchParams({q:e});return n&&a.set("workspace",n),s&&a.set("projectId",s),T(`/files/search?${a.toString()}`)}function nS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function sS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function iS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),T(`/files/${encodeURIComponent(n)}/delete?${a.toString()}`,{method:"POST"})}function aS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function ob(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${a.toString()}`}function rS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${a.toString()}`}function oS(e,n,s){return T(V("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function lS(e,n,s,a,r){return T(V("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId,planningDepth:a?.planningDepth,customQuestionCount:a?.customQuestionCount,...r?{existingSessionId:r}:{}})})}function qm(e,n,s,a){return T(V("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function cS(e,n,s){return T(V(`/planning/${encodeURIComponent(e)}/back`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function dS(e,n,s){return T(V(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function uS(e,n,s){return T(V(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function lb(e,n,s){return T(V("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function G3(e,n,s,a){return T(V("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,mode:n.mode,existingAgentConfig:n.existingAgentConfig,planningModelProvider:a?.planningModelProvider,planningModelId:a?.planningModelId})})}function J3(e,n,s){return T(V("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function Y3(e,n){return T(V("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function mS(e,n,s){return T(V("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function hS(e,n,s){return T(V("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function pS(e,n,s){return T(V("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const iu=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(iu))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function fS(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Pr(e,n,s={}){const a=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,d=null,u=!1;const m=p=>{const g=p.lastEventId;if(!g)return!0;const x=Number.parseInt(g,10);return Number.isFinite(x)?d!==null&&x<=d?!1:(d=x,!0):!0},h=()=>{if(o)return;const p=fS(e,d),g=new EventSource(Di(p));r=g,g.onopen=()=>{l=0,u=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=x=>{const w=x;m(w)&&n.onMessage?.(w)};for(const[x,w]of Object.entries(n.events??{}))g.addEventListener(x,b=>{const y=b;m(y)&&w(y)});g.onerror=()=>{if(o||r!==g)return;if(g.readyState===EventSource.CONNECTING){u||(u=!0,s.onConnectionStateChange?.("reconnecting"));return}if(g.close(),l>=a){s.onFatalError?.("Connection lost");return}u=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const w=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},w)}};h();const f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),iu.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return iu.add(f),f}function Vm(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,a=e.name,r=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,o=typeof e.confidence=="number"?e.confidence:1,l=n==="root"?"root":n,c=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:a,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${a} (${l})`}}function kr(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",a=typeof e.previewUrl=="string"?e.previewUrl:e.detectedUrl,r=typeof e.manualPreviewUrl=="string"?e.manualPreviewUrl:e.manualUrl;return{id:typeof e.id=="string"?e.id:"",name:typeof e.name=="string"&&e.name.length>0?e.name:"default",status:s,command:typeof e.command=="string"?e.command:"",scriptName:typeof e.scriptId=="string"?e.scriptId:"",cwd:typeof e.cwd=="string"?e.cwd:"",pid:e.pid,startedAt:e.startedAt,previewUrl:a,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:a,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function gS(e,n){return{id:typeof e.id=="number"&&Number.isFinite(e.id)?e.id:n,text:typeof e.text=="string"?e.text:typeof e.line=="string"?e.line:"",stream:e.stream==="stderr"?"stderr":"stdout",timestamp:typeof e.timestamp=="string"?e.timestamp:""}}function bS(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((a,r)=>gS(a,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function xS(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,a=typeof n.offset=="number"&&Number.isFinite(n.offset)?Math.max(0,Math.floor(n.offset)):0,r=typeof n.lastEventId=="number"&&Number.isFinite(n.lastEventId)?Math.max(0,Math.floor(n.lastEventId)):null,o=e.length,l=e.map((u,m)=>({id:m+1,text:u,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(u=>u.id>r).slice(0,s),totalLines:o};const c=Math.max(o-a,0),d=Math.max(c-s,0);return{lines:l.slice(d,c),totalLines:o}}function Wm(e){return Array.isArray(e)?e.map(Vm):(e.candidates??[]).map(Vm)}async function vS(e){try{const n=await T(V("/dev-server/candidates",e));return Wm(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await T(V("/dev-server/detect",e));return Wm(s)}throw n}}function Fu(e){return T(V("/dev-server/status",e)).then(kr)}async function Q3(e={},n){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const a=s.size>0?`?${s.toString()}`:"";try{const r=await T(V(`/dev-server/logs/history${a}`,n));return bS(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await Fu(n);return xS(o.logs,e)}throw r}}function yS(e,n){const s=e.cwd??e.packagePath??".",a=e.scriptName;return T(V("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:a,scriptId:a,cwd:s,packagePath:e.packagePath})}).then(kr)}function wS(e){return T(V("/dev-server/stop",e),{method:"POST"}).then(kr)}function kS(e){return T(V("/dev-server/restart",e),{method:"POST"}).then(kr)}async function jS(e,n){const s=typeof e=="string"?{url:e}:e;try{const a=await T(V("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return kr(a)}catch(a){if(a instanceof Error&&/\/dev-server\/preview-url/.test(a.message)){const r=await T(V("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return kr(r)}throw a}}function X3(e){return Ts(V("/dev-server/logs/stream",e))}async function Z3(e){try{return(await T(V("/devserver",e))).sessions??[]}catch{try{const n=await Fu(e);return[{config:{id:n.id??"default",name:n.name??"Dev Server",command:n.command??"",cwd:n.cwd??"."},status:n.status,runtime:n.pid?{pid:n.pid,startedAt:n.startedAt??new Date().toISOString(),exitCode:n.exitCode??void 0,previewUrl:n.previewUrl}:void 0,previewUrl:n.previewUrl??n.detectedUrl??void 0,logHistory:(n.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}]}catch{return[]}}}async function e6(e,n){try{return await T(V(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await Fu(n);return!e||e==="default"||e===s.id?{config:{id:s.id??"default",name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}:null}catch{return null}}}async function t6(e,n){try{return await T(V(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await yS({command:""},n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function n6(e,n){try{return await T(V(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await wS(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function s6(e,n){try{return await T(V(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await kS(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function i6(e,n,s){try{const a=await T(V(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:a.url??null,source:a.source??null}}catch{const a=await jS({url:n},s);return{url:a.previewUrl??a.manualUrl??null,source:"manual"}}}async function a6(e){try{return(await T(V("/devserver/detect",e))).candidates??[]}catch{try{return(await vS(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function r6(e,n){return Ts(V(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function zo(e,n,s=25e3){const a=setInterval(()=>{g0(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(a)}}}function NS(e,n){return Ts(V(`/planning/${encodeURIComponent(e)}/stream`,n))}function SS(e,n){return Ts(V(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function o6(e,n,s,a){const r=SS(e,n),o=Pr(r,{events:{thinking:l=>{try{s.onThinking?.(JSON.parse(l.data))}catch{s.onThinking?.(l.data)}},question:l=>{try{s.onQuestion?.(JSON.parse(l.data))}catch{}},summary:l=>{try{s.onSummary?.(JSON.parse(l.data))}catch{}},error:l=>{try{const c=JSON.parse(l.data);s.onError?.(c.message||c)}catch{s.onError?.(l.data||"Stream error")}},complete:()=>{s.onComplete?.()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:l=>s.onError?.(l)});return{close:o.close,isConnected:o.isConnected}}function CS(e,n,s,a){const r=NS(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Pr(r,{onOpen:()=>{c(),o=zo(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[planning] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[planning] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function Bo(e,n){const s=new URLSearchParams;n?.scope&&s.set("scope",n.scope),n?.projectId&&s.set("projectId",n.projectId);const a=s.toString();return a?`${e}?${a}`:e}function ES(e){return T(Bo("/routines",e))}function _S(e,n){return T(Bo("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Km(e,n,s){return T(Bo(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function MS(e,n){await T(Bo(`/routines/${e}`,n),{method:"DELETE"})}function AS(e,n){return T(Bo(`/routines/${e}/trigger`,n),{method:"POST"})}function Gm(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since!==void 0&&n.set("since",e.since),e?.type!==void 0&&n.set("type",e.type),e?.projectId&&n.set("projectId",e.projectId);const s=n.size>0?`?${n.toString()}`:"";return T(`/activity${s}`)}function RS(e){const n=V("/activity",e);return T(n,{method:"DELETE"})}function Uo(e){return T(V("/workflow-steps",e))}function Jm(e,n){return T(V("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function IS(e,n,s){return T(V(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function TS(e,n){return T(V(`/workflow-steps/${e}`,n),{method:"DELETE"})}function Ym(e,n){return T(V(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function PS(e,n){return T(V(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function $S(){return T("/workflow-step-templates")}function DS(){return T("/plugin-workflow-step-templates")}function LS(e,n){return T(V(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function _o(e){return T(V("/scripts",e))}function OS(e,n,s){return T(V("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function FS(e,n){return T(V(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function cb(e,n,s){return(await T(V("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const tl={RATE_LIMIT:"Too many refinement requests. Please wait an hour.",INVALID_TYPE:"Invalid refinement option selected.",NETWORK:"Failed to refine text. Please try again."};function db(e){if(!(e instanceof Error))return tl.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?tl.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?tl.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:tl.NETWORK}function zS(e,n){return T(V("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function BS(e,n,s){return T(V(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function US(e,n){return Ts(V(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function HS(e,n,s,a){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Pr(US(e,n),{onOpen:()=>{l(),r=zo(e,n)},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},subtasks:d=>{try{s.onSubtasks?.(JSON.parse(d.data))}catch(u){console.error("[subtasks] Failed to parse subtasks event:",u)}},error:d=>{try{const u=JSON.parse(d.data),m=typeof u=="string"&&u.length>0?u:null;s.onError?.(m||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{l(),s.onError?.(d)}});return o={close:()=>{l(),c.close()},isConnected:c.isConnected},o}function qS(e,n,s,a,r){return T(V("/subtasks/create-tasks",a),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,...r?.branch!==void 0?{branch:r.branch}:{},...r?.baseBranch!==void 0?{baseBranch:r.baseBranch}:{},...r?.branchSelection?{branchSelection:r.branchSelection}:{},...r?.branchAssignment?{branchAssignment:r.branchAssignment}:{},subtasks:n.map(o=>({tempId:o.id,title:o.title,description:o.description,size:o.suggestedSize,dependsOn:o.dependsOn}))})})}function ub(e,n,s){return T(V("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function V(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function VS(e,n,s){if(!n||n===s)return e;const a="/api",r=e.startsWith(a)?e.slice(a.length):e;return`/proxy/${encodeURIComponent(n)}${r}`}function Ho(e,n){const{nodeId:s,localNodeId:a,...r}=n??{},o=VS(e,s,a);return T(o,r)}function $r(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return T(`/agents${a}`)}function au(e,n){return T(V(`/agents/${encodeURIComponent(e)}`,n))}function WS(e,n){return T(V("/agents",n),{method:"POST",body:JSON.stringify(e)})}function KS(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function l6(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ts(V(`/agents/${encodeURIComponent(e)}/avatar`,s)),{method:"POST",headers:wi(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Avatar upload failed");return o}function c6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/avatar`,n),{method:"DELETE"})}function d6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function u6(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function m6(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function h6(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function p6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function f6(e,n,s){const a=`path=${encodeURIComponent(n)}`;return T(V(`/agents/${encodeURIComponent(e)}/memory/file?${a}`,s))}function g6(e,n,s,a){return T(V(`/agents/${encodeURIComponent(e)}/memory/file`,a),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function GS(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function JS(e,n){return T(V(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function b6(e,n,s){const a=new URLSearchParams;n!==void 0&&a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return T(`/agents/${encodeURIComponent(e)}/runs${r}`)}function x6(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function v6(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function y6(e,n,s){const a=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return T(V(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:a,triggerDetail:r})})}function w6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function YS(e){return T(V("/agents/stats",e))}function k6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function j6(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const a=s.toString();return T(`/agents/org-tree${a?`?${a}`:""}`)}function N6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function Qm(e,n,s){return T(V(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function mb(e){return{reviewState:{source:e.mode,summary:e.summary??void 0,items:e.items.map(n=>({id:n.itemId,body:n.body,author:{login:n.author},createdAt:n.createdAt??new Date(0).toISOString(),updatedAt:n.updatedAt??void 0,path:n.filePath,threadId:n.threadId,htmlUrl:n.url,state:n.reviewState??void 0,isResolved:n.isResolved})),addressing:[],lastRefreshedAt:e.fetchedAt??void 0,refreshStatus:"ready",refreshSource:"initial-load"},automationStatus:null}}async function QS(e,n){const s=await T(V(`/tasks/${encodeURIComponent(e)}/review`,n));return mb(s)}async function XS(e,n){const s=await T(V(`/tasks/${encodeURIComponent(e)}/review/refresh`,n),{method:"POST"});return mb(s)}function ZS(e,n,s){return T(V(`/tasks/${encodeURIComponent(e)}/review/address`,s),{method:"POST",body:JSON.stringify({selectedItems:n,tab:"review"})})}function S6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/tasks`,n))}function C6(){return T("/agents/companies")}function E6(e,n){return T(V("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function _6(e,n){return T(V("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function M6(e,n){return T(V(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function A6(e){return T(V("/backups",e))}function R6(e){return T(V("/backups",e),{method:"POST"})}function I6(e,n){const s=V("/settings/export",n),a=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return T(a)}function T6(e,n,s){return T(V("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function e1(e){return Array.isArray(e.nodeMappings)||Array.isArray(e.projectNodeMappings)||Array.isArray(e.pathMappings)}function Xm(){return T("/projects/across-nodes")}function ql(){return T("/nodes")}function P6(){return T("/docker/nodes")}function $6(e){return T(`/docker/nodes/${encodeURIComponent(e)}/container-status`)}function D6(e,n){const s=new URLSearchParams;typeof n?.tail=="number"&&s.set("tail",String(n.tail));const a=s.size>0?`?${s.toString()}`:"";return T(`/docker/nodes/${encodeURIComponent(e)}/logs${a}`)}function L6(e){return T("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function t1(e){return T("/nodes",{method:"POST",body:JSON.stringify(e)})}function n1(e){return T("/nodes/discover-projects",{method:"POST",body:JSON.stringify(e)})}function s1(e,n){return T(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function i1(e){return T(`/nodes/${encodeURIComponent(e)}/docker-config`)}function a1(e,n){return T(`/nodes/${encodeURIComponent(e)}/docker-config`,{method:"PATCH",body:JSON.stringify(n)})}function r1(e){return T(`/nodes/${encodeURIComponent(e)}/docker-config/diff`)}function Zm(e){return T(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function o1(e){const n=await T(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}async function O6(){return T("/mesh/state")}function F6(e,n,s,a){const r=s&&s!==a?s:void 0,o=new URLSearchParams;e&&o.set("path",e),n&&o.set("showHidden","true"),r&&o.set("nodeId",r);const l=wr();l&&o.set("fn_token",l);const c=o.toString(),d=`/browse-directory${c?`?${c}`:""}`;return T(d)}function l1(e){return T("/projects",{method:"POST",body:JSON.stringify(e)})}function hb(e){return T(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function c1(e,n,s){return T(`/projects/${encodeURIComponent(e)}/path-mappings/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({path:s})})}function eh(e){return T(`/projects/${encodeURIComponent(e)}/health`)}function d1(e){return T(V("/executor/stats",e))}function u1(e){return T(V("/system-stats",e))}function m1(e){return T(V("/kill-vitest",e),{method:"POST"})}function th(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since&&n.set("since",e.since),e?.projectId&&n.set("projectId",e.projectId),e?.type&&n.set("type",e.type);const s=n.size>0?`?${n.toString()}`:"";return T(`/activity-feed${s}`)}function h1(e){return T(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function p1(e){return T(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function z6(){return T("/global-concurrency")}function B6(e){return T("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function f1(e,n){return T(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function pb(e,n,s){const a=new URLSearchParams;n&&a.set("worktree",n),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return T(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function g1(e,n){return T(V(`/tasks/${encodeURIComponent(e)}/commit-associations`,n))}function b1(e){return T(V("/missions",e))}function x1(e,n){return T(V("/missions",n),{method:"POST",body:JSON.stringify(e)})}function fb(e,n){return T(V(`/missions/${encodeURIComponent(e)}`,n))}function v1(e,n,s){return T(V(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function y1(e,n){return T(V(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function w1(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return T(V(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function k1(e){return T(V("/missions/health",e))}function j1(e,n,s){return T(V(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function N1(e,n,s){return T(V(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function S1(e,n){return T(V(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function C1(e,n,s){return T(V(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function E1(e,n,s){return T(V(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function _1(e,n){return T(V(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function M1(e,n){return T(V(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function A1(e,n,s){return T(V(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function R1(e,n,s){return T(V(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function I1(e,n){return T(V(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function T1(e,n,s){return T(V(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function P1(e,n){return T(V(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function $1(e,n,s,a,r){return T(V(`/missions/features/${encodeURIComponent(e)}/triage`,a),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s,...r})})}function D1(e,n,s){return T(V(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST",body:JSON.stringify({})})}function Dc(e,n){return T(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function L1(e,n,s){return T(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function O1(e,n,s){return T(V(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function F1(e,n,s){return T(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function z1(e,n,s){return T(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function B1(e,n){return T(V(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Lc(e,n){return T(V(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function nh(e,n){return T(V(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function U1(e,n){return T(V(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function sh(e,n){return T(V(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function H1(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return T(V(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function q1(e,n){return T(V(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function V1(e,n){return T(V(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function W1(e,n){return T(V(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function K1(e,n){return T(V(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function G1(e,n,s){return T(V(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function J1(e,n,s){return T(V("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function Y1(e,n,s,a){return T(V("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function Q1(e,n,s){return T(V(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function gb(e,n,s){return T(V("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function X1(e,n,s,a){return T(V("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Z1(e,n,s,a){const r=Ts(V(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Pr(r,{onOpen:()=>{c(),o=zo(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[mission-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[mission-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function qo(e,n,s){return V(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Vo(e,n,s){return V(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function e0(e,n){return T(qo(e,"/start",n),{method:"POST"})}function t0(e,n,s,a){return T(qo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function n0(e,n,s,a){const r=Ts(qo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Pr(r,{onOpen:()=>{c(),o=zo(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[milestone-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[milestone-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function s0(e,n,s){return T(qo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function i0(e,n){return T(qo(e,"/skip",n),{method:"POST"})}function a0(e,n){return T(Vo(e,"/start",n),{method:"POST"})}function r0(e,n,s,a){return T(Vo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function o0(e,n,s,a){const r=Ts(Vo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Pr(r,{onOpen:()=>{c(),o=zo(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[slice-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[slice-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function l0(e,n,s){return T(Vo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function c0(e,n){return T(Vo(e,"/skip",n),{method:"POST"})}async function d0(e,n){try{return await T(V(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function U6(e){return T(V("/todos",e))}function H6(e,n){const s={title:e};return T(V("/todos",n),{method:"POST",body:JSON.stringify(s)})}function q6(e,n,s){const a={title:n};return T(V(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function V6(e,n){return T(V(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function W6(e,n,s){const a={text:n};return T(V(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(a)})}function K6(e,n,s){const a=n;return T(V(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function G6(e,n){return T(V(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function J6(e,n,s){return T(V(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function jr(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function zu(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeCompleted&&s.set("includeCompleted","1"),n?.includeArchived&&s.set("includeArchived","1");const a=s.toString(),r=await fetch(Ts(`/ai-sessions${a?`?${a}`:""}`),{headers:wi()});return r.ok?(await r.json()).sessions??[]:[]}async function u0(e){return T(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function m0(e){return T(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function Ti(e){const n=await fetch(Ts(`/ai-sessions/${encodeURIComponent(e)}`),{headers:wi()});return n.ok?n.json():null}async function h0(e,n){const s=await T(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function p0(e,n){return T(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function f0(e,n){return T(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function bb(e){await fetch(Ts(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:wi()})}function g0(e,n){return T(V(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function b0(e,n,s){return T(V(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function x0(e,n){return T(V(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function v0(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.unreadOnly&&s.set("unreadOnly","true"),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return T(`/messages/inbox${a}`)}function y0(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return T(`/messages/outbox${a}`)}function xb(e){return T(V("/messages/unread-count",e))}function w0(e,n){return T(V("/messages",n),{method:"POST",body:JSON.stringify(e)})}function k0(e,n){return T(V(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function j0(e){return T(V("/messages/read-all",e),{method:"POST"})}function N0(e,n){return T(V(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function S0(e,n,s){const a=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return T(V(a,s))}function C0(e,n){return T(V(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function E0(e){return T(V("/agents/mailbox/all",e))}function nl(e,n){const s=new URLSearchParams;e?.status&&s.set("status",e.status),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return T(`/approvals${a}`)}function ih(e,n){return T(V(`/approvals/${encodeURIComponent(e)}`,n))}function _0(e,n,s){return T(V(`/approvals/${encodeURIComponent(e)}/decision`,s),{method:"POST",body:JSON.stringify(n)})}function Y6(e,n,s){const a=new URLSearchParams;a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return T(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function Q6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function X6(e,n,s){const a=new URLSearchParams;s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return T(`/agents/${encodeURIComponent(e)}/performance${r}`)}function Z6(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.category&&a.set("category",n.category),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return T(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function e5(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function t5(e,n){return T(V(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function n5(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function s5(e,n){return T(V(`/agents/${encodeURIComponent(e)}/budget`,n))}function i5(e,n){return T(V(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function a5(e){return T(V("/plugins",e))}async function r5(e,n){return T(V("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function o5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function l5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function c5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function d5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function u5(e,n,s){return T(V(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function m5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}/setup-status`,n))}async function h5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}/setup/install`,n),{method:"POST"})}async function p5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function f5(e,n,s){return T(V(`/plugins/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function g5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}/rescan`,n),{method:"POST"})}async function M0(e){return T(V("/plugins/ui-slots",e))}async function A0(e){return T(V("/plugins/dashboard-views",e))}async function b5(e){return T(V("/plugins/runtimes",e))}async function R0(e){return(await T(V("/skills/discovered",e))).skills}async function x5(e,n,s){return T(V("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function v5(e,n,s){const a=new URLSearchParams;e&&a.set("q",e),a.set("limit",String(n));const r=a.size>0?`?${a.toString()}`:"";return T(V(`/skills/catalog${r}`,s))}async function y5(e,n){return(await T(V(`/skills/${encodeURIComponent(e)}/content`,n))).content}function ah(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const a=s.toString();return T(`/chat/sessions${a?`?${a}`:""}`)}async function I0(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const a=e.modelProvider?.trim(),r=e.modelId?.trim();if(a&&!r||!a&&r)throw new Error("Both modelProvider and modelId must be provided together, or neither should be provided");const o=new URLSearchParams;return o.set("lookup","resume"),o.set("agentId",s),n&&o.set("projectId",n),a&&r&&(o.set("modelProvider",a),o.set("modelId",r)),{session:(await T(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function T0(e,n){return T(V("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function P0(e,n){return T(V(`/chat/sessions/${encodeURIComponent(e)}`,n))}function w5(e,n,s){return T(V(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function k5(e,n){return T(V(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Wr(e,n,s){const a=new URLSearchParams;n?.limit!==void 0&&a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset)),n?.before&&a.set("before",n.before);const r=a.toString();return T(V(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function j5(e={},n){const s=new URLSearchParams;n&&s.set("projectId",n),e.status&&s.set("status",e.status),e.agentId&&s.set("agentId",e.agentId);const a=s.toString();return T(`/chat/rooms${a?`?${a}`:""}`)}function N5(e,n){const s={...e,...n?{projectId:n}:{}};return T(V("/chat/rooms",n),{method:"POST",body:JSON.stringify(s)})}function S5(e,n){return T(V(`/chat/rooms/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function C5(e,n){return T(V(`/chat/rooms/${encodeURIComponent(e)}/members`,n))}function E5(e,n,s){const a=new URLSearchParams;n?.limit!==void 0&&a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset)),n?.before&&a.set("before",n.before);const r=a.toString();return T(V(`/chat/rooms/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function _5(e,n,s){return T(V(`/chat/rooms/${encodeURIComponent(e)}/messages`,s),{method:"POST",body:JSON.stringify(n)})}function $0(e,n){return T(V(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function D0(e){if(!e||typeof e!="object")return null;const n=e,s=typeof n.summary=="string"?n.summary.trim():"";if(!s)return null;const a=(()=>{const r=n.reference;if(!r||typeof r!="object")return;const o=r,l=typeof o.kind=="string"?o.kind.trim():"",c=typeof o.id=="string"?o.id.trim():"";if(!(!l||!c))return{kind:l,id:c,...typeof o.label=="string"&&o.label.trim()?{label:o.label.trim()}:{}}})();return{summary:s,...typeof n.errorClass=="string"&&n.errorClass.trim()?{errorClass:n.errorClass.trim()}:{},...typeof n.code=="string"&&n.code.trim()?{code:n.code.trim()}:{},...typeof n.detail=="string"&&n.detail.trim()?{detail:n.detail.trim()}:{},...a?{reference:a}:{}}}function vb(e){try{const n=JSON.parse(e),s=D0(n);return s||(n&&typeof n=="object"&&typeof n.message=="string"?n.message:typeof n=="string"?n:e||"Stream error")}catch{return e||"Stream error"}}function L0(e,n,s,a,r,o){const l=Ts(V(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let d=!1,u=!1,m=!1;const h=Math.max(1e3,6e4);let f=null;const p=()=>{f&&(clearTimeout(f),f=null)},g=()=>{m||(m=!0,p())},x=(w,b)=>{if(w)switch(g(),w){case"thinking":try{s.onThinking?.(JSON.parse(b))}catch{s.onThinking?.(b)}break;case"text":try{s.onText?.(JSON.parse(b))}catch{s.onText?.(b)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(b))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(b))}catch{}break;case"fallback":try{s.onFallback?.(JSON.parse(b))}catch{}break;case"done":u=!0;try{const y=JSON.parse(b);s.onDone?.({messageId:typeof y.messageId=="string"?y.messageId:"",...y.message&&typeof y.message=="object"?{message:y.message}:{}})}catch{s.onDone?.({messageId:""})}break;case"error":u=!0,s.onError?.(vb(b));break}};return(async()=>{try{const w=Array.isArray(a)&&a.length>0,b=w?(()=>{const _=new FormData;return _.append("content",n),a.forEach(M=>_.append("attachments",M)),_})():JSON.stringify({content:n}),y=await fetch(l,{method:"POST",headers:w?wi():wi({"Content-Type":"application/json"}),body:b,signal:c.signal});if(!y.ok){const _=await y.text();let M=`Request failed: ${y.status}`;try{M=JSON.parse(_).error||M}catch{}s.onError?.(M);return}if(!y.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected"),f=setTimeout(()=>{u||d||m||(u=!0,s.onError?.("Timed out waiting for first response event"),c.abort())},h);const S=y.body.getReader(),j=new TextDecoder;let C="",v="",N=[];const I=(_,M=!1)=>{C+=_;const z=C.split(`
643
+ `);C=z.pop()||"",M&&C.length>0&&(z.push(C),C="");for(const U of z){const R=U.endsWith("\r")?U.slice(0,-1):U;if(R.startsWith("event:"))v=R.slice(6).trim();else if(R.startsWith("data:")){const D=R.slice(5);N.push(D.startsWith(" ")?D.slice(1):D)}else if(R===""){const D=N.join(`
644
+ `);x(v,D),v="",N=[]}}if(M&&v&&N.length>0){const U=N.join(`
645
+ `);x(v,U),v="",N=[]}};for(;;){const{done:_,value:M}=await S.read();if(_){I(j.decode(),!0);break}I(j.decode(M,{stream:!0}))}const F=C.length>0||v.length>0||N.length>0;!u&&!d&&!F&&s.onError?.("Connection closed unexpectedly"),p()}catch(w){if(w instanceof DOMException&&w.name==="AbortError"){!d&&!u&&s.onError?.("Connection aborted"),p();return}if(d){p();return}p(),s.onError?.(w instanceof Error?w.message:"Connection error")}})(),{close:()=>{d=!0,p(),c.abort()},isConnected:()=>!d}}function O0(e,n,s,a){const r=Ts(V(`/chat/sessions/${encodeURIComponent(e)}/stream`,s)),o=new AbortController;let l=!1,c=!1;const d=(u,m)=>{if(u)switch(u){case"thinking":try{n.onThinking?.(JSON.parse(m))}catch{n.onThinking?.(m)}break;case"text":try{n.onText?.(JSON.parse(m))}catch{n.onText?.(m)}break;case"tool_start":try{n.onToolStart?.(JSON.parse(m))}catch{}break;case"tool_end":try{n.onToolEnd?.(JSON.parse(m))}catch{}break;case"fallback":try{n.onFallback?.(JSON.parse(m))}catch{}break;case"done":c=!0;try{const h=JSON.parse(m);n.onDone?.({messageId:typeof h.messageId=="string"?h.messageId:"",...h.message&&typeof h.message=="object"?{message:h.message}:{}})}catch{n.onDone?.({messageId:""})}break;case"error":c=!0,n.onError?.(vb(m));break}};return(async()=>{try{const u=new Headers(wi());typeof a?.lastEventId=="number"&&u.set("Last-Event-ID",String(a.lastEventId));const m=await fetch(r,{method:"GET",headers:u,signal:o.signal});if(!m.ok){const y=await m.text();let S=`Request failed: ${m.status}`;try{S=JSON.parse(y).error||S}catch{}n.onError?.(S);return}if(!m.body){n.onError?.("No response body");return}n.onConnectionStateChange?.("connected");const h=m.body.getReader(),f=new TextDecoder;let p="",g="",x=[];const w=(y,S=!1)=>{p+=y;const j=p.split(`
646
+ `);p=j.pop()||"",S&&p.length>0&&(j.push(p),p="");for(const C of j){const v=C.endsWith("\r")?C.slice(0,-1):C;if(v.startsWith("event:"))g=v.slice(6).trim();else if(v.startsWith("data:")){const N=v.slice(5);x.push(N.startsWith(" ")?N.slice(1):N)}else if(v===""){const N=x.join(`
647
+ `);d(g,N),g="",x=[]}}if(S&&g&&x.length>0){const C=x.join(`
648
+ `);d(g,C),g="",x=[]}};for(;;){const{done:y,value:S}=await h.read();if(y){w(f.decode(),!0);break}w(f.decode(S,{stream:!0}))}const b=p.length>0||g.length>0||x.length>0;if(!c&&!l&&!b)return}catch(u){if(u instanceof DOMException&&u.name==="AbortError"){!l&&!c&&n.onError?.("Connection aborted");return}if(l)return;n.onError?.(u instanceof Error?u.message:"Connection error")}})(),{close:()=>{l=!0,o.abort()},isConnected:()=>!l}}function M5(e={},n){const s=new URLSearchParams;e.category&&s.set("category",e.category),e.status&&s.set("status",e.status),e.runId&&s.set("runId",e.runId),e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset));const a=s.size>0?`?${s.toString()}`:"";return T(V(`/insights${a}`,n))}function A5(e,n){return T(V(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function R5(e,n){return T(V(`/insights/${encodeURIComponent(e)}/archive`,n),{method:"POST"})}function I5(e,n){return T(V(`/insights/${encodeURIComponent(e)}/unarchive`,n),{method:"POST"})}function T5(e="manual",n,s,a,r){const o={trigger:e,inputMetadata:n};return a&&(o.modelProvider=a),r&&(o.modelId=r),T(V("/insights/run",s),{method:"POST",body:JSON.stringify(o)})}function P5(e){return T(V("/insights/runs",e))}function $5(e,n){return T(V(`/insights/runs/${encodeURIComponent(e)}`,n))}function D5(e,n){return T(V(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function L5(e={},n){const s=new URLSearchParams;e.q&&s.set("q",e.q),e.runId&&s.set("runId",e.runId),e.scoreMin!==void 0&&s.set("scoreMin",String(e.scoreMin)),e.scoreMax!==void 0&&s.set("scoreMax",String(e.scoreMax)),e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset));const a=s.size>0?`?${s.toString()}`:"";return T(V(`/evals${a}`,n))}function O5(e,n){return T(V(`/evals/${encodeURIComponent(e)}`,n))}function F5(e){return T(V("/evals/runs",e))}function z5(e={},n){const s=new URLSearchParams;e.q&&s.set("q",e.q),e.status&&s.set("status",e.status),e.limit!==void 0&&s.set("limit",String(e.limit));const a=s.size>0?`?${s.toString()}`:"";return T(V(`/research/runs${a}`,n))}function B5(e,n){return T(V("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function U5(e,n){return T(V(`/research/runs/${encodeURIComponent(e)}`,n))}function yb(e){if(e instanceof sb){const n=e.details?.code,s=typeof n=="string"?n:"INTERNAL_ERROR",a=typeof e.details?.setupHint=="string"?e.details.setupHint:void 0,r=typeof e.details?.retryable=="boolean"?e.details.retryable:void 0,o=e;throw o.researchCode=s,o.setupHint=a,o.retryable=r,o}throw e}async function H5(e,n){try{return await T(V(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}catch(s){yb(s)}}async function q5(e,n){try{return await T(V(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}catch(s){yb(s)}}function V5(e,n,s){return T(V(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function W5(e,n,s){const a=n.findingId??"finding-1";return T(V(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/task`,s),{method:"POST",body:JSON.stringify({title:n.title,description:n.description,priority:n.priority,attachExport:n.attachExport})})}function K5(e,n,s){const a=n.findingId??"finding-1";return T(V(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/tasks/${encodeURIComponent(n.taskId)}/enrich`,s),{method:"POST",body:JSON.stringify({attachExport:n.attachExport})})}async function F0(e){return Ho("/health",{nodeId:e})}async function z0(e){return Ho("/projects",{nodeId:e})}async function B0(e,n,s){const a=new URLSearchParams({projectId:n});return s&&s.trim()&&a.set("q",s.trim()),Ho(`/tasks?${a.toString()}`,{nodeId:e})}async function U0(e,n){return Ho(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function G5(e){return T(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function J5(e){return T(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function Y5(e){return T(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function Q5(e){return T(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}async function H0(e,n){return Promise.all(n.map(({projectId:s,path:a})=>c1(s,e,a)))}function q0(e){switch(e){case"online":return{label:"Online",dotClass:"node-status-indicator__dot--online"};case"offline":return{label:"Offline",dotClass:"node-status-indicator__dot--offline"};case"connecting":return{label:"Connecting",dotClass:"node-status-indicator__dot--connecting"};case"error":return{label:"Error",dotClass:"node-status-indicator__dot--error"};default:return{label:"Unknown",dotClass:"node-status-indicator__dot--offline"}}}function V0({node:e,showDetails:n=!1}){if(!e||e.type==="local")return t.jsx("div",{className:"node-status-indicator node-status-indicator--local",children:t.jsx("span",{className:"node-status-indicator__label",children:"Local"})});const{label:s,dotClass:a}=q0(e.status),r=e.status==="connecting";return t.jsxs("div",{className:"node-status-indicator node-status-indicator--remote",children:[t.jsx("span",{className:`node-status-indicator__dot ${a}`,children:r&&t.jsx("span",{className:"node-status-indicator__spinner"})}),t.jsx("span",{className:"node-status-indicator__name",children:e.name}),n&&t.jsxs("span",{className:"node-status-indicator__details",children:[e.type," · ",s]})]})}function W0(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Oa({status:e,showLabel:n=!1,className:s,compact:a=!1}){const r=W0(e);return t.jsxs("span",{className:`node-health-dot${a?" node-health-dot--compact":""}${s?` ${s}`:""}`,title:r,"aria-label":`Node status: ${r}`,children:[t.jsx("span",{className:`status-dot status-dot--${e}`}),n?t.jsx("span",{className:"node-health-dot__label",children:r}):null]})}const rh=new Map,K0=6e4;function wb(e){const[n,s]=i.useState([]),[a,r]=i.useState(!0),[o,l]=i.useState(null),c=i.useRef(!1),d=i.useRef(!1),u=i.useCallback(m=>n.filter(h=>h.slot.slotId===m),[n]);return i.useEffect(()=>{const m=e??"default";let h=!1;async function f(){const p=rh.get(m);if(p&&Date.now()<p.expiresAt){if(h||d.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const x=await M0(e);if(h||d.current)return;rh.set(m,{slots:x,expiresAt:Date.now()+K0}),s(x),c.current=!0}catch(x){if(h||d.current)return;l(x instanceof Error?x.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!d.current&&r(!1)}}return f(),()=>{h=!0}},[e]),i.useEffect(()=>{c.current=!1,d.current=!1},[e]),i.useEffect(()=>()=>{d.current=!0},[]),i.useMemo(()=>({slots:n,getSlotsForId:u,loading:a,error:o}),[n,u,a,o])}function oh({size:e,color:n,label:s="llama.cpp"}){return t.jsx(Wg,{size:e,color:n,"aria-label":s,"data-testid":"llama-cpp-icon"})}const G0={sm:16,md:20,lg:24};function J0({size:e,color:n,label:s="Anthropic"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"anthropic-icon","aria-label":s,children:t.jsx("path",{d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z",fill:n})})}function lh({size:e,color:n,label:s="OpenAI"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"openai-icon","aria-label":s,children:t.jsx("path",{d:"M22.282 9.821a6 6 0 0 0-.516-4.91a6.05 6.05 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a6 6 0 0 0-3.998 2.9a6.05 6.05 0 0 0 .743 7.097a5.98 5.98 0 0 0 .51 4.911a6.05 6.05 0 0 0 6.515 2.9A6 6 0 0 0 13.26 24a6.06 6.06 0 0 0 5.772-4.206a6 6 0 0 0 3.997-2.9a6.06 6.06 0 0 0-.747-7.073M13.26 22.43a4.48 4.48 0 0 1-2.876-1.04l.141-.081l4.779-2.758a.8.8 0 0 0 .392-.681v-6.737l2.02 1.168a.07.07 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494M3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085l4.783 2.759a.77.77 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646M2.34 7.896a4.5 4.5 0 0 1 2.366-1.973V11.6a.77.77 0 0 0 .388.677l5.815 3.354l-2.02 1.168a.08.08 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855l-5.833-3.387L15.119 7.2a.08.08 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667m2.01-3.023l-.141-.085l-4.774-2.782a.78.78 0 0 0-.785 0L9.409 9.23V6.897a.07.07 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135l-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.8.8 0 0 0-.393.681zm1.097-2.365l2.602-1.5l2.607 1.5v2.999l-2.597 1.5l-2.607-1.5Z",fill:n})})}function _i({size:e,color:n,label:s="Google Gemini"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"gemini-icon","aria-label":s,children:t.jsx("path",{d:"M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81",fill:n})})}function Y0({size:e,color:n,label:s="Ollama"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"ollama-icon","aria-label":s,children:t.jsx("path",{d:"M16.361 10.26a.894.894 0 0 0-.558.47l-.072.148.001.207c0 .193.004.217.059.353.076.193.152.312.291.448.24.238.51.3.872.205a.86.86 0 0 0 .517-.436.752.752 0 0 0 .08-.498c-.064-.453-.33-.782-.724-.897a1.06 1.06 0 0 0-.466 0zm-9.203.005c-.305.096-.533.32-.65.639a1.187 1.187 0 0 0-.06.52c.057.309.31.59.598.667.362.095.632.033.872-.205.14-.136.215-.255.291-.448.055-.136.059-.16.059-.353l.001-.207-.072-.148a.894.894 0 0 0-.565-.472 1.02 1.02 0 0 0-.474.007Zm4.184 2c-.131.071-.223.25-.195.383.031.143.157.288.353.407.105.063.112.072.117.136.004.038-.01.146-.029.243-.02.094-.036.194-.036.222.002.074.07.195.143.253.064.052.076.054.255.059.164.005.198.001.264-.03.169-.082.212-.234.15-.525-.052-.243-.042-.28.087-.355.137-.08.281-.219.324-.314a.365.365 0 0 0-.175-.48.394.394 0 0 0-.181-.033c-.126 0-.207.03-.355.124l-.085.053-.053-.032c-.219-.13-.259-.145-.391-.143a.396.396 0 0 0-.193.032zm.39-2.195c-.373.036-.475.05-.654.086-.291.06-.68.195-.951.328-.94.46-1.589 1.226-1.787 2.114-.04.176-.045.234-.045.53 0 .294.005.357.043.524.264 1.16 1.332 2.017 2.714 2.173.3.033 1.596.033 1.896 0 1.11-.125 2.064-.727 2.493-1.571.114-.226.169-.372.22-.602.039-.167.044-.23.044-.523 0-.297-.005-.355-.045-.531-.288-1.29-1.539-2.304-3.072-2.497a6.873 6.873 0 0 0-.855-.031zm.645.937a3.283 3.283 0 0 1 1.44.514c.223.148.537.458.671.662.166.251.26.508.303.82.02.143.01.251-.043.482-.08.345-.332.705-.672.957a3.115 3.115 0 0 1-.689.348c-.382.122-.632.144-1.525.138-.582-.006-.686-.01-.853-.042-.57-.107-1.022-.334-1.35-.68-.264-.28-.385-.535-.45-.946-.03-.192.025-.509.137-.776.136-.326.488-.73.836-.963.403-.269.934-.46 1.422-.512.187-.02.586-.02.773-.002zm-5.503-11a1.653 1.653 0 0 0-.683.298C5.617.74 5.173 1.666 4.985 2.819c-.07.436-.119 1.04-.119 1.503 0 .544.064 1.24.155 1.721.02.107.031.202.023.208a8.12 8.12 0 0 1-.187.152 5.324 5.324 0 0 0-.949 1.02 5.49 5.49 0 0 0-.94 2.339 6.625 6.625 0 0 0-.023 1.357c.091.78.325 1.438.727 2.04l.13.195-.037.064c-.269.452-.498 1.105-.605 1.732-.084.496-.095.629-.095 1.294 0 .67.009.803.088 1.266.095.555.288 1.143.503 1.534.071.128.243.393.264.407.007.003-.014.067-.046.141a7.405 7.405 0 0 0-.548 1.873c-.062.417-.071.552-.071.991 0 .56.031.832.148 1.279L3.42 24h1.478l-.05-.091c-.297-.552-.325-1.575-.068-2.597.117-.472.25-.819.498-1.296l.148-.29v-.177c0-.165-.003-.184-.057-.293a.915.915 0 0 0-.194-.25 1.74 1.74 0 0 1-.385-.543c-.424-.92-.506-2.286-.208-3.451.124-.486.329-.918.544-1.154a.787.787 0 0 0 .223-.531c0-.195-.07-.355-.224-.522a3.136 3.136 0 0 1-.817-1.729c-.14-.96.114-2.005.69-2.834.563-.814 1.353-1.336 2.237-1.475.199-.033.57-.028.776.01.226.04.367.028.512-.041.179-.085.268-.19.374-.431.093-.215.165-.333.36-.576.234-.29.46-.489.822-.729.413-.27.884-.467 1.352-.561.17-.035.25-.04.569-.04.319 0 .398.005.569.04a4.07 4.07 0 0 1 1.914.997c.117.109.398.457.488.602.034.057.095.177.132.267.105.241.195.346.374.43.14.068.286.082.503.045.343-.058.607-.053.943.016 1.144.23 2.14 1.173 2.581 2.437.385 1.108.276 2.267-.296 3.153-.097.15-.193.27-.333.419-.301.322-.301.722-.001 1.053.493.539.801 1.866.708 3.036-.062.772-.26 1.463-.533 1.854a2.096 2.096 0 0 1-.224.258.916.916 0 0 0-.194.25c-.054.109-.057.128-.057.293v.178l.148.29c.248.476.38.823.498 1.295.253 1.008.231 2.01-.059 2.581a.845.845 0 0 0-.044.098c0 .006.329.009.732.009h.73l.02-.074.036-.134c.019-.076.057-.3.088-.516.029-.217.029-1.016 0-1.258-.11-.875-.295-1.57-.597-2.226-.032-.074-.053-.138-.046-.141.008-.005.057-.074.108-.152.376-.569.607-1.284.724-2.228.031-.26.031-1.378 0-1.628-.083-.645-.182-1.082-.348-1.525a6.083 6.083 0 0 0-.329-.7l-.038-.064.131-.194c.402-.604.636-1.262.727-2.04a6.625 6.625 0 0 0-.024-1.358 5.512 5.512 0 0 0-.939-2.339 5.325 5.325 0 0 0-.95-1.02 8.097 8.097 0 0 1-.186-.152.692.692 0 0 1 .023-.208c.208-1.087.201-2.443-.017-3.503-.19-.924-.535-1.658-.98-2.082-.354-.338-.716-.482-1.15-.455-.996.059-1.8 1.205-2.116 3.01a6.805 6.805 0 0 0-.097.726c0 .036-.007.066-.015.066a.96.96 0 0 1-.149-.078A4.857 4.857 0 0 0 12 3.03c-.832 0-1.687.243-2.456.698a.958.958 0 0 1-.148.078c-.008 0-.015-.03-.015-.066a6.71 6.71 0 0 0-.097-.725C8.997 1.392 8.337.319 7.46.048a2.096 2.096 0 0 0-.585-.041Zm.293 1.402c.248.197.523.759.682 1.388.03.113.06.244.069.292.007.047.026.152.041.233.067.365.098.76.102 1.24l.002.475-.12.175-.118.178h-.278c-.324 0-.646.041-.954.124l-.238.06c-.033.007-.038-.003-.057-.144a8.438 8.438 0 0 1 .016-2.323c.124-.788.413-1.501.696-1.711.067-.05.079-.049.157.013zm9.825-.012c.17.126.358.46.498.888.28.854.36 2.028.212 3.145-.019.14-.024.151-.057.144l-.238-.06a3.693 3.693 0 0 0-.954-.124h-.278l-.119-.178-.119-.175.002-.474c.004-.669.066-1.19.214-1.772.157-.623.434-1.185.68-1.382.078-.062.09-.063.159-.012z",fill:n})})}function ch({size:e,color:n,label:s="MiniMax"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"minimax-icon","aria-label":s,children:t.jsx("path",{d:"M11.43 3.92a.86.86 0 1 0-1.718 0v14.236a1.999 1.999 0 0 1-3.997 0V9.022a.86.86 0 1 0-1.718 0v3.87a1.999 1.999 0 0 1-3.997 0V11.49a.57.57 0 0 1 1.139 0v1.404a.86.86 0 0 0 1.719 0V9.022a1.999 1.999 0 0 1 3.997 0v9.134a.86.86 0 0 0 1.719 0V3.92a1.998 1.998 0 1 1 3.996 0v11.788a.57.57 0 1 1-1.139 0zm10.572 3.105a2 2 0 0 0-1.999 1.997v7.63a.86.86 0 0 1-1.718 0V3.923a1.999 1.999 0 0 0-3.997 0v16.16a.86.86 0 0 1-1.719 0V18.08a.57.57 0 1 0-1.138 0v2a1.998 1.998 0 0 0 3.996 0V3.92a.86.86 0 0 1 1.719 0v12.73a1.999 1.999 0 0 0 3.996 0V9.023a.86.86 0 1 1 1.72 0v6.686a.57.57 0 0 0 1.138 0V9.022a2 2 0 0 0-1.998-1.997",fill:n})})}function Q0({size:e,color:n,label:s="Z.ai"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"zai-icon","aria-label":s,children:t.jsx("path",{d:"M3 5H21V8.5L7 17.5H21V21H3V17.5L17 8.5H3Z",fill:n})})}function Oc({size:e,color:n,label:s="Kimi"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"kimi-icon","aria-label":s,children:t.jsx("path",{d:"M12 3a9 9 0 1 0 9 9c0-.46-.04-.92-.1-1.36a5.39 5.39 0 0 1-4.4 2.26 5.4 5.4 0 0 1-3.14-9.8c.2-.07.4-.1.64-.1z",fill:n})})}function dh({size:e,color:n,label:s="Amazon Bedrock"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"bedrock-icon","aria-label":s,children:t.jsx("path",{d:"M.045 18.02c.072-.116.187-.124.348-.022 2.344 1.476 4.878 2.212 7.607 2.212 1.86 0 3.68-.398 5.453-1.198.386-.168.71-.298.972-.39.26-.092.478-.113.654-.06.176.052.263.2.263.443 0 .222-.12.453-.358.693-.96.962-2.16 1.71-3.592 2.242A12.126 12.126 0 0 1 7.297 23c-2.456 0-4.583-.665-6.378-1.992a.39.39 0 0 1-.098-.096c-.05-.078-.05-.156 0-.234zm6.609-3.26c0-.37.093-.665.282-.886.188-.222.43-.332.727-.332.282 0 .524.105.726.314.2.21.3.498.3.866v4.116c0 .382-.098.676-.294.882-.196.206-.436.31-.72.31-.294 0-.54-.108-.738-.324-.198-.216-.296-.506-.296-.868v-4.078h.014zm-2.986 2.3c0-.376.096-.672.288-.89.192-.216.434-.324.726-.324.292 0 .534.108.726.324.192.218.288.514.288.89v1.778c0 .376-.096.672-.288.89-.192.216-.434.324-.726.324-.292 0-.534-.108-.726-.324-.192-.218-.288-.514-.288-.89v-1.778zm-2.92 1.334c0-.36.09-.65.27-.868.18-.218.42-.328.722-.328s.544.11.73.328c.186.218.278.508.278.868v.444c0 .36-.092.65-.278.868-.186.218-.428.328-.73.328s-.542-.11-.722-.328c-.18-.218-.27-.508-.27-.868v-.444zM21.93 16.4c.804.456 1.39.87 1.758 1.242.368.372.552.7.552.984 0 .208-.102.37-.308.488-.206.118-.462.128-.768.032-.306-.096-.674-.316-1.104-.66a12.728 12.728 0 0 1-1.864-1.75c-1.592.644-3.342.966-5.25.966-1.354 0-2.604-.178-3.752-.534a8.103 8.103 0 0 1-.09-.032l.03.012c-.136-.048.056.022-.042-.014-.04-.016-.04-.016 0 0l.012.004-.012-.004c-.32-.122-.528-.222-.624-.3-.096-.078-.144-.178-.144-.3 0-.098.04-.186.122-.264.082-.078.19-.116.326-.116.076 0 .284.054.624.162 1.078.34 2.264.51 3.558.51 1.642 0 3.194-.286 4.658-.856a17.018 17.018 0 0 1-1.904-3.326c-.416-.94-.726-1.86-.93-2.758-.206-.898-.308-1.728-.308-2.49 0-.664.094-1.194.28-1.592.188-.396.456-.594.804-.594.2 0 .392.074.576.224.184.148.312.354.384.614.1.358.178.758.234 1.198.056.44.084.876.084 1.306 0 .898-.116 1.862-.348 2.894-.232 1.032-.614 2.11-1.146 3.234a16.217 16.217 0 0 0 1.916 1.694z",fill:n})})}function uh({size:e,color:n,label:s="xAI"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"xai-icon","aria-label":s,children:t.jsx("path",{d:"M2.21 3l7.964 11.386L2.13 21h1.974l6.843-7.07L17.165 21H22.1l-8.392-11.97L21.17 3h-1.974l-6.349 6.56L6.845 3z",fill:n})})}function mh({size:e,color:n,label:s="Opencode"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"opencode-icon","aria-label":s,children:t.jsx("path",{d:"M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6z",fill:n})})}function Fc({size:e,color:n,label:s="DeepSeek"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"deepseek-icon","aria-label":s,children:t.jsx("path",{d:"M4 12a8 8 0 1 1 12.7 6.4L12 16h4a4 4 0 1 0-1.6 3.2L12 22l7-1-1.2-3.6A10 10 0 1 0 2 12z",fill:n})})}function hh({size:e,color:n,label:s="Cloudflare"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"cloudflare-icon","aria-label":s,children:t.jsx("path",{d:"M7 16.5h10.8a2.9 2.9 0 0 0 .3-5.8 4.9 4.9 0 0 0-9.3-1.6A3.6 3.6 0 0 0 7 16.5m-1.9 0h3.2a2.5 2.5 0 0 0 .2-5 3.4 3.4 0 0 0-3.4 3.4c0 .6 0 1 .2 1.6",fill:n})})}function Kr({size:e,color:n,label:s="Qwen"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"qwen-icon","aria-label":s,children:[t.jsx("circle",{cx:"11",cy:"12",r:"7.5",stroke:n,strokeWidth:"2",fill:"none"}),t.jsx("path",{d:"M14 15 L21 22",stroke:n,strokeWidth:"2.6",strokeLinecap:"round"})]})}function ph({size:e,color:n,label:s="LM Studio"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"lmstudio-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"4.5",fill:n}),t.jsx("text",{x:"12",y:"16",textAnchor:"middle",fontFamily:"-apple-system, system-ui, sans-serif",fontSize:"9.5",fontWeight:"700",fill:"var(--provider-icon-contrast)",letterSpacing:"-0.4",children:"LM"})]})}function zc({size:e,color:n,label:s="Hugging Face"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"huggingface-icon","aria-label":s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"9",fill:n}),t.jsx("circle",{cx:"8.5",cy:"10.5",r:"1.4",fill:"var(--provider-icon-contrast)"}),t.jsx("circle",{cx:"15.5",cy:"10.5",r:"1.4",fill:"var(--provider-icon-contrast)"}),t.jsx("path",{d:"M7.5 14.5 Q12 18.5 16.5 14.5",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.6",strokeLinecap:"round",fill:"none"}),t.jsx("path",{d:"M3.5 16 Q5 13.5 7 14.5 M20.5 16 Q19 13.5 17 14.5",stroke:n,strokeWidth:"1.8",strokeLinecap:"round",fill:"none"})]})}function fh({size:e,color:n,label:s="Mistral AI"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"mistral-icon","aria-label":s,children:t.jsx("path",{d:"M2 4h3v16H2zM7 4h3v12H7zM12 4h3v16h-3zM17 4h3v8h-3zM7 16h3v4H7zM17 8h3v12h-3z",fill:n})})}function Bc({size:e,color:n,label:s="Azure"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"azure-icon","aria-label":s,children:t.jsx("path",{d:"M10.4 3.2 4.5 16.6l3.5.5L13 6 9.6 19.5h9.9zM3 19.5l4.6.6 8.6-1.7-7-1.6z",fill:n})})}function X0({size:e,color:n,label:s="Cerebras"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"cerebras-icon","aria-label":s,children:[t.jsx("path",{d:"M19.5 6.5A8.5 8.5 0 1 0 19.5 17.5",stroke:n,strokeWidth:"2.4",strokeLinecap:"round",fill:"none"}),t.jsx("path",{d:"M16.5 9A4.6 4.6 0 1 0 16.5 15",stroke:n,strokeWidth:"1.8",strokeLinecap:"round",fill:"none"}),t.jsx("circle",{cx:"11",cy:"12",r:"1.6",fill:n})]})}function Z0({size:e,color:n,label:s="Groq"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"groq-icon","aria-label":s,children:t.jsx("path",{d:"M14 2 4 13h6l-2 9 10-11h-6z",fill:n})})}function gh({size:e,color:n,label:s="Vercel"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"vercel-icon","aria-label":s,children:t.jsx("path",{d:"M12 2 22 21H2z",fill:n})})}function Uc({size:e,color:n,label:s="Fireworks AI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"fireworks-icon","aria-label":s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"2.4",fill:n}),t.jsx("circle",{cx:"12",cy:"3.5",r:"1.4",fill:n}),t.jsx("circle",{cx:"12",cy:"20.5",r:"1.4",fill:n}),t.jsx("circle",{cx:"3.5",cy:"12",r:"1.4",fill:n}),t.jsx("circle",{cx:"20.5",cy:"12",r:"1.4",fill:n}),t.jsx("circle",{cx:"6",cy:"6",r:"1.2",fill:n}),t.jsx("circle",{cx:"18",cy:"6",r:"1.2",fill:n}),t.jsx("circle",{cx:"6",cy:"18",r:"1.2",fill:n}),t.jsx("circle",{cx:"18",cy:"18",r:"1.2",fill:n}),t.jsx("path",{d:"M12 5.5v3M12 15.5v3M5.5 12h3M15.5 12h3",stroke:n,strokeWidth:"1.4",strokeLinecap:"round"})]})}function eC({size:e,color:n,label:s="OpenRouter"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"openrouter-icon","aria-label":s,children:t.jsx("path",{d:"M12 2.5a9.5 9.5 0 1 0 9.5 9.5h-2.7a6.8 6.8 0 1 1-2-4.8l-3.1 3.1H22V2.5l-3.2 3.2A9.45 9.45 0 0 0 12 2.5",fill:n})})}function bh({size:e,color:n,label:s="GitHub"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"github-icon","aria-label":s,children:t.jsx("path",{d:"M12 0a12 12 0 0 0-3.79 23.39c.6.11.82-.26.82-.58v-2.23c-3.34.73-4.04-1.41-4.04-1.41-.55-1.39-1.34-1.76-1.34-1.76-1.09-.75.08-.74.08-.74 1.2.08 1.84 1.24 1.84 1.24 1.08 1.84 2.82 1.31 3.5 1 .1-.78.42-1.31.77-1.62-2.67-.3-5.47-1.34-5.47-5.95 0-1.31.47-2.38 1.24-3.22-.12-.31-.54-1.56.12-3.24 0 0 1.01-.32 3.3 1.23a11.3 11.3 0 0 1 6 0c2.29-1.55 3.3-1.23 3.3-1.23.66 1.68.24 2.93.12 3.24.77.84 1.24 1.91 1.24 3.22 0 4.62-2.8 5.64-5.48 5.94.43.37.82 1.1.82 2.22v3.29c0 .32.22.69.83.58A12 12 0 0 0 12 0",fill:n})})}function Hc({size:e,color:n,label:s="Hermes"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 64 64",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":s,children:[t.jsx("rect",{x:"30",y:"10",width:"4",height:"46",rx:"2",fill:n}),t.jsx("path",{d:"M30 18 C24 14, 14 14, 10 18 C14 16, 22 16, 28 20",fill:n,opacity:"0.9"}),t.jsx("path",{d:"M30 22 C26 19, 18 19, 14 22 C18 20, 24 20, 28 24",fill:n,opacity:"0.7"}),t.jsx("path",{d:"M34 18 C40 14, 50 14, 54 18 C50 16, 42 16, 36 20",fill:n,opacity:"0.9"}),t.jsx("path",{d:"M34 22 C38 19, 46 19, 50 22 C46 20, 40 20, 36 24",fill:n,opacity:"0.7"}),t.jsx("path",{d:"M32 48 C22 44, 20 38, 26 34 C20 36, 18 42, 24 46 C18 40, 22 30, 30 28 C24 32, 22 38, 28 42",fill:"none",stroke:n,strokeWidth:"2.5",strokeLinecap:"round"}),t.jsx("path",{d:"M32 48 C42 44, 44 38, 38 34 C44 36, 46 42, 40 46 C46 40, 42 30, 34 28 C40 32, 42 38, 36 42",fill:"none",stroke:n,strokeWidth:"2.5",strokeLinecap:"round",opacity:"0.8"}),t.jsx("circle",{cx:"32",cy:"10",r:"4",fill:n})]})}function xh({size:e,label:n="OpenClaw"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":n,children:[t.jsx("rect",{width:"16",height:"16",fill:"none"}),t.jsxs("g",{fill:"#3a0a0d",children:[t.jsx("rect",{x:"1",y:"5",width:"1",height:"3"}),t.jsx("rect",{x:"2",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"2",y:"8",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"3",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"9",width:"1",height:"1"}),t.jsx("rect",{x:"4",y:"2",width:"1",height:"1"}),t.jsx("rect",{x:"4",y:"10",width:"1",height:"1"}),t.jsx("rect",{x:"5",y:"2",width:"6",height:"1"}),t.jsx("rect",{x:"11",y:"2",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"3",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"9",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"8",width:"1",height:"1"}),t.jsx("rect",{x:"14",y:"5",width:"1",height:"3"}),t.jsx("rect",{x:"5",y:"11",width:"6",height:"1"}),t.jsx("rect",{x:"4",y:"12",width:"1",height:"1"}),t.jsx("rect",{x:"11",y:"12",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"13",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"13",width:"1",height:"1"}),t.jsx("rect",{x:"5",y:"14",width:"6",height:"1"})]}),t.jsxs("g",{fill:"#ff4f40",children:[t.jsx("rect",{x:"5",y:"3",width:"6",height:"1"}),t.jsx("rect",{x:"4",y:"4",width:"8",height:"1"}),t.jsx("rect",{x:"3",y:"5",width:"10",height:"1"}),t.jsx("rect",{x:"3",y:"6",width:"10",height:"1"}),t.jsx("rect",{x:"3",y:"7",width:"10",height:"1"}),t.jsx("rect",{x:"4",y:"8",width:"8",height:"1"}),t.jsx("rect",{x:"5",y:"9",width:"6",height:"1"}),t.jsx("rect",{x:"5",y:"12",width:"6",height:"1"}),t.jsx("rect",{x:"6",y:"13",width:"4",height:"1"})]}),t.jsxs("g",{fill:"#ff775f",children:[t.jsx("rect",{x:"1",y:"6",width:"2",height:"1"}),t.jsx("rect",{x:"2",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"2",y:"7",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"6",width:"2",height:"1"}),t.jsx("rect",{x:"13",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"7",width:"1",height:"1"})]}),t.jsxs("g",{fill:"#081016",children:[t.jsx("rect",{x:"6",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"9",y:"5",width:"1",height:"1"})]}),t.jsxs("g",{fill:"#f5fbff",children:[t.jsx("rect",{x:"6",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"9",y:"4",width:"1",height:"1"})]})]})}function qc({size:e,color:n,label:s="Paperclip"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":s,children:t.jsx("path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function vh({size:e,color:n,label:s="Anthropic — via Claude CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"claude-cli-icon","aria-label":s,children:[t.jsx("g",{transform:"translate(-1 -1.5) scale(0.82)",children:t.jsx("path",{d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z",fill:n})}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}function tC({size:e,color:n,label:s="Factory AI — via Droid CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"droid-cli-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"3",width:"14",height:"14",rx:"3",fill:n}),t.jsx("path",{d:"M6.5 7.5h2.6a2.9 2.9 0 1 1 0 5.8H6.5zM9 7.5v5.8",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}function nC({size:e,color:n,label:s="Cursor — via Cursor CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"cursor-cli-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"3",width:"14",height:"14",rx:"3",fill:n}),t.jsx("path",{d:"M10.8 7.2a3.6 3.6 0 1 0 0 5.6",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}const sC={anthropic:{component:J0,color:"var(--provider-anthropic)"},"claude-cli":{component:vh,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:vh,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:tC,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},"cursor-cli":{component:nC,color:"var(--provider-cursor-cli)",label:"Cursor — via Cursor CLI"},"llama-cpp":{component:oh,color:"var(--provider-ollama)",label:"llama.cpp"},"llama-server":{component:oh,color:"var(--provider-ollama)",label:"llama.cpp"},openai:{component:lh,color:"var(--provider-openai)"},"openai-codex":{component:lh,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:_i,color:"var(--provider-gemini)"},gemini:{component:_i,color:"var(--provider-gemini)"},"google-antigravity":{component:_i,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:_i,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:_i,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:_i,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:_i,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:_i,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:_i,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:_i,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:Y0,color:"var(--text)"},github:{component:bh,color:"var(--text)"},"github-copilot":{component:bh,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:eC,color:"var(--provider-openrouter)"},minimax:{component:ch,color:"var(--provider-minimax)"},"minimax-cn":{component:ch,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:Q0,color:"var(--provider-zai)"},kimi:{component:Oc,color:"var(--provider-kimi)"},moonshot:{component:Oc,color:"var(--provider-kimi)"},"kimi-coding":{component:Oc,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:dh,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:dh,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:uh,color:"var(--text)"},grok:{component:uh,color:"var(--text)",label:"xAI"},opencode:{component:mh,color:"var(--provider-opencode)"},"opencode-go":{component:mh,color:"var(--provider-opencode)",label:"Opencode (Go)"},deepseek:{component:Fc,color:"var(--provider-deepseek)",label:"DeepSeek"},"deepseek-ai":{component:Fc,color:"var(--provider-deepseek)",label:"DeepSeek"},"deep-seek":{component:Fc,color:"var(--provider-deepseek)",label:"DeepSeek"},cloudflare:{component:hh,color:"var(--provider-cloudflare)",label:"Cloudflare"},cloudflared:{component:hh,color:"var(--provider-cloudflare)",label:"Cloudflare"},qwen:{component:Kr,color:"var(--provider-qwen)"},"qwen-ai":{component:Kr,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:Kr,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:Kr,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:Kr,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:ph,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:ph,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:zc,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:zc,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:zc,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:fh,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:fh,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:Bc,color:"var(--provider-azure)"},"azure-openai":{component:Bc,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:Bc,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:Uc,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:Uc,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:Uc,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:X0,color:"var(--provider-cerebras)"},groq:{component:Z0,color:"var(--provider-groq)"},vercel:{component:gh,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:gh,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:Hc,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:Hc,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:Hc,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:xh,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:xh,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:qc,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:qc,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:qc,color:"var(--provider-paperclip)",label:"Paperclip"}};function Fn({provider:e,size:n="sm"}){const s=e.toLowerCase(),a=sC[s],r=a?.component,o=a?.color??"var(--text-muted)",l=a?.label,c=G0[n];return t.jsx("span",{className:"provider-icon",style:{color:o},"data-provider":s,children:r?t.jsx(r,{size:c,color:o,label:l}):t.jsx(Wg,{size:c})})}function kb({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),u=i.useRef(!0);i.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const m=i.useCallback(async()=>{try{const b=await iN();return u.current&&r(b),b}catch(b){return u.current&&d({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);i.useEffect(()=>{m()},[m]);const h=i.useCallback(async()=>{l("testing"),d(null),await m(),u.current&&l(null)},[m]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await lN(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,m]),p=a?.binary.available??!1,g=a?.enabled??e,x=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"droid"})," CLI. Uses your existing Factory AI subscription / quota instead of an API key."]}),w=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`droid` binary not detected on PATH — install Droid CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"droid-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(Fn,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(iC,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:w})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[x,t.jsx(yh,{status:a,authenticated:e}),c&&t.jsx(wh,{action:c})]})]})]}):t.jsxs("div",{className:`onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"droid-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(Fn,{provider:"droid-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Factory AI — via Droid CLI"}),x,t.jsx(yh,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:w}),c&&t.jsx(wh,{action:c})]})}function iC({status:e,authenticated:n}){const s=e?.enabled??n,a=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!a&&e?t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not installed"}):t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not connected"})}function yh({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(jt,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:a,extension:r,ready:o}=e;return s.available?a?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"droid"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`droid` not found on PATH"]})}function wh({action:e}){if(e.kind==="error")return t.jsx("p",{className:"onboarding-helper-text onboarding-helper-text--error",children:e.message});const n=e.kind==="enabled"?"Enabled":"Disabled";return t.jsxs("p",{className:"onboarding-helper-text",children:[n,"."," ",e.kind==="enabled"?"Factory AI (via Droid CLI) models are now visible in the model picker.":"Factory AI (via Droid CLI) models are hidden from the model picker.",e.restartRequired?" Restart required: restart your active CLI/chat session for routing changes to take effect.":""]})}function kh({actions:e}){return t.jsx(kb,{compact:!0,authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function aC({actions:e}){return t.jsx(kb,{authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function rC(){return t.jsx("p",{className:"onboarding-helper-text","data-testid":"droid-onboarding-setup-help",children:"Tip: Enable Droid CLI to reuse your Factory AI subscription without adding an API key."})}function oC({actions:e}){return t.jsxs("div",{className:"post-onboarding-recommendations__item","data-testid":"droid-post-onboarding-recommendation",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:"Enable Droid CLI"}),t.jsx("span",{children:"Use your local Droid CLI session as an AI provider in Fusion."})]}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>e?.openSettingsSection?.("authentication"),children:"Open Authentication"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>e?.openModelOnboarding?.(),children:"Open Onboarding"})]})}const lC=[{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-provider-card",componentPath:"./components/settings-provider-card.js",component:kh},{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-integration-card",componentPath:"./components/settings-integration-card.js",component:kh},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-provider-card",componentPath:"./components/onboarding-provider-card.js",component:aC},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-setup-help",componentPath:"./components/onboarding-setup-help.js",component:rC},{pluginId:"fusion-plugin-droid-runtime",slotId:"post-onboarding-recommendation",componentPath:"./components/post-onboarding-recommendation.js",component:oC}];function cC(e){return lC.find(s=>s.pluginId===e.pluginId&&s.slotId===e.slot.slotId&&s.componentPath===e.slot.componentPath)?.component??null}function dC({slotId:e,pluginId:n}){return t.jsxs("section",{className:"plugin-slot-shell","data-plugin-slot":!0,"data-slot-id":e,"data-plugin-id":n,"data-plugin-slot-state":"missing-component",role:"status","aria-live":"polite",children:[t.jsx("p",{className:"plugin-slot-shell__title",children:"Plugin component unavailable"}),t.jsx("p",{className:"plugin-slot-shell__message",children:"The dashboard could not resolve this plugin surface from the static host registry."})]})}function la({slotId:e,projectId:n,pluginIds:s,renderPlaceholder:a=!0,actions:r}){const{getSlotsForId:o,loading:l,error:c}=wb(n);if(l||c||!e)return null;const d=o(e).filter(u=>s&&s.length>0?s.includes(u.pluginId):!0);return d.length===0?null:t.jsx(Fo,{level:"page",children:t.jsx(t.Fragment,{children:d.map((u,m)=>{const h=`${u.pluginId}-${u.slot.slotId}-${m}`,f=cC(u);return f?t.jsx(f,{entry:u,actions:r},h):a?t.jsx(dC,{slotId:u.slot.slotId,pluginId:u.pluginId},h):null})})})}function uC(){return typeof window>"u"?"desktop":window.matchMedia("(max-width: 768px)").matches?"mobile":window.matchMedia("(min-width: 769px) and (max-width: 1024px)").matches?"tablet":"desktop"}function ri(){const[e,n]=i.useState(uC);return i.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(max-width: 768px)"),a=window.matchMedia("(min-width: 769px) and (max-width: 1024px)"),r=()=>{s.matches?n("mobile"):a.matches?n("tablet"):n("desktop")};return s.addEventListener("change",r),a.addEventListener("change",r),()=>{s.removeEventListener("change",r),a.removeEventListener("change",r)}},[]),e}function Dr(e){return e.replace(/\\/g,"/")}function Bu(e){return e.replace(/[\\/]+$/g,"")}function Uu(e){const n=Dr(Bu(e));return n?n.split("/").filter(Boolean):[]}function Hu(e){const n=Dr(Bu(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function jb(e,n){const s=Uu(e);return s.length===0?Dr(e):s.slice(-2).join("/")}function mC(e){const n=Dr(Bu(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function hC(e,n){return!e||e==="."?n:[...Uu(e),n].join("/")}function pC(e){const n=Uu(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function X5(e){const n=Dr(e),s=n.match(/^([A-Za-z]:)(?:\/(.*))?$/);if(s){const r=`${s[1]}/`,o=(s[2]??"").split("/").filter(Boolean),l=[{label:s[1],path:r}];for(let c=0;c<o.length;c+=1)l.push({label:o[c],path:`${r}${o.slice(0,c+1).join("/")}`});return l}if(n.startsWith("/")){const r=n.split("/").filter(Boolean),o=[{label:"/",path:"/"}];for(let l=0;l<r.length;l+=1)o.push({label:r[l],path:`/${r.slice(0,l+1).join("/")}`});return o}const a=n.split("/").filter(Boolean);return a.map((r,o)=>({label:r,path:a.slice(0,o+1).join("/")}))}const qu=new Map;function Wo(e,n){return`plugin:${e}:${n}`}function Nb(e){const n=/^plugin:([^:]+):(.+)$/u.exec(e);return n?{pluginId:n[1],viewId:n[2]}:null}function fr(e){return Nb(e)!==null}function sl(e,n,s){qu.set(Wo(e,n),s)}function fC(e,n){return qu.get(Wo(e,n))??null}function Sb(e,n){return qu.has(Wo(e,n))}function Vc({viewId:e}){return t.jsxs("section",{className:"card plugin-dashboard-view-missing","data-testid":"plugin-view-unavailable",children:[t.jsxs("h2",{className:"plugin-dashboard-view-missing-title",children:[t.jsx(Oo,{}),"Plugin view unavailable"]}),t.jsxs("p",{className:"plugin-dashboard-view-missing-description",children:["No host registration found for ",t.jsx("code",{children:e}),"."]})]})}function gC({viewId:e,context:n}){const s=Nb(e);if(!s)return t.jsx(Vc,{viewId:e});const a=fC(s.pluginId,s.viewId);return a?t.jsx(Fo,{fallback:t.jsx(Vc,{viewId:e}),children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(a,{context:n})})}):t.jsx(Vc,{viewId:e})}const yo=Wo,bC={activity:Ys,bot:Kn,brain:So,checksquare:$u,clock:Ji,filetext:ua,folder:Es,gitbranch:Fs,grid3x3:uc,layoutgrid:ma,mail:Da,map:sk,messagesquare:Ki,monitor:yr,search:Wi,sparkles:gs,target:Rs,workflow:Bl,zap:as};function xC(e){return(e??"").trim().toLowerCase().replace(/[-_\s]/g,"")}function Vl(e){return bC[xC(e)]??uc}const il="__fusion:no-branch__",Cb={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function vC({projects:e,currentProject:n,onViewAll:s,onSelectProject:a}){const[r,o]=i.useState(!1),l=i.useRef(null);i.useEffect(()=>{if(!r)return;const d=u=>{l.current&&!l.current.contains(u.target)&&o(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[r]),i.useEffect(()=>{if(!r)return;const d=u=>{u.key==="Escape"&&o(!1)};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[r]);const c=i.useCallback(d=>{a?.(d),o(!1)},[a]);return t.jsx("div",{className:"project-selector",ref:l,children:e.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:`project-selector-trigger${r?" project-selector-trigger--open":""}`,onClick:()=>o(d=>!d),title:n?.name?`Switch project (current: ${n.name})`:"Switch project","aria-label":"Switch project","aria-expanded":r,"aria-haspopup":"listbox","data-testid":"project-selector-trigger",children:[t.jsx("span",{className:"project-selector-trigger-label",children:n?.name??"Projects"}),t.jsx(pn,{size:12,className:`project-selector-chevron${r?" project-selector-chevron--open":""}`})]}),r&&t.jsxs("div",{className:"project-selector-dropdown",role:"listbox","aria-label":"Select project","data-testid":"project-selector-dropdown",children:[e.map(d=>{const u=n?.id===d.id,m=Cb[d.status]?.color;return t.jsxs("button",{className:`project-selector-item${u?" project-selector-item--current":""}`,onClick:()=>c(d),role:"option","aria-selected":u,children:[t.jsx("span",{className:"project-selector-dot",style:{backgroundColor:m||"var(--text-muted)"}}),t.jsxs("div",{className:"project-selector-info",children:[t.jsx("span",{className:"project-selector-name",children:d.name}),t.jsx("span",{className:"project-selector-path",children:jb(d.path)})]}),u&&t.jsx(js,{size:14,className:"project-selector-check"})]},d.id)}),t.jsx("div",{className:"project-selector-divider",role:"presentation"}),t.jsx("button",{className:"project-selector-manage",onClick:()=>{s(),o(!1)},"data-testid":"manage-projects-action",children:"Manage Projects"})]})]})})}function jh({size:e=16}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:t.jsx("path",{d:"M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.203 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.942.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"})})}function yC({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:a,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,mailboxPendingApprovalCount:m=0,chatHasUnreadResponse:h=!1,stashOrphanCount:f=0,onOpenSchedules:p,onOpenGitManager:g,onOpenNodes:x,showNodesButton:w,onOpenWorkflowSteps:b,onOpenScripts:y,onRunScript:S,onToggleTerminal:j,onOpenFiles:C,filesOpen:v,onOpenTodos:N,todosOpen:I,todosEnabled:F,globalPaused:_,enginePaused:M,onToggleGlobalPause:z,onToggleEnginePause:U,view:R="board",onChangeView:D,showSkillsTab:K,showAgentsTab:Z,searchQuery:ne="",onSearchChange:O,branchFilter:A="",baseBranchFilter:P="",branchOptions:$=[],baseBranchOptions:k=[],onBranchFilterChange:J,onBaseBranchFilterChange:ce,projects:je=[],currentProject:He,onSelectProject:xe,onViewAllProjects:Ne,projectId:Y,shellHost:ie={kind:"browser"},mobileNavEnabled:ee,availableNodes:oe=[],currentNode:W,onSelectNode:L,isRemote:pe=!1,experimentalFeatures:fe,pluginDashboardViews:B=[],shellConnectionControl:ve}){const Fe=ri(),ae=Fe==="mobile",Pe=ae||Fe==="tablet",nt=ae&&ee,[Be,de]=i.useState(!1),[Ie,$e]=i.useState(!1),[st,Ue]=i.useState(!1),[me,re]=i.useState(!1),[_e,xt]=i.useState(!1),[ut,Qe]=i.useState(!1),[vt,Ae]=i.useState(!1),[Je,dt]=i.useState(!1),[Nt,yt]=i.useState(!1),[Se,G]=i.useState(!1),[ge,pt]=i.useState(!1),[ke,tt]=i.useState({}),[Rt,Re]=i.useState(!1),[be,rt]=i.useState(-1),[lt,gt]=i.useState(null),[St,Lt]=i.useState({}),[Yt,tn]=i.useState(!1),mn=i.useRef(null),Qt=i.useRef(null),yn=i.useRef(null),Gt=i.useRef(null),on=i.useRef(null),sn=i.useRef(null),ln=i.useRef(!1),Wt=i.useRef(null),ye=i.useRef(null),Le=i.useRef(null),Ke=i.useRef(null),mt=i.useRef(null),Ve=i.useRef(null),Pt=i.useRef(null),Ot=i.useRef(null),bt=i.useRef(!1),Dt=i.useMemo(()=>oe.filter(le=>le.type==="remote"),[oe]),Ft=Dt.length>0,Ht=i.useMemo(()=>Object.entries(ke).sort(([le],[ct])=>le.localeCompare(ct)),[ke]),rn=Ht.length>0,Xt=Ht.length+(rn?1:0),an=i.useMemo(()=>Object.entries(St).sort(([le],[ct])=>le.localeCompare(ct)),[St]),Me=i.useMemo(()=>!!(D||fe?.researchView||F||fe?.insights||K||fe?.memoryView||fe?.devServerView||!nt||B.some(le=>le.view.placement!=="primary")),[D,fe,F,K,nt,B]),it=i.useCallback(()=>{const le=window.visualViewport;return le&&le.width>0&&le.height>0?{width:le.width,height:le.height,offsetTop:le.offsetTop,offsetLeft:le.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),kt=i.useCallback(()=>{const le=Pt.current;if(!le)return;const ct=le.getBoundingClientRect(),nn=Ot.current,{width:Rn,height:Un,offsetTop:wn,offsetLeft:rs}=it(),_s=16,bn=16,Ut=6,xs=nn?.offsetWidth||Math.max(ct.width,260),xn=Math.min(xs,Math.max(Rn-_s*2,160)),Xn=nn?.offsetHeight||280,$n=Math.min(Xn,Math.max(Un-bn*2,160)),vs=ct.top-wn,ms=ct.bottom-wn,hs=ct.right-rs,Jn=Un-ms,ps=vs,Ns=Jn<$n&&ps>Jn,Yn=Math.min(Math.max(hs-xn,_s),Rn-_s-xn)+rs,ys=Ns?Math.max(bn+wn,vs-$n-Ut+wn):Math.min(ms+Ut+wn,Un+wn-bn-$n);gt({top:ys,left:Yn,width:xn})},[it]),$t=i.useCallback((le,ct)=>{S?.(le,ct),pt(!1),rt(-1)},[S]),se=i.useCallback(()=>{y?.(),pt(!1),rt(-1)},[y]),te=i.useCallback(le=>{switch(le.key){case"ArrowDown":le.preventDefault(),Xt>0&&rt(ct=>ct<Xt-1?ct+1:0);break;case"ArrowUp":le.preventDefault(),Xt>0&&rt(ct=>ct>0?ct-1:Xt-1);break;case"Enter":if(le.preventDefault(),be>=0)if(be<Ht.length){const[ct,nn]=Ht[be];$t(ct,nn)}else rn&&be===Ht.length&&se();break;case"Home":le.preventDefault(),Xt>0&&rt(0);break;case"End":le.preventDefault(),Xt>0&&rt(Xt-1);break}},[se,$t,be,Ht,rn,Xt]);i.useEffect(()=>{ln.current=_e},[_e]),i.useEffect(()=>{bt.current=ge},[ge]),i.useEffect(()=>{if(!_e||!Pe)return;let le=!1;return tn(!0),_o(Y).then(ct=>{le||Lt(ct)}).catch(()=>{le||Lt({})}).finally(()=>{le||tn(!1)}),()=>{le=!0}},[_e,Pe,Y]),i.useEffect(()=>{if(!ge||Pe)return;let le=!1;return Re(!0),_o(Y).then(ct=>{le||tt(ct)}).catch(()=>{le||tt({})}).finally(()=>{le||Re(!1)}),()=>{le=!0}},[ge,Pe,Y]),i.useEffect(()=>{if(!ge)return;const le=ct=>{Ve.current&&!Ve.current.contains(ct.target)&&pt(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[ge]),i.useEffect(()=>{if(!ge)return;const le=ct=>{ct.key==="Escape"&&(pt(!1),Pt.current?.focus())};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[ge]),i.useEffect(()=>{if(ge){rt(-1);const le=window.setTimeout(()=>Ot.current?.focus(),0);return()=>window.clearTimeout(le)}gt(null)},[ge]),i.useEffect(()=>{if(!ge)return;const le=requestAnimationFrame(()=>{kt()});return()=>cancelAnimationFrame(le)},[ge,Rt,Ht.length,rn,kt]),i.useEffect(()=>{if(!ge)return;const le=()=>kt();window.addEventListener("resize",le),window.addEventListener("scroll",le,!0);const ct=window.visualViewport;return ct&&(ct.addEventListener("resize",le),ct.addEventListener("scroll",le)),()=>{window.removeEventListener("resize",le),window.removeEventListener("scroll",le,!0),ct&&(ct.removeEventListener("resize",le),ct.removeEventListener("scroll",le))}},[ge,kt]),i.useEffect(()=>{Pe&&(pt(!1),rt(-1))},[Pe]);const De=Be||ne.length>0,ft=(Ie||ne.length>0)&&!st,qt=(R==="board"||R==="list")&&!ae&&O&&!st&&ne.length===0,zt=(R==="board"||R==="list")&&!ae&&O,Pn=R==="board";i.useEffect(()=>{ne===""&&Ue(!1)},[ne]),i.useEffect(()=>{if(!me)return;const le=ct=>{Qt.current&&!Qt.current.contains(ct.target)&&mn.current&&!mn.current.contains(ct.target)&&re(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[me]),i.useEffect(()=>{if(!Nt)return;const le=ct=>{Gt.current&&!Gt.current.contains(ct.target)&&yn.current&&!yn.current.contains(ct.target)&&yt(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[Nt]),i.useEffect(()=>{if(!ut)return;const le=ct=>{Wt.current&&!Wt.current.contains(ct.target)&&Qe(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[ut]),i.useEffect(()=>{const le=ct=>{if(ct.key==="Escape"){if(dt(!1),yt(!1),ln.current){xt(!1);return}if(bt.current){pt(!1),Pt.current?.focus();return}re(!1),de(!1),Qe(!1),Ae(!1)}};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[]),i.useEffect(()=>{if(!vt)return;const le=ct=>{ye.current&&!ye.current.contains(ct.target)&&Ae(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[vt]),i.useEffect(()=>{if(!Se)return;const le=ct=>{mt.current&&!mt.current.contains(ct.target)&&G(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[Se]),i.useEffect(()=>{if(!Se)return;const le=ct=>{ct.key==="Escape"&&G(!1)};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[Se]),i.useEffect(()=>{if(!Je)return;const le=ct=>{Le.current&&!Le.current.contains(ct.target)&&Ke.current&&!Ke.current.contains(ct.target)&&dt(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[Je]);const he=i.useCallback(()=>{de(le=>!le)},[]),ht=i.useCallback(()=>{$e(!0),Ue(!1)},[]),at=i.useCallback(()=>{$e(!1),Ue(!0),O&&O("")},[O]),wt=i.useCallback(()=>{re(le=>!le)},[]),Xe=i.useCallback(le=>{le&&le(),re(!1),xt(!1)},[]),Et=i.useCallback(()=>{de(!1),O&&O("")},[O]),Zt=ie.kind==="desktop-shell";return t.jsxs("div",{className:"header-wrapper",children:[t.jsxs("header",{className:"header","data-shell-kind":ie.kind,children:[t.jsxs("div",{className:"header-left",children:[t.jsxs("div",{className:"header-brand",children:[t.jsxs("svg",{className:"header-logo",width:24,height:24,viewBox:"0 0 128 128",fill:"none","aria-label":"Fusion logo",role:"img",children:[t.jsx("circle",{cx:"64",cy:"64",r:"52",stroke:"currentColor",strokeWidth:"8"}),t.jsx("path",{d:"M26 101C44 82 62 64 82 45C90 37 98 30 104 24C96 35 89 47 81 60C70 79 57 95 43 108C38 112 32 108 26 101Z",fill:"currentColor"})]}),t.jsx("h1",{className:"logo",children:"Fusion"})]}),ae&&je.length>=1&&xe&&t.jsxs("div",{className:"mobile-project-switch",ref:ye,children:[t.jsx("button",{className:`mobile-project-switch-trigger${vt?" mobile-project-switch-trigger--open":""}`,onClick:()=>Ae(le=>!le),title:"Switch project","aria-label":"Switch project","aria-expanded":vt,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(pn,{size:14,className:`mobile-project-switch-chevron${vt?" mobile-project-switch-chevron--open":""}`})}),vt&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:je.map(le=>{const ct=He?.id===le.id,nn=Cb[le.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${ct?" mobile-project-switch-item--current":""}`,onClick:()=>{xe(le),Ae(!1)},role:"option","aria-selected":ct,"data-testid":`mobile-project-switch-item-${le.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:nn||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:le.name}),t.jsx("span",{className:"mobile-project-switch-path",children:jb(le.path)})]}),ct&&t.jsx(js,{size:14,className:"mobile-project-switch-check"})]},le.id)})})]}),!Pe&&je.length>=1&&Ne&&t.jsx(vC,{projects:je,currentProject:He??null,onViewAll:Ne,onSelectProject:xe}),Ft&&t.jsxs("div",{className:`header-node-selector${ae?" header-node-selector--mobile":""}`,ref:ae?void 0:Wt,children:[t.jsx(V0,{node:W??null,showDetails:!ae}),!ae&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${ut?" node-selector-trigger--open":""}`,onClick:()=>Qe(le=>!le),title:"Switch node","aria-label":"Switch node","aria-expanded":ut,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(On,{size:12,className:`node-selector-chevron${ut?" node-selector-chevron--open":""}`})}),ut&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${pe?"":" node-selector-option--active"}`,onClick:()=>{L?.(null),Qe(!1)},role:"option","aria-selected":!pe,"data-testid":"node-option-local",children:[t.jsx(Oa,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Dt.map(le=>t.jsxs("button",{className:`node-selector-option${W?.id===le.id?" node-selector-option--active":""}`,onClick:()=>{L?.(le),Qe(!1)},role:"option","aria-selected":W?.id===le.id,"data-testid":`node-option-${le.id}`,children:[t.jsx(Oa,{status:le.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:le.name}),t.jsx("span",{className:"node-selector-option-status",children:le.status})]},le.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[ve,nt&&D&&(R==="board"||R==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${R==="board"?" active":""}`,onClick:()=>D("board"),title:"Board view","aria-label":"Board view","aria-pressed":R==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(ma,{size:16})}),t.jsx("button",{className:`view-toggle-btn${R==="list"?" active":""}`,onClick:()=>D("list"),title:"List view","aria-label":"List view","aria-pressed":R==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(Zd,{size:16})})]}),O&&ae&&(nt||R==="board"||R==="list")&&!De&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:he,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Wi,{size:16})}),qt&&t.jsx("button",{className:"btn-icon",onClick:ht,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Wi,{size:16})}),ae&&nt&&o&&t.jsx("button",{className:"btn-icon",onClick:le=>o(le.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ys,{size:16})}),!nt&&D&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${R==="board"?" active":""}`,onClick:()=>D("board"),title:"Board view","aria-label":"Board view","aria-pressed":R==="board",children:t.jsx(ma,{size:16})}),t.jsx("button",{className:`view-toggle-btn${R==="list"?" active":""}`,onClick:()=>D("list"),title:"List view","aria-label":"List view","aria-pressed":R==="list",children:t.jsx(Zd,{size:16})}),Z&&t.jsx("button",{className:`view-toggle-btn${R==="agents"?" active":""}`,onClick:()=>D("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":R==="agents",children:t.jsx(Kn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${R==="missions"?" active":""}`,onClick:()=>D("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":R==="missions",children:t.jsx(Rs,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${R==="chat"?" active":""}`,onClick:()=>D("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":R==="chat","data-testid":"header-chat-view-btn",children:[t.jsx(Ki,{size:16}),h&&R!=="chat"&&t.jsx("span",{className:"status-dot status-dot--pending header-chat-unread-dot","aria-label":"Unread chat response"})]}),t.jsx("button",{className:`view-toggle-btn${R==="documents"?" active":""}`,onClick:()=>D("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":R==="documents",children:t.jsx(ua,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${R==="mailbox"?" active":""}`,onClick:()=>D("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":R==="mailbox",children:[t.jsx(Da,{size:16}),m>0&&R!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending header-chat-unread-dot","aria-label":"Pending approvals"})]}),B.filter(le=>le.view.placement==="primary").sort((le,ct)=>(le.view.order??Number.MAX_SAFE_INTEGER)-(ct.view.order??Number.MAX_SAFE_INTEGER)).map(le=>{const ct=yo(le.pluginId,le.view.viewId),nn=Vl(le.view.icon);return t.jsx("button",{className:`view-toggle-btn${R===ct||R==="graph"&&le.pluginId==="fusion-plugin-dependency-graph"&&le.view.viewId==="graph"?" active":""}`,onClick:()=>D(le.pluginId==="fusion-plugin-dependency-graph"&&le.view.viewId==="graph"?"graph":ct),title:`${le.view.label} view`,"aria-label":`${le.view.label} view`,"aria-pressed":R===ct,"data-testid":`view-toggle-plugin-${le.pluginId}-${le.view.viewId}`,children:t.jsx(nn,{size:16})},`${le.pluginId}:${le.view.viewId}`)}),Me&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Ke,className:`view-toggle-btn${["research","skills","insights","memory","dev-server","devserver","graph","stash-recovery"].includes(R)||fe?.evalsView&&R==="evals"||F&&I||fr(R)?" active":""}`,onClick:()=>dt(le=>!le),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Je,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(pn,{size:12})}),Je&&t.jsxs("div",{ref:Le,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[fe?.evalsView&&t.jsxs("button",{className:`view-toggle-overflow-item${R==="evals"?" active":""}`,onClick:()=>{D("evals"),dt(!1)},role:"menuitem","data-testid":"view-overflow-evals",children:[t.jsx(Rs,{size:14}),t.jsx("span",{children:"Evals"})]}),t.jsxs("button",{className:`view-toggle-overflow-item${R==="stash-recovery"?" active":""}`,onClick:()=>{D("stash-recovery"),dt(!1)},role:"menuitem","data-testid":"view-overflow-stash-recovery",children:[t.jsx(Pa,{size:14}),t.jsx("span",{children:"Stash Recovery"}),f>0?t.jsx("span",{className:"btn-badge",children:f}):null]}),fe?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${R==="research"?" active":""}`,onClick:()=>{D("research"),dt(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(Wi,{size:14}),t.jsx("span",{children:"Research"})]}),fe?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${R==="insights"?" active":""}`,onClick:()=>{D("insights"),dt(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(gs,{size:14}),t.jsx("span",{children:"Insights"})]}),K&&t.jsxs("button",{className:`view-toggle-overflow-item${R==="skills"?" active":""}`,onClick:()=>{D("skills"),dt(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(as,{size:14}),t.jsx("span",{children:"Skills"})]}),fe?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${R==="memory"?" active":""}`,onClick:()=>{D("memory"),dt(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(So,{size:14}),t.jsx("span",{children:"Memory"})]}),fe?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${R==="dev-server"||R==="devserver"?" active":""}`,onClick:()=>{D("devserver"),dt(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(yr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),F&&N&&t.jsxs("button",{className:`view-toggle-overflow-item${I?" active":""}`,onClick:()=>{N(),dt(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx($u,{size:14}),t.jsx("span",{children:"Todos"})]}),B.filter(le=>le.view.placement!=="primary").sort((le,ct)=>(le.view.order??Number.MAX_SAFE_INTEGER)-(ct.view.order??Number.MAX_SAFE_INTEGER)).map(le=>{const ct=yo(le.pluginId,le.view.viewId),nn=Vl(le.view.icon);return t.jsxs("button",{className:`view-toggle-overflow-item${R===ct||R==="graph"&&le.pluginId==="fusion-plugin-dependency-graph"&&le.view.viewId==="graph"?" active":""}`,onClick:()=>{D(le.pluginId==="fusion-plugin-dependency-graph"&&le.view.viewId==="graph"?"graph":ct),dt(!1)},role:"menuitem","data-testid":`view-overflow-plugin-${le.pluginId}-${le.view.viewId}`,children:[t.jsx(nn,{size:14}),t.jsx("span",{children:le.view.label})]},`${le.pluginId}:${le.view.viewId}`)})]})]})]}),!Pe&&o&&t.jsx("button",{className:"btn-icon",onClick:le=>o(le.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Ys,{size:16})}),!Pe&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(yr,{size:16})}),!Pe&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(Pa,{size:16})}),!Pe&&!Zt&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(jh,{size:16})}),!Pe&&t.jsxs("button",{className:`btn-icon${r>0?" btn-icon--has-indicator":""}`,onClick:r>0&&a?a:s,title:r>0?"Resume planning session":"Create a task with AI planning","data-testid":"planning-btn",style:{position:"relative"},children:[t.jsx($i,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"planning-badge","aria-label":`${r} active planning session${r!==1?"s":""}`,children:r})]}),!Pe&&t.jsxs("div",{className:"terminal-split-btn",ref:Ve,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:j,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(Gi,{size:16})}),y&&S&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:Pt,className:`btn-icon terminal-split-btn__chevron${ge?" btn-icon--active":""}`,onClick:()=>pt(le=>!le),title:"Scripts","aria-haspopup":"listbox","aria-expanded":ge,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(pn,{size:12,className:`quick-scripts-dropdown__trigger-chevron${ge?" rotate":""}`})}),ge&&t.jsx("div",{ref:Ot,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:te,"data-testid":"quick-scripts-dropdown",style:lt?{position:"fixed",top:`${lt.top}px`,left:`${lt.left}px`,width:`${lt.width}px`,right:"auto"}:void 0,children:Rt?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(jt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Ht.length===0?t.jsxs("div",{className:"quick-scripts-dropdown__empty","data-testid":"quick-scripts-empty",children:[t.jsx("div",{className:"quick-scripts-dropdown__empty-icon",children:t.jsx(Gi,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:se,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Ht.map(([le,ct],nn)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${be===nn?"highlighted":""}`,onClick:()=>$t(le,ct),role:"option","aria-selected":be===nn,"data-testid":`quick-script-item-${le}`,children:[t.jsx(is,{size:14,className:"quick-scripts-dropdown__item-icon"}),t.jsxs("div",{className:"quick-scripts-dropdown__item-info",children:[t.jsx("span",{className:"quick-scripts-dropdown__item-name",children:le}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:ct,children:ct.length>50?`${ct.slice(0,50)}...`:ct})]})]},le))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${rn&&be===Ht.length?"highlighted":""}`,onClick:se,"data-testid":"quick-scripts-manage",children:[t.jsx(vo,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!Pe&&C&&t.jsx("button",{className:`btn-icon${v?" btn-icon--active":""}`,onClick:C,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(Es,{size:16})}),!Pe&&g&&t.jsx("button",{className:"btn-icon",onClick:g,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Fs,{size:16})}),!Pe&&b&&t.jsx("button",{className:"btn-icon",onClick:b,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Bl,{size:16})}),!Pe&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:yn,className:"btn-icon",onClick:()=>yt(le=>!le),title:"More actions","aria-label":"More actions","aria-expanded":Nt,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(Yd,{size:16})}),Nt&&t.jsxs("div",{ref:Gt,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[x&&w!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{x(),yt(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(Co,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{Xe(p),yt(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(Ji,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:mt,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${_?" btn-icon--stopped":""}`,onClick:z,title:_?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:_?t.jsx(is,{size:16}):t.jsx(Ii,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Se?" btn-icon--active":""}`,onClick:()=>G(le=>!le),title:"Engine options","aria-haspopup":"menu","aria-expanded":Se,"data-testid":"engine-control-chevron-btn",children:t.jsx(pn,{size:12})}),Se&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${M?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{U?.(),G(!1)},role:"menuitem",title:M?"Resume scheduling":"Pause triage",disabled:!!_,"data-testid":"engine-control-pause-triage-btn",children:[M?t.jsx(is,{size:14}):t.jsx(vi,{size:14}),t.jsx("span",{children:M?"Resume scheduling":"Pause triage"})]})})]}),!Pe&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(vo,{size:16})}),t.jsx(la,{slotId:"header-action",projectId:Y}),Pe&&!nt&&t.jsx("button",{ref:mn,className:"btn-icon compact-overflow-trigger",onClick:wt,title:"More header actions","aria-label":"More header actions","aria-expanded":me,"aria-haspopup":"menu",children:t.jsx(Yd,{size:16})}),Pe&&!nt&&me&&t.jsxs("div",{ref:Qt,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[je.length>=1&&Ne&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(Ne),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(uc,{size:16}),t.jsx("span",{children:"Projects"})]}),C&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(C),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(Es,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>Xe(r>0&&a?a:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx($i,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"overflow-planning-badge",children:r})]}),t.jsx("span",{children:r>0?`Resume planning session (${r})`:"Create a task with AI planning"})]}),g&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(g),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Fs,{size:16}),t.jsx("span",{children:"Git Manager"})]}),x&&w!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(x),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(Co,{size:16}),t.jsx("span",{children:"Nodes"})]}),!Zt&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(n),role:"menuitem",children:[t.jsx(jh,{size:16}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("div",{className:"mobile-overflow-group","data-testid":"overflow-terminal-group",children:[t.jsxs("div",{className:"mobile-overflow-split-row",children:[t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-split-primary",onClick:()=>Xe(j),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Gi,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>xt(le=>!le),role:"menuitem","aria-expanded":_e,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(On,{size:14,className:`mobile-overflow-chevron${_e?" mobile-overflow-chevron--open":""}`})})]}),_e&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Yt?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(jt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):an.length>0?t.jsxs(t.Fragment,{children:[an.map(([le,ct])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{S&&S(le,ct),re(!1),xt(!1)},role:"menuitem","data-testid":`overflow-script-item-${le}`,children:[t.jsx(is,{size:14}),t.jsx("span",{children:le})]},le)),y&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>Xe(y),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(xi,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):y&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>Xe(y),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(xi,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(p),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(Ji,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(Pa,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),d&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(Da,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]}),m>0&&t.jsx("span",{className:"header-badge","data-testid":"overflow-mailbox-approval-badge",children:m})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:le=>Xe(()=>o(le.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Ys,{size:16}),t.jsx("span",{children:"View Usage"})]}),b&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(b),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Bl,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(e),role:"menuitem",children:[t.jsx(vo,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),zt&&ft&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{className:"header-search",children:[t.jsx(Wi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:ne,onChange:le=>O(le.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:at,"aria-label":"Close search",children:t.jsx(un,{size:14})})]}),Pn&&t.jsxs("div",{className:"header-branch-filters","data-testid":"header-branch-filters-desktop",children:[t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Working branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:A,onChange:le=>J?.(le.target.value),"data-testid":"working-branch-filter",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:il,children:"No working branch"}),$.map(le=>t.jsx("option",{value:le,children:le},le))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Base branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:P,onChange:le=>ce?.(le.target.value),"data-testid":"target-branch-filter",children:[t.jsx("option",{value:"",children:"All base branches"}),t.jsx("option",{value:il,children:"No base branch"}),k.map(le=>t.jsx("option",{value:le,children:le},le))]})]})]})]}),O&&ae&&De&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{ref:on,className:"header-search mobile-search-expanded",children:[t.jsx(Wi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:sn,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:ne,onChange:le=>O(le.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Et,"aria-label":"Close search",children:t.jsx(un,{size:14})})]}),Pn&&t.jsxs("div",{className:"header-branch-filters","data-testid":"header-branch-filters-mobile",children:[t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Working branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:A,onChange:le=>J?.(le.target.value),"data-testid":"working-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:il,children:"No working branch"}),$.map(le=>t.jsx("option",{value:le,children:le},le))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Base branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:P,onChange:le=>ce?.(le.target.value),"data-testid":"target-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All base branches"}),t.jsx("option",{value:il,children:"No base branch"}),k.map(le=>t.jsx("option",{value:le,children:le},le))]})]})]})]})]})}const wC={themeMode:"dark",colorTheme:"default",dashboardFontScalePct:100,defaultProvider:void 0,defaultModelId:void 0,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyAccessToken:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input","message:agent-to-user","message:agent-to-agent","gridlock","fallback-used","memory-dreams-processed"],ntfyDashboardHost:void 0,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],customProviders:[],defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,opencodeGoModelSync:!0,updateCheckEnabled:!0,fnBinaryCheckEnabled:!0,updateCheckFrequency:"daily",autoReloadOnVersionChange:!0,showGitHubStarButton:!0,githubTrackingDefaultRepo:void 0,modelOnboardingComplete:void 0,useClaudeCli:void 0,useDroidCli:void 0,useLlamaCpp:void 0,executionGlobalProvider:void 0,executionGlobalModelId:void 0,planningGlobalProvider:void 0,planningGlobalModelId:void 0,validatorGlobalProvider:void 0,validatorGlobalModelId:void 0,titleSummarizerGlobalProvider:void 0,titleSummarizerGlobalModelId:void 0,daemonToken:void 0,daemonPort:4040,daemonHost:"127.0.0.1",settingsSyncEnabled:!1,settingsSyncAuth:!1,settingsSyncInterval:9e5,settingsSyncConflictResolution:"last-write-wins",dashboardCurrentNodeId:void 0,dashboardCurrentProjectIdByNode:void 0,vitestAutoKillEnabled:!0,vitestKillThresholdPct:90,persistAgentToolOutput:!0,persistAgentThinkingLog:!1,researchGlobalDefaults:{searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},maxSourcesPerRun:20,defaultExportFormat:"markdown"},researchGlobalEnabled:!0,researchGlobalMaxConcurrentRuns:3,researchGlobalDefaultTimeout:3e5,researchGlobalMaxSourcesPerRun:20,researchGlobalMaxSynthesisRounds:2,researchGlobalWebSearchProvider:"builtin",researchGlobalSearxngUrl:void 0,researchGlobalBraveApiKey:void 0,researchGlobalGoogleSearchApiKey:void 0,researchGlobalGoogleSearchCx:void 0,researchGlobalTavilyApiKey:void 0,researchGlobalGitHubEnabled:!1,researchGlobalLocalDocsEnabled:!0,researchGlobalMaxSearchResults:10,researchGlobalFetchTimeoutMs:3e4,researchGlobalUserAgent:"FusionResearchBot/1.0",remoteAccess:{activeProvider:null,providers:{tailscale:{enabled:!1,hostname:"",targetPort:0,acceptRoutes:!1},cloudflare:{enabled:!1,quickTunnel:!0,tunnelName:"",tunnelToken:null,ingressUrl:""}},tokenStrategy:{persistent:{enabled:!0,token:null},shortLived:{enabled:!1,ttlMs:9e5,maxTtlMs:864e5}},lifecycle:{rememberLastRunning:!1,wasRunningOnShutdown:!1,lastRunningProvider:null}},experimentalFeatures:{}},kC={globalPause:!1,globalPauseReason:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",requirePrApproval:!1,pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",defaultNodeId:void 0,worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,worktreeNaming:"random",taskPrefix:"FN",includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",planningProvider:void 0,planningModelId:void 0,planningFallbackProvider:void 0,planningFallbackModelId:void 0,defaultProviderOverride:void 0,defaultModelIdOverride:void 0,executionProvider:void 0,executionModelId:void 0,validatorProvider:void 0,validatorModelId:void 0,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0,modelPresets:[],autoSelectModelPreset:!1,completionDocumentationMode:"off",defaultPresetBySize:{},autoResolveConflicts:!0,smartConflictResolution:!0,mergerAutostashMaxAgeHours:24,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",worktreeRebaseLocalBase:!0,mergeConflictStrategy:"smart-prefer-main",workflowStepTimeoutMs:36e4,workflowRevisionForkOnScopeMismatch:!0,strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,agentProvisioning:{},specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:6e5,staleHighFanoutBlockerAgeThresholdMs:7200*1e3,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,preserveProgressOnStuckRequeue:!0,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:3e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,githubTrackingEnabledByDefault:!1,githubTrackingDefaultRepo:void 0,githubAuthMode:"gh-cli",githubAuthToken:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",memoryBackupEnabled:!1,memoryBackupSchedule:"0 3 * * *",memoryBackupRetention:14,memoryBackupDir:".fusion/backups/memory",memoryBackupScope:"all",autoSummarizeTitles:!1,useAiMergeCommitSummary:!0,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,scripts:void 0,setupScript:void 0,insightExtractionEnabled:!1,insightExtractionSchedule:"0 2 * * *",insightExtractionMinIntervalMs:864e5,taskEvaluationEnabled:!1,taskEvaluationSchedule:"0 5 * * *",taskEvaluationProvider:void 0,taskEvaluationModelId:void 0,taskEvaluationFollowUpPolicy:"off",taskEvaluationRetention:void 0,memoryEnabled:!0,memoryBackendType:"qmd",memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *",tokenCap:void 0,runStepsInNewSessions:!1,maxParallelSteps:2,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,researchSettings:{enabled:!0,searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},limits:{maxConcurrentRuns:3,maxSourcesPerRun:20,maxDurationMs:3e5,requestTimeoutMs:3e4}},evalSettings:{enabled:!1,intervalMs:864e5,evaluatorProvider:void 0,evaluatorModelId:void 0,followUpPolicy:"suggest-only",retentionDays:30},researchEnabled:!0,researchMaxConcurrentRuns:3,researchDefaultTimeout:3e5,researchMaxSourcesPerRun:20,researchMaxSynthesisRounds:2},jC=Object.freeze(Object.keys(wC)),NC=Object.freeze(Object.keys(kC));function Z5(e){return jC.includes(e)}function e8(e){return NC.includes(e)}function Ee(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function SC(e){return!!(e?.provider&&e?.modelId)}function ha(...e){for(const n of e)if(SC(n))return{provider:n.provider,modelId:n.modelId};return{}}function xc(e){return ha({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function CC(e){return ha({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},xc(e))}function EC(e){return ha({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},xc(e))}function _C(e){return ha({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},xc(e))}function t8(e){return ha({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},xc(e))}function Eb(e,n){return ha({provider:e.modelProvider,modelId:e.modelId},CC(n))}function _b(e,n){return ha({provider:e.validatorModelProvider,modelId:e.validatorModelId},_C(n))}function Mb(e,n){return ha({provider:e.planningModelProvider,modelId:e.planningModelId},EC(n))}const n8=["off","minimal","low","medium","high"],oa=["triage","todo","in-progress","in-review","done","archived"],Wl="triage";function Vu(e){return typeof e=="string"&&oa.includes(e)}function Ab(e,n=Wl){return Vu(e)?e:n}const pa=["low","normal","high","urgent"],Ls="normal",Wu=5,Rb=7200*1e3,MC=["default","ocean","forest","sunset","zen","berry","high-contrast","industrial","monochrome","slate","ash","graphite","silver","solarized","factory","ayu","one-dark","nord","dracula","gruvbox","tokyo-night","catppuccin-mocha","github-dark","everforest","rose-pine","kanagawa","night-owl","palenight","monokai-pro","slime","brutalist","neon-city","parchment","terminal","glass","horizon","vitesse","outrun","snazzy","porple","espresso","mars","poimandres","ember","rust","copper","foundry","carbon","sandstone","lagoon","frost","lavender","neon-bloom","sepia"],vc=/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/,ds={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},AC={triage:"Raw ideas — AI will plan these",todo:"Specified and ready to start","in-progress":"AI is working on this in a worktree","in-review":"Complete — ready to merge",done:"Merged and closed",archived:"Completed and archived"},ru={triage:["todo"],todo:["in-progress","triage"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo","triage"],done:["todo","triage","archived"],archived:["done"]};function RC(e){const n=e.metadata??{};return!!(n.agentKind==="task-worker"||n.taskWorker===!0||n.managedBy==="task-executor"||n.type==="spawned"||n.internal===!0||e.role==="executor"&&typeof e.name=="string"&&e.name.startsWith("executor-")&&e.reportsTo==null||e.role==="executor"&&e.name==="verification-agent"&&e.reportsTo==null)}function Nh(e){return e==="urgent"?3:e==="high"?2:e==="low"?0:1}function Sh(e,n){return Nh(n)-Nh(e)}function Wc(e,n){const s=Number.parseInt(e.slice(e.lastIndexOf("-")+1),10),a=Number.parseInt(n.slice(n.lastIndexOf("-")+1),10);return Number.isFinite(s)&&Number.isFinite(a)&&s!==a?s-a:e.localeCompare(n)}function Ch(e){const n=e.columnMovedAt??e.updatedAt??e.createdAt,s=Date.parse(n);return Number.isFinite(s)?s:0}function Eh(e){return e==="merging"||e==="merging-pr"||e==="merging-fix"}function Ib(e,n){return n==="todo"?[...e].sort((s,a)=>{const r=Sh(s.priority,a.priority);return r!==0?r:s.createdAt!==a.createdAt?s.createdAt.localeCompare(a.createdAt):Wc(s.id,a.id)}):[...e].sort((s,a)=>{if(n==="done"){const o=Ch(a)-Ch(s);return o!==0?o:Wc(s.id,a.id)}if(n==="in-review"){const o=Eh(s.status),l=Eh(a.status);if(o!==l)return o?-1:1}const r=Sh(s.priority,a.priority);return r!==0?r:Wc(s.id,a.id)})}function IC(e,n=1400){const s=i.useRef(null),[a,r]=i.useState(!1),o=i.useRef(null);return i.useEffect(()=>(s.current!==null&&e>s.current&&(r(!0),o.current=setTimeout(()=>r(!1),n)),s.current=e,()=>{o.current!==null&&clearTimeout(o.current)}),[e,n]),a}function TC({isOpen:e,options:n,onConfirm:s,onCancel:a}){const r=i.useRef(null);return i.useEffect(()=>{if(!e)return;r.current?.focus();const o=l=>{l.key==="Escape"&&(l.preventDefault(),a())};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e,a]),!e||!n?null:t.jsx("div",{className:"modal-overlay open confirm-dialog-overlay",onClick:a,children:t.jsxs("div",{className:"modal confirm-dialog",onClick:o=>o.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":n.title,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:n.title}),t.jsx("button",{className:"modal-close",onClick:a,"aria-label":"Close confirmation dialog",children:"×"})]}),t.jsx("div",{className:"confirm-dialog__body",children:n.message}),t.jsxs("div",{className:"modal-actions confirm-dialog__actions",children:[t.jsx("button",{ref:r,className:"btn",onClick:a,children:n.cancelLabel??"Cancel"}),t.jsx("button",{className:`btn ${n.danger?"btn-danger":"btn-primary"}`,onClick:s,children:n.confirmLabel??"Confirm"})]})]})})}const Tb=i.createContext(null);function PC({children:e}){const[n,s]=i.useState([]),a=i.useRef([]),r=i.useCallback(u=>{s(m=>{const h=u(m);return a.current=h,h})},[]),o=i.useCallback(u=>new Promise(m=>{r(h=>[...h,{options:u,resolve:m}])}),[r]),l=i.useCallback(u=>{const m=a.current[0];m&&(m.resolve(u),r(h=>h.slice(1)))},[r]),c=n[0]??null,d=i.useMemo(()=>({confirm:o}),[o]);return Ol.createElement(Tb.Provider,{value:d},e,Ol.createElement(TC,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function pi(){const e=i.useContext(Tb);return e||{confirm:async n=>!1}}function $C(e,n){return e==="open"?"card-github-badge--open":n==="completed"?"card-github-badge--completed":n==="not_planned"?"card-github-badge--not-planned":"card-github-badge--closed"}function Pb({prInfo:e,issueInfo:n,onIssueRefresh:s}){return t.jsxs(t.Fragment,{children:[e&&t.jsxs("a",{className:`card-github-badge card-github-badge--${e.status}`,title:`PR #${e.number}: ${e.title}`,href:e.url,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(si,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("a",{className:`card-github-badge ${$C(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,href:n.url,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(cc,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function al(e,n){return`${e??"default"}:${n}`}class DC{ws=null;listeners=new Set;badgeUpdates=new Map;subscriptionsByTask=new Map;reconnectTimeout=null;reconnectDelayMs=1e3;shouldReconnect=!1;isConnected=!1;projectId=null;snapshot={badgeUpdates:new Map,isConnected:!1};previousProjectIdRef=null;projectContextVersionRef=0;contextVersionAtStart=0;subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}setProjectId(n){if(this.projectId===n)return;this.previousProjectIdRef=this.projectId,this.projectContextVersionRef++,this.contextVersionAtStart=this.projectContextVersionRef;const s=this.subscriptionsByTask.size>0,a=[];for(const[r,o]of this.subscriptionsByTask){const l=r.split(":").slice(1).join(":");for(const c of o)a.push({hookId:c,taskId:l})}if(this.projectId=n,this.reset(),s){for(const{hookId:r,taskId:o}of a){const l=al(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const a=al(this.projectId,s),r=this.subscriptionsByTask.get(a)??new Set,o=!r.has(n);r.add(n),this.subscriptionsByTask.set(a,r),this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect(),o&&this.send({type:"subscribe",taskId:s,projectId:this.projectId})}unsubscribeTask(n,s){const a=al(this.projectId,s),r=this.subscriptionsByTask.get(a);r&&(r.delete(n),r.size===0&&(this.subscriptionsByTask.delete(a),this.badgeUpdates.delete(a),this.send({type:"unsubscribe",taskId:s,projectId:this.projectId}),this.emit()),this.shouldReconnect=this.subscriptionsByTask.size>0,this.shouldReconnect||this.disconnect())}cleanupHook(n){for(const s of[...this.subscriptionsByTask.keys()]){const a=s.split(":").slice(1).join(":");this.unsubscribeTask(n,a)}}reset(){this.disconnect(),this.badgeUpdates.clear(),this.subscriptionsByTask.clear(),this.shouldReconnect=!1,this.emit()}connect(){if(!this.shouldReconnect||typeof window>"u"||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;const n=this.projectContextVersionRef;let a=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/ws`;this.projectId&&(a+=`?projectId=${encodeURIComponent(this.projectId)}`);const r=new WebSocket(Di(a));this.ws=r,r.onopen=()=>{if(this.projectContextVersionRef!==n){r.close();return}this.isConnected=!0,this.reconnectDelayMs=1e3,this.emit();const o=new Set;for(const l of this.subscriptionsByTask.keys()){const c=l.split(":").slice(1).join(":");o.add(c)}for(const l of o)this.send({type:"subscribe",taskId:l,projectId:this.projectId})},r.onmessage=o=>{if(this.projectContextVersionRef===n)try{const l=JSON.parse(o.data);if(l.type!=="badge:updated"||l.projectId!==void 0&&l.projectId!==this.projectId)return;const c=al(this.projectId,l.taskId),d=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:_h(l,"prInfo")?l.prInfo??null:d?.prInfo,issueInfo:_h(l,"issueInfo")?l.issueInfo??null:d?.issueInfo,timestamp:l.timestamp}),this.emit()}catch{}},r.onclose=()=>{this.projectContextVersionRef===n&&(this.ws=null,this.isConnected&&(this.isConnected=!1,this.emit()),this.shouldReconnect&&this.scheduleReconnect(n))},r.onerror=()=>{}}disconnect(){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws){const n=this.ws;this.ws=null,n.close()}this.isConnected&&(this.isConnected=!1,this.emit())}scheduleReconnect(n){if(this.reconnectTimeout)return;const s=n??this.projectContextVersionRef,a=Math.min(this.reconnectDelayMs,5e3);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.projectContextVersionRef===s&&this.shouldReconnect&&this.connect()},a),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,5e3)}send(n){!this.ws||this.ws.readyState!==WebSocket.OPEN||this.ws.send(JSON.stringify(n))}emit(){this.snapshot={badgeUpdates:new Map(this.badgeUpdates),isConnected:this.isConnected};for(const n of this.listeners)n()}}const Ma=new DC;let LC=0;function _h(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function $b(e){const n=i.useRef(null);n.current===null&&(n.current=`badge-hook-${LC++}`);const s=i.useSyncExternalStore(o=>Ma.subscribe(o),()=>Ma.getSnapshot(),()=>Ma.getSnapshot()),a=i.useCallback(o=>{Ma.subscribeTask(n.current,o)},[]),r=i.useCallback(o=>{Ma.unsubscribeTask(n.current,o)},[]);return i.useEffect(()=>{Ma.setProjectId(e??null)},[e]),i.useEffect(()=>()=>{Ma.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:a,unsubscribeFromBadge:r}}function Kl(e,n,s,a){return e===void 0||!n?s:!a||n>=a?e??void 0:s}function OC({taskId:e,prInfo:n,issueInfo:s,updatedAt:a,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:d}=$b(o),u=!!(n||s);i.useEffect(()=>{if(!u||!r){d(e);return}return c(e),()=>{d(e)}},[u,r,o,c,e,d]);const m=l.get(`${o??"default"}:${e}`),h=Kl(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??a),f=Kl(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??a);return!h&&!f?null:t.jsx(Pb,{prInfo:h,issueInfo:f})}const FC=i.memo(OC);FC.displayName="TaskCardBadge";const li={data:new Map,pendingPromise:null,lastFetchTime:null},zC=5e3;function Pl(e,n){return n?`${n}::${e}`:e}function BC(e,n){const s=li.data.get(Pl(e,n));if(!(!s||Date.now()-s.timestamp>zC))return s}function UC(e){const[n,s]=i.useState(!1),a=i.useRef(null),r=i.useCallback(async c=>{let u=null;for(let m=0;m<3;m++)try{return await IN(c,e)}catch(h){u=h instanceof Error?h:new Error(String(h));const f=Ee(h);if(f?.includes("429")||f?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,m),3e4);await new Promise(g=>setTimeout(g,p));continue}break}if(u)throw u;return{}},[e]),o=i.useCallback(async c=>{if(c.length===0)return;const u=Date.now()-5e3;if(c.every(f=>{const p=li.data.get(Pl(f,e));return p&&p.timestamp>u})&&li.lastFetchTime&&li.lastFetchTime>u)return;if(a.current&&(clearTimeout(a.current),a.current=null),li.pendingPromise){s(!0);try{await li.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);li.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,x]of Object.entries(f))li.data.set(Pl(g,e),{result:x,timestamp:p});li.lastFetchTime=p}catch{}finally{li.pendingPromise=null,s(!1)}},[r,e]),l=i.useCallback(c=>li.data.get(Pl(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:li.lastFetchTime,getBatchData:l}}const ou=new Map,HC=3e4;function Db(e,n,s,a){return`${e}:${n??""}:${s??""}:${a??""}`}function qC(e,n,s,a){const r=Db(e,n,s,a),o=ou.get(r);return o?Date.now()>o.expiresAt?(ou.delete(r),null):o.stats:null}function VC(e,n,s,a,r){const o=Db(e,n,s,a);ou.set(o,{stats:r,expiresAt:Date.now()+HC})}function WC(e,n,s,a,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,d=r.pollIntervalMs,[u,m]=i.useState(null),[h,f]=i.useState(!1);return i.useEffect(()=>{if(!o){m(null),f(!1);return}const p=n==="done"&&!!s,g=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!g){m(null),f(!1);return}const x=g?l:void 0,w=c!==void 0?String(c):void 0;let b=!1;async function y(j=!1){if(!j){const C=qC(e,a,x,w);if(C){b||(m(C),f(!1));return}}f(!0);try{const C=await pb(e,x,a);b||(m(C.stats),VC(e,a,x,w,C.stats))}catch{b||m(null)}finally{b||f(!1)}}y();let S;return d&&g&&(S=setInterval(()=>{y(!0)},d)),()=>{b=!0,S&&clearInterval(S)}},[e,n,s,a,o,l,c,d]),{stats:u,loading:h}}const KC=new Set(["failed","stuck-killed"]);function Gl(e,n,s){if(e.column!=="in-progress"||e.status&&KC.has(e.status)||!n||n<=0)return!1;const a=new Date(e.updatedAt).getTime();return(s??Date.now())-a>n}function GC(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function JC(e){return e==="done"||e==="skipped"}function YC(e,n,s){const a=s?.get(e)?.trim();if(a)return a;const r=n?.workflowStepName?.trim();return r||e}function Lb(e,n){const s=(e.steps??[]).map((d,u)=>({id:`step-${u}`,name:d.name,status:d.status,source:"step",phase:"pre-merge"})),a=new Map((e.workflowStepResults??[]).map(d=>[d.workflowStepId,d])),r=(e.enabledWorkflowSteps??[]).map(d=>{const u=a.get(d);return{id:`workflow-${d}`,name:YC(d,u,n),status:u?GC(u.status):"pending",source:"workflow",phase:u?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(d=>JC(d.status)).length;return{total:l,completed:c,items:o}}function QC(e){return(e.action||e.outcome||"").replace(/^\[timing\]\s*/i,"").replace(/^\[[^\]]+\]\s*/i,"").replace(/\s+in\s+\d+(?:\.\d+)?ms\b/i,"").replace(/\s+after\s+\d+(?:\.\d+)?ms\b/i,"").trim()||"Timing event"}function Ob(e){return e.filter(n=>{const s=typeof n.action=="string"?n.action:"",a=typeof n.outcome=="string"?n.outcome:"";return s.includes("[timing]")||a.includes("[timing]")}).map(n=>{const a=`${n.action??""}
649
+ ${n.outcome??""}`.match(/(\d+(?:\.\d+)?)ms\b/i),r=a?Number(a[1]):void 0;return{timestamp:n.timestamp,durationMs:Number.isFinite(r)?r:void 0,summary:QC(n)}})}function Fb(e){if(!e||e.length===0)return null;let n=0,s=0;for(const a of Ob(e))typeof a.durationMs=="number"&&(n+=a.durationMs,s+=1);return s>0?n:null}function Fa(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function zb(e,n){if(!e||e.length===0)return null;let s=0,a=0;for(const r of e){if(!r.startedAt)continue;const o=Fa(r.startedAt);if(o==null)continue;let l;if(r.completedAt){const c=Fa(r.completedAt);if(c==null||c<o)continue;l=c}else l=Math.max(o,n);s+=l-o,a+=1}return a>0?s:null}function Bb(e,n,s){const a=Fa(e);if(a==null)return null;const r=Fa(n),o=r!=null&&r>=a?r:s;return Math.max(0,o-a)}function Ku(e){if(!(e instanceof Error))return null;const n=e.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(a=>typeof a=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}const lu=new Map;async function XC(e,n){const s=lu.get(e);if(s)return s;try{const a=await fb(e,n);return lu.set(e,a.title),a.title}catch{return e}}const Mh=12;function ZC(e){return e.length<=Mh?e:e.slice(0,Mh-3)+"..."}const cu=new Map;async function eE(e,n){const s=cu.get(e);if(s)return s;try{const a=await au(e,n);return cu.set(e,a.name),a.name}catch{return e}}function tE(e){return typeof e=="string"&&pa.includes(e)?e:Ls}function nE(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}function Ub(e){const n=e.sourceMetadata?.agentName;if(typeof n=="string"&&n.trim().length>0)return n.trim();if(typeof e.sourceAgentId=="string"&&e.sourceAgentId.trim().length>0)return e.sourceAgentId.trim()}function sE(e){return e.sourceType==="agent_heartbeat"||e.sourceType==="automation"||!!Ub(e)}const iE=new Set(["triage","todo"]),Ah=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),Rh=new Set(["merging","merging-pr","merging-fix"]),aE={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},rE=new Set(["in-progress","in-review","done"]),oE=3e4;function lE(e){return e==="merging-fix"?"Merging fixes…":e}function cE(e){const n=Fa(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function Ih(e,n){const s=Fa(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function mo(e,n){return Bb(e.executionStartedAt,e.executionCompletedAt,n)}function dE(e){return e.column==="done"?cE(e):null}function Hb(e,n){const s=Fa(e.updatedAt);return s==null?null:Math.max(0,n-s)}function uE(e,n){const s=mo(e,n);if(s!=null)return s;const a=Hb(e,n),r=ho(e,n);return r!=null?r+(a??0):a}function ho(e,n){if(typeof e.timedExecutionMs=="number")return e.timedExecutionMs;const s=Fb(e.log),a=zb(e.workflowStepResults,n);return s==null&&a==null?null:(s??0)+(a??0)}function Th(e){if(!Number.isFinite(e)||e<0)return"";if(e<6e4)return"<1m";const n=Math.floor(e/6e4);if(n<60)return`${n}m`;const s=Math.floor(n/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function Ph(e){if(!e)return null;const n=e.trim();return n.length>0?n:null}function mE(e){const n=Ph(e.branch),s=Ph(e.baseBranch),a=`fusion/${e.id.toLowerCase()}`,r=n&&(n===a||n.startsWith(`${a}-`))?null:n,o=s?.toLowerCase()==="main"?null:s;return{branch:r,baseBranch:o??null}}function $h(e){if(!Number.isFinite(e)||e<0||e===0)return"";const n=Math.ceil(e/6e4);if(n<59)return`${n}m`;const s=Math.ceil(e/36e5);return s<24?`${s}h`:`${Math.ceil(e/864e5)}d`}function Dh(e,n){if(!e&&!n)return!0;if(!e||!n)return!1;const s=Object.keys(e),a=Object.keys(n);return s.length!==a.length?!1:s.every(r=>e[r]===n[r])}function hE(e,n){return e.length!==n.length?!1:e.every((s,a)=>s.name===n[a]?.name&&s.status===n[a]?.status)}function Kc(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function pE(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function fE(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function gE(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];return r?s.workflowStepId===r.workflowStepId&&s.workflowStepName===r.workflowStepName&&s.phase===r.phase&&s.status===r.status&&s.output===r.output&&s.startedAt===r.startedAt&&s.completedAt===r.completedAt:!1})}function bE(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];return r?s.filename===r.filename&&s.mimeType===r.mimeType&&s.size===r.size:!1})}function xE(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];return r?s.author===r.author&&s.text===r.text&&s.createdAt===r.createdAt:!1})}function vE(e,n){const s=e.task,a=n.task;return e.queued===n.queued&&e.projectId===n.projectId&&e.globalPaused===n.globalPaused&&e.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&e.onOpenDetail===n.onOpenDetail&&e.addToast===n.addToast&&e.onUpdateTask===n.onUpdateTask&&e.onArchiveTask===n.onArchiveTask&&e.onUnarchiveTask===n.onUnarchiveTask&&e.onDeleteTask===n.onDeleteTask&&e.onRetryTask===n.onRetryTask&&e.onOpenDetailWithTab===n.onOpenDetailWithTab&&e.onOpenMission===n.onOpenMission&&e.onMoveTask===n.onMoveTask&&e.workflowStepNameLookup===n.workflowStepNameLookup&&e.disableDrag===n.disableDrag&&e.fanout?.totalCount===n.fanout?.totalCount&&e.fanout?.activeTodoCount===n.fanout?.activeTodoCount&&e.fanout?.isHighFanout===n.fanout?.isHighFanout&&e.fanout?.escalation?.blockingAgeMs===n.fanout?.escalation?.blockingAgeMs&&Kc(e.fanout?.dependentIds??[],n.fanout?.dependentIds??[])&&Kc(e.fanout?.staleBlockedByDependentIds??[],n.fanout?.staleBlockedByDependentIds??[])&&s.id===a.id&&s.title===a.title&&s.description===a.description&&s.column===a.column&&s.columnMovedAt===a.columnMovedAt&&s.timedExecutionMs===a.timedExecutionMs&&s.updatedAt===a.updatedAt&&s.createdAt===a.createdAt&&s.status===a.status&&s.priority===a.priority&&s.executionMode===a.executionMode&&s.paused===a.paused&&s.error===a.error&&s.size===a.size&&s.blockedBy===a.blockedBy&&s.worktree===a.worktree&&s.branch===a.branch&&s.baseBranch===a.baseBranch&&s.breakIntoSubtasks===a.breakIntoSubtasks&&s.currentStep===a.currentStep&&s.modelProvider===a.modelProvider&&s.modelId===a.modelId&&s.validatorModelProvider===a.validatorModelProvider&&s.validatorModelId===a.validatorModelId&&s.planningModelProvider===a.planningModelProvider&&s.planningModelId===a.planningModelId&&s.reviewLevel===a.reviewLevel&&s.missionId===a.missionId&&s.assignedAgentId===a.assignedAgentId&&s.mergeRetries===a.mergeRetries&&s.sourceType===a.sourceType&&s.sourceAgentId===a.sourceAgentId&&s.sourceMetadata?.issueUrl===a.sourceMetadata?.issueUrl&&s.sourceMetadata?.agentName===a.sourceMetadata?.agentName&&bE(s.attachments,a.attachments)&&xE(s.comments,a.comments)&&Kc(s.dependencies,a.dependencies)&&hE(s.steps,a.steps)&&pE(s.enabledWorkflowSteps,a.enabledWorkflowSteps)&&gE(s.workflowStepResults,a.workflowStepResults)&&Dh(s.prInfo,a.prInfo)&&Dh(s.issueInfo,a.issueInfo)}function yE({task:e,projectId:n,queued:s,onOpenDetail:a,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:d,onDeleteTask:u,onRetryTask:m,onOpenDetailWithTab:h,taskStuckTimeoutMs:f,onOpenMission:p,onMoveTask:g,lastFetchTimeMs:x,workflowStepNameLookup:w,disableDrag:b,fanout:y}){const[S,j]=i.useState(!1),[C,v]=i.useState(!1),[N,I]=i.useState(!1),[F,_]=i.useState(e.description||""),[M,z]=i.useState(!1),[U,R]=i.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(Me=>Me.status==="done"||Me.status==="skipped")),[D,K]=i.useState(null),[Z,ne]=i.useState(null),[O,A]=i.useState(!1),[P,$]=i.useState(!1),[k,J]=i.useState(()=>Date.now()),ce=i.useRef(null),je=i.useRef(!1),He=i.useRef(null),xe=i.useRef(null),[Ne,Y]=i.useState(!1),{badgeUpdates:ie,subscribeToBadge:ee,unsubscribeFromBadge:oe}=$b(n),{confirm:W}=pi(),L=i.useRef(null),pe=i.useRef(!1),fe=i.useCallback(Me=>Me instanceof Element?!!Me.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);i.useEffect(()=>{_(e.description||"")},[e.id,e.description]),i.useEffect(()=>{if(!O)return;const Me=it=>{xe.current&&!xe.current.contains(it.target)&&A(!1)};return document.addEventListener("click",Me),()=>document.removeEventListener("click",Me)},[O]),i.useEffect(()=>{if(!e.missionId){K(null);return}const Me=lu.get(e.missionId);if(Me){K(Me);return}let it=!1;return XC(e.missionId,n).then(kt=>{it||K(kt)}),()=>{it=!0}},[e.missionId,n]),i.useEffect(()=>{if(!e.assignedAgentId){ne(null);return}const Me=cu.get(e.assignedAgentId);if(Me){ne(Me);return}ne(null);let it=!1;return eE(e.assignedAgentId,n).then(kt=>{it||ne(kt)}),()=>{it=!0}},[e.assignedAgentId,n]),i.useEffect(()=>{if(N&&ce.current){const Me=ce.current;Me.focus(),Me.style.height="auto",Me.style.height=Me.scrollHeight+"px"}},[N]),i.useEffect(()=>{if(typeof IntersectionObserver>"u"){Y(!0);return}const Me=He.current;if(!Me)return;const it=new IntersectionObserver(([kt])=>{Y(kt?.isIntersecting??!0)},{rootMargin:"200px"});return it.observe(Me),()=>it.disconnect()},[N,e.id]);const B=i.useCallback(Me=>{Me.dataTransfer.setData("text/plain",e.id),Me.dataTransfer.effectAllowed="move",j(!0)},[e.id]),ve=i.useCallback(()=>{j(!1)},[]),Fe=i.useCallback(Me=>Me.dataTransfer.types.includes("Files"),[]),ae=i.useCallback(Me=>{Fe(Me)&&(Me.preventDefault(),Me.stopPropagation(),Me.dataTransfer.dropEffect="copy",v(!0))},[Fe]),qe=i.useCallback(Me=>{Fe(Me)&&(Me.preventDefault(),Me.stopPropagation(),v(!1))},[Fe]),Pe=i.useCallback(async Me=>{if(!Fe(Me))return;Me.preventDefault(),Me.stopPropagation(),v(!1);const it=Array.from(Me.dataTransfer.files);for(const kt of it)try{await bc(e.id,kt,n),r(`Attached ${kt.name} to ${e.id}`,"success")}catch($t){r(`Failed to attach ${kt.name}: ${Ee($t)}`,"error")}},[e.id,Fe,r]),nt=i.useCallback(()=>{N||a(e)},[e,a,N]),Be=i.useCallback(Me=>{if(je.current){je.current=!1;return}fe(Me.target)||nt()},[nt,fe]),de=i.useCallback(Me=>{const it=Me.touches[0];it&&(L.current={x:it.clientX,y:it.clientY,time:Date.now()},pe.current=!1)},[]),Ie=i.useCallback(Me=>{if(!L.current)return;const it=Me.touches[0];if(!it)return;const kt=Math.abs(it.clientX-L.current.x),$t=Math.abs(it.clientY-L.current.y);(kt>Lh||$t>Lh)&&(pe.current=!0)},[]),$e=i.useCallback(Me=>{if(fe(Me.target)||!L.current)return;const kt=Date.now()-L.current.time<wE,$t=!pe.current;kt&&$t&&(je.current=!0,nt()),L.current=null,pe.current=!1},[nt,fe]),st=i.useCallback(async(Me,it)=>{Me.stopPropagation();try{const kt=await La(it,n);a(kt)}catch{r(`Failed to load dependency ${it}`,"error")}},[a,r]),Ue=e.status==="failed",me=e.paused===!0,re=!!(e.paused&&e.pausedByAgentId),_e=tE(e.priority),xt=_e!==Ls,ut=Gl(e,f,x),Qe=e.column==="triage"&&e.status==="awaiting-approval",vt=e.column==="archived",Ae=!o&&!s&&!Ue&&!me&&!ut&&!Qe&&(e.column==="in-progress"||Ah.has(e.status)),Je=!b&&!s&&!me&&!N&&!vt,dt=iE.has(e.column)&&!Ae&&!me&&!s&&l,Nt=!!(e.prInfo||e.issueInfo),yt=e.sourceType==="github_import",Se=i.useMemo(()=>mE(e),[e.id,e.branch,e.baseBranch]),G=!!(Se.branch||Se.baseBranch),ge=fE(e.sourceMetadata),pt=sE(e),ke=Ub(e),tt=ke?`Created by agent: ${ke}`:"Created by agent",Rt=!!(e.assignedAgentId&&Z===null),Re=i.useMemo(()=>{const Me=[];return e.modelProvider&&Me.push(e.modelProvider),e.validatorModelProvider&&!Me.includes(e.validatorModelProvider)&&Me.push(e.validatorModelProvider),e.planningModelProvider&&!Me.includes(e.planningModelProvider)&&Me.push(e.planningModelProvider),Me},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),be=i.useMemo(()=>Lb(e,w),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,w]),rt=be.total>0&&(e.status==="executing"||e.column==="in-progress");i.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const Me=e.status!=null&&Rh.has(e.status);if(e.column==="in-progress"){const kt=mo(e,Date.now()),$t=Ih(e,Date.now()),se=ho(e,Date.now());if(kt==null&&$t==null&&se==null)return}if(!Me&&e.column==="in-review"){const kt=mo(e,Date.now()),$t=ho(e,Date.now());if(kt==null&&$t==null)return}J(Date.now());const it=window.setInterval(()=>{J(Date.now())},oE);return()=>window.clearInterval(it)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const lt=i.useMemo(()=>{if(!rE.has(e.column))return null;if(e.status!=null&&Rh.has(e.status)){const te=uE(e,k);if(te!=null){const De=$h(te);if(De){const ft=Hb(e,k),qt=ft==null?null:Th(ft),zt=qt?`Execution time ${De}. Merge phase ${qt}`:`Execution time ${De}. Merging`;return{label:De,title:zt,ariaLabel:zt}}}}if(e.column==="in-progress"){const te=mo(e,k)??Ih(e,k)??ho(e,k);if(te==null)return null;const De=Th(te);return De?{label:De,title:`In progress ${De}`,ariaLabel:`In progress ${De}`}:null}const it=mo(e,k)??ho(e,k);if(it==null)return null;const kt=$h(it);if(!kt)return null;const $t=dE(e);if($t==null)return{label:kt,title:`Execution time ${kt}`,ariaLabel:`Execution time ${kt}`};const se=new Date($t).toLocaleString();return{label:kt,title:`Execution time ${kt}. Completed ${se}`,ariaLabel:`Execution time ${kt}. Completed ${se}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,k]);i.useEffect(()=>{if(!Nt||!Ne){oe(e.id);return}return ee(e.id),()=>{oe(e.id)}},[Nt,Ne,ee,e.id,oe]);const gt=ie.get(`${n??"default"}:${e.id}`),St=e.column==="in-progress"||e.column==="in-review",Lt=i.useMemo(()=>e.steps.map(Me=>`${Me.name}:${Me.status}`).join("|"),[e.steps]),{stats:Yt}=WC(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:Ne,worktree:e.worktree,stepVersion:St?Lt:void 0,pollIntervalMs:St?3e4:void 0}),tn=i.useMemo(()=>BC(e.id,n),[e.id,n]),mn=i.useMemo(()=>{const Me=gt?.prInfo,it=gt?.timestamp,kt=tn?.result?.prInfo,$t=tn?.timestamp?new Date(tn.timestamp).toISOString():void 0,se=e.prInfo,te=e.prInfo?.lastCheckedAt??e.updatedAt;let De=Kl(Me,it,se,te);const ft=it&&it>=te?it:te;return kt&&$t&&(!ft||$t>ft)&&(De=kt),De},[gt,tn,e.prInfo,e.updatedAt]),Qt=i.useMemo(()=>{const Me=gt?.issueInfo,it=gt?.timestamp,kt=tn?.result?.issueInfo,$t=tn?.timestamp?new Date(tn.timestamp).toISOString():void 0,se=e.issueInfo,te=e.issueInfo?.lastCheckedAt??e.updatedAt;let De=Kl(Me,it,se,te);const ft=it&&it>=te?it:te;return kt&&$t&&(!ft||$t>ft)&&(De=kt),De},[gt,tn,e.issueInfo,e.updatedAt]),yn=i.useCallback(Me=>{Me?.stopPropagation(),!(!dt||M)&&(I(!0),_(e.description||""))},[dt,M,e.description]),Gt=i.useCallback(()=>{I(!1),_(e.description||"")},[e.description]),on=i.useCallback(()=>F!==(e.description||""),[F,e.description]),sn=i.useCallback(async()=>{if(!(!l||M)){if(!on()){Gt();return}z(!0);try{await l(e.id,{description:F.trim()||void 0}),r(`Updated ${e.id}`,"success"),I(!1)}catch(Me){r(`Failed to update ${e.id}: ${Ee(Me)}`,"error")}finally{z(!1)}}},[l,e.id,F,M,on,Gt,r]),ln=i.useCallback(Me=>{Me.key==="Enter"&&!Me.shiftKey?(Me.preventDefault(),sn()):Me.key==="Escape"&&(Me.preventDefault(),Gt())},[sn,Gt]),Wt=i.useCallback(()=>{setTimeout(()=>{const Me=document.activeElement;Me===ce.current||Me?.closest(".card-editing-content")||(on()?sn():Gt())},0)},[on,sn,Gt]),ye=i.useCallback(Me=>{dt&&(Me.stopPropagation(),yn(Me))},[dt,yn]),Le=i.useCallback(Me=>{Me.stopPropagation(),yn(Me)},[yn]),Ke=i.useCallback(Me=>{_(Me.target.value);const it=Me.target;it.style.height="auto",it.style.height=it.scrollHeight+"px"},[]),mt=i.useCallback(Me=>{Me.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(it=>{r(`Failed to archive ${e.id}: ${Ee(it)}`,"error")})},[r,c,e.id]),Ve=i.useCallback(Me=>{Me.stopPropagation(),d&&d(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(it=>{r(`Failed to unarchive ${e.id}: ${Ee(it)}`,"error")})},[r,d,e.id]),Pt=i.useCallback(async Me=>{if(Me.stopPropagation(),!(!u||!await W({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await u(e.id),r(`Deleted ${e.id}`,"success")}catch(kt){const $t=Ku(kt);if(!$t||$t.dependentIds.length===0){r(`Failed to delete ${e.id}: ${Ee(kt)}`,"error");return}const se=$t.dependentIds.join(", ");if(!await W({title:"Force Delete Task",message:`${e.id} is a dependency of ${se}.
650
+
651
+ Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await u(e.id,{removeDependencyReferences:!0}),r(`Deleted ${e.id} after removing dependency references`,"success")}catch(De){r(`Failed to delete ${e.id}: ${Ee(De)}`,"error")}}},[r,W,u,e.id]),Ot=i.useCallback(Me=>{Me.stopPropagation(),h?.(e,"changes")},[e,h]),bt=i.useCallback(Me=>{Me.stopPropagation(),R(it=>!it)},[]),Dt=i.useCallback(Me=>{Me.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),Ft=i.useCallback(Me=>{Me.stopPropagation(),A(it=>!it)},[]),Ht=i.useCallback(async(Me,it)=>{if(Me.stopPropagation(),A(!1),!!g)try{const kt=e.steps.some(te=>te.status!=="pending"),$t=(it==="todo"||it==="triage")&&kt;let se;if($t){if(await W({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))se={preserveProgress:!0};else if(!await W({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await g(e.id,it,se),r(`Moved ${e.id} to ${ds[it]}`,"success")}catch(kt){r(`Failed to move ${e.id}: ${Ee(kt)}`,"error")}},[r,W,g,e.id,e.steps]),rn=i.useCallback(async Me=>{if(Me.stopPropagation(),!(!m||P)){$(!0);try{await m(e.id)}catch(it){r(`Failed to retry ${e.id}: ${Ee(it)}`,"error")}finally{$(!1)}}},[r,P,m,e.id]),Xt=`card${S?" dragging":""}${s?" queued":""}${Ae?" agent-active":""}${Ue?" failed":""}${me?" paused":""}${ut?" stuck":""}${Qe?" awaiting-approval":""}${C?" file-drop-target":""}${N?" card-editing":""}${M?" card-saving":""}`,an=(()=>{if(e.column==="in-progress"){const Me=Yt?.filesChanged,it=Me==null||Me===0?e.modifiedFiles?.length:void 0,kt=Me!=null&&Me>0?Me:it;return kt==null||kt===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ot,disabled:!h,children:[t.jsx(Es,{size:12}),t.jsxs("span",{children:[kt," ",kt===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const Me=Yt?.filesChanged,it=Me==null||Me===0?e.modifiedFiles?.length:void 0,kt=Me!=null&&Me>0?Me:it;return kt==null||kt===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ot,disabled:!h,children:[t.jsx(Es,{size:12}),t.jsxs("span",{children:[kt," ",kt===1?"file":"files"," changed"]})]})}if(e.column==="done"){const Me=Yt?.filesChanged,it=e.mergeDetails?.filesChanged,kt=Me??it;if(kt!=null&&kt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ot,disabled:!h,children:[t.jsx(Es,{size:12}),t.jsxs("span",{children:[kt," ",kt===1?"file":"files"," changed"]})]});const $t=e.modifiedFiles?.length;if($t!=null&&$t>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ot,disabled:!h,children:[t.jsx(Es,{size:12}),t.jsxs("span",{children:[$t," ",$t===1?"file":"files"," changed"]})]})}return null})();return N?t.jsx("div",{ref:He,className:Xt,"data-id":e.id,"data-column":e.column,onDoubleClick:ye,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:ce,className:"card-edit-desc-textarea",placeholder:"Task description",value:F,onChange:Ke,onKeyDown:ln,onBlur:Wt,disabled:M,rows:4}),M&&t.jsxs("div",{className:"card-edit-loading",children:[t.jsx("span",{className:"card-edit-loading-spinner"}),t.jsx("span",{className:"card-edit-loading-text",children:"Saving..."})]})]})}):t.jsxs("div",{ref:He,className:Xt,"data-id":e.id,"data-column":e.column,draggable:Je,onDragStart:Je?B:void 0,onDragEnd:Je?ve:void 0,onDragOver:ae,onDragLeave:qe,onDrop:Pe,onClick:Be,onTouchStart:de,onTouchMove:Ie,onTouchEnd:$e,onDoubleClick:ye,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),me&&t.jsx("span",{className:"card-status-badge paused",children:re?"paused by agent":"paused"}),!me&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${Qe?" awaiting-approval":""}${Ah.has(e.status)?" pulsing":""}${Ue?" failed":""}${ut?" stuck":""}`,children:ut?"Stuck":Qe?"Awaiting Approval":lE(e.status)}),ut&&(me||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),Nt&&t.jsx(Pb,{prInfo:mn,issueInfo:Qt}),pt&&t.jsxs("span",{className:"card-agent-created-badge",title:tt,"aria-label":tt,children:[t.jsx(Kn,{size:11,"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:tt}),t.jsx("span",{"aria-hidden":"true",children:"Agent"})]}),xt&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${_e}`,children:_e}),e.executionMode==="fast"&&t.jsxs("span",{className:"card-execution-mode-badge card-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(as,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:Dt,title:`Mission: ${D??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(Rs,{size:11}),ZC(D??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[dt&&t.jsx("button",{className:"card-edit-btn",onClick:Le,title:"Edit task","aria-label":"Edit task",children:t.jsx(qs,{size:12})}),e.column==="triage"&&u&&t.jsx("button",{className:"card-delete-btn",onClick:Pt,title:"Delete task","aria-label":"Delete task",children:t.jsx(_n,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:mt,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&d&&t.jsx("button",{className:"card-unarchive-btn",onClick:Ve,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:xe,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Ft,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":O,children:["Send back",t.jsx(pn,{size:10})]}),O&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:ru["in-progress"].filter(Me=>Me!=="in-review").map(Me=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:it=>Ht(it,Me),children:ds[Me]},Me))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:xe,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Ft,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":O,children:["Move",t.jsx(pn,{size:10})]}),O&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:ru["in-review"].map(Me=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:it=>Ht(it,Me),children:Me==="done"?"Done (no merge)":ds[Me]},Me))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),Ue&&e.error&&t.jsxs("div",{className:"card-error",title:e.error,children:[t.jsx("span",{className:"card-error-icon",children:"⚠"}),t.jsx("span",{className:"card-error-text",children:e.error.length>60?e.error.slice(0,60)+"…":e.error}),m&&t.jsxs("button",{type:"button",className:"btn btn-sm card-error-retry-btn",onClick:rn,disabled:P,children:[t.jsx(Ak,{size:12}),P?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Fh(e.title,Oh)||Fh(e.description,Oh)||e.id}),G&&t.jsxs("div",{className:"card-branch-row","aria-label":"Branch metadata",children:[Se.branch&&t.jsxs("span",{className:"card-branch-chip",title:Se.branch,children:[t.jsx("span",{className:"card-branch-label",children:"Branch"}),t.jsx("span",{className:"card-branch-value",children:Se.branch})]}),Se.baseBranch&&t.jsxs("span",{className:"card-branch-chip",title:Se.baseBranch,children:[t.jsx("span",{className:"card-branch-label",children:"Base"}),t.jsx("span",{className:"card-branch-value",children:Se.baseBranch})]})]}),rt&&(()=>{const Me=be.completed/be.total*100;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"card-progress",children:[t.jsx("div",{className:"card-progress-bar",children:t.jsx("div",{className:"card-progress-fill",style:{width:`${Me}%`,backgroundColor:aE[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[be.completed,"/",be.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:bt,"aria-expanded":U,"aria-label":U?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[be.total," step",be.total===1?"":"s"]}),t.jsx(pn,{size:14,className:`card-steps-toggle-icon${U?" expanded":""}`})]}),U&&t.jsx("div",{className:"card-steps-list",children:be.items.map(it=>{const kt=it.source==="workflow"&&it.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${it.status}${kt?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${it.status==="done"?" completed":""}`,children:it.name}),it.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${it.phase}`,title:"Workflow check",children:"workflow"})]},it.id)})})]})})(),(an||lt||yt)&&t.jsxs("div",{className:"card-footer-row",children:[an,yt&&t.jsx("span",{className:"card-source-provenance",title:ge?`Imported from GitHub: ${ge}`:"Imported from GitHub","aria-label":"Imported from GitHub",children:t.jsx(Fn,{provider:"github",size:"sm"})}),lt&&t.jsxs("span",{className:"card-time-indicator",title:lt.title,"aria-label":lt.ariaLabel,children:[t.jsx(Ji,{size:12}),t.jsx("span",{children:lt.label})]})]}),(e.dependencies&&e.dependencies.length>0||s||e.status==="queued"||e.blockedBy||y&&y.totalCount>0)&&t.jsxs("div",{className:"card-meta",children:[e.dependencies&&e.dependencies.length>0&&t.jsx("div",{className:"card-dep-list",children:e.dependencies.map(Me=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:it=>void st(it,Me),title:`Click to view ${Me}`,children:[t.jsx(vr,{size:12,style:{verticalAlign:"middle"}})," ",Me]},Me))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx($a,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),y&&y.totalCount>0&&t.jsxs("span",{className:`card-fanout-badge${y.staleBlockedByDependentIds.length>0?" card-fanout-badge--stale":""}${y.isHighFanout?" card-fanout-badge--high-impact":""}${y.escalation?" card-fanout-badge--escalated":""}`,"data-tooltip":`Blocking ${y.totalCount} active task(s); ${y.activeTodoCount} waiting in todo${y.isHighFanout?` (high fan-out threshold: ${Wu})`:""}${y.escalation?` · escalated after ${Math.floor(y.escalation.blockingAgeMs/6e4)}m in blocking column`:""}`,children:[t.jsx(Fs,{size:12,style:{verticalAlign:"middle"}}),t.jsxs("span",{children:[y.escalation?"Escalated":y.isHighFanout?"High fan-out":"Blocks"," ",t.jsx("span",{className:"card-fanout-count",children:y.totalCount}),y.isHighFanout?` (${y.activeTodoCount} todo)`:"",y.staleBlockedByDependentIds.length>0?` (${y.staleBlockedByDependentIds.length} stale)`:""]})]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(Ji,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||Re.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Re.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Re.map(Me=>t.jsx(Fn,{provider:Me,size:"sm"},Me))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${Rt?" card-agent-badge--loading":""}`,title:`Assigned to ${Z??e.assignedAgentId}`,children:[t.jsx(Kn,{size:11}),t.jsx("span",{className:"card-agent-badge-text","aria-hidden":"true",children:nE(Z??e.assignedAgentId,15)}),t.jsxs("span",{className:"visually-hidden",children:["Assigned to ",Z??e.assignedAgentId]})]})]}),t.jsx(la,{slotId:"task-card-badge",projectId:n})]})}const Lh=10,wE=300,Oh=140;function Fh(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const Mo=i.memo(yE,vE);Mo.displayName="TaskCard";function kE({label:e,activeTasks:n,queuedTasks:s,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p,blockerFanoutMap:g}){return t.jsxs("div",{className:"worktree-group",children:[t.jsxs("div",{className:"worktree-group-header",children:[t.jsx("span",{className:"worktree-icon",children:e==="Up Next"||e==="Unassigned"?t.jsx(Wy,{size:14}):t.jsx(Fs,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(x=>t.jsx(Mo,{task:x,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p,fanout:g?.get(x.id)},x.id)),s.map(x=>t.jsx(Mo,{task:x,projectId:a,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p,fanout:g?.get(x.id)},x.id))]})}const qb=i.memo(kE);qb.displayName="WorktreeGroup";function zh(e){return e.toLowerCase().replace(/[-_./]/g,"")}function jE(e,n){let s=0;for(let a=0;a<n.length&&s<e.length;a++)e[s]===n[a]&&s++;return s===e.length}function NE(e,n,s){const a=e.length,r=n.length;if(a===0)return!0;if(r===0)return!1;let o=new Array(r+1).fill(0),l=new Array(r+1).fill(0);for(let c=1;c<=a;c++){const d=new Array(r+1);d[0]=c;for(let u=1;u<=r;u++){const m=e[c-1]===n[u-1]?0:1;d[u]=Math.min(l[u]+1,d[u-1]+1,l[u-1]+m),c>=2&&u>=2&&e[c-1]===n[u-2]&&e[c-2]===n[u-1]&&(d[u]=Math.min(d[u],o[u-2]+1))}o=l,l=d}for(let c=0;c<=r;c++)if(l[c]<=s)return!0;return!1}function SE(e,n){const s=zh(e),a=zh(n);if(s.length===0||a.includes(s))return!0;const r=a.split(/\s+/).filter(Boolean);for(const o of r)if(s.length>=3&&jE(s,o)||s.length>=4&&NE(s,o,1))return!0;return!1}function CE(e,n){const s=n.toLowerCase().trim().split(/\s+/).filter(Boolean);return s.length===0?e:e.filter(a=>{const r=`${a.provider} ${a.id} ${a.name}`;return s.every(o=>SE(o,r))})}function Is({models:e,value:n,onChange:s,placeholder:a="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:d,favoriteModels:u=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:f="No change"}){const[p,g]=i.useState(!1),[x,w]=i.useState(""),[b,y]=i.useState(0),[S,j]=i.useState(null),[C,v]=i.useState(null),N=i.useRef(null),I=i.useRef(null),F=i.useRef(null),_=i.useRef(null),M=i.useRef(null),z=i.useMemo(()=>CE(e,x),[e,x]),U=i.useMemo(()=>z.reduce((ee,oe)=>((ee[oe.provider]??=[]).push(oe),ee),{}),[z]),R=i.useMemo(()=>{const ee=[];for(const oe of u){const W=oe.indexOf("/");if(W===-1)continue;const L=oe.slice(0,W),pe=oe.slice(W+1),fe=z.find(B=>B.provider===L&&B.id===pe);fe&&ee.push({model:fe,fullId:oe})}return ee},[u,z]),D=i.useMemo(()=>{const ee=Object.entries(U),oe=new Set(c);return ee.sort(([W],[L])=>{const pe=oe.has(W),fe=oe.has(L);if(pe&&!fe)return-1;if(!pe&&fe)return 1;if(pe&&fe){const B=c.indexOf(W),ve=c.indexOf(L);if(B!==ve)return B-ve}return W.localeCompare(L)})},[U,c]),K=typeof h=="string"&&h.length>0,Z=i.useMemo(()=>{if(!n||K&&n===h)return null;const ee=n.indexOf("/");return ee===-1?null:n.slice(0,ee)},[K,h,n]),ne=i.useMemo(()=>{const ee=[];return K&&ee.push({type:"no-change",value:h,label:f}),ee.push({type:"default",value:"",label:"Use default"}),ee},[K,f,h]),O=i.useMemo(()=>{const ee=[...ne];for(const{model:oe,fullId:W}of R)ee.push({type:"favorite",value:W,label:oe.name,provider:oe.provider});return D.forEach(([oe,W])=>{ee.push({type:"provider",value:`__group_${oe}`,label:oe,provider:oe}),W.forEach(L=>{ee.push({type:"model",value:`${L.provider}/${L.id}`,label:L.name,provider:L.provider})})}),ee},[R,D,ne]),A=i.useMemo(()=>{if(K&&n===h)return f;if(!n)return"Use default";const ee=n.indexOf("/");if(ee===-1)return n;const oe=n.slice(0,ee),W=n.slice(ee+1);return e.find(pe=>pe.provider===oe&&pe.id===W)?.name||n},[K,f,h,n,e]),P=i.useMemo(()=>O.findIndex(ee=>ee.value===n),[O,n]),$=i.useCallback(()=>{const ee=window.visualViewport;return ee&&ee.height>0&&ee.width>0?{width:ee.width,height:ee.height,offsetTop:ee.offsetTop,offsetLeft:ee.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),k=i.useCallback(()=>{const{height:ee}=$(),oe=typeof window.matchMedia=="function",W=oe?window.matchMedia("(max-width: 640px)").matches:!1,L=oe?window.matchMedia("(max-width: 768px)").matches:!1;return ee<=0?320:W?Math.min(ee*.6,360):L?Math.min(ee*.7,420):320},[$]),J=i.useCallback(()=>{const ee=I.current;if(!ee)return;const oe=ee.getBoundingClientRect(),{width:W,height:L,offsetTop:pe,offsetLeft:fe}=$(),B=16,ve=16,Fe=4,ae=k(),qe=oe.bottom-pe,Pe=oe.top-pe,nt=oe.left-fe,Be=L-qe,de=Pe,Ie=Math.max(Be-ve-Fe,160),$e=Math.max(de-ve-Fe,160),st=Be<ae&&de>Be,Ue=Math.max(Math.min(st?$e:Ie,ae),160),me=Math.min(oe.width,W-B*2),re=Math.min(Math.max(nt,B),W-B-me)+fe,_e=st?Math.max(ve+pe,Pe-Ue-Fe+pe):Math.min(qe+Fe+pe,L+pe-ve-Ue);j({top:_e,left:re,width:me,maxHeight:Ue})},[$,k]);i.useEffect(()=>{v(document.body)},[]);const ce=i.useRef(!1);i.useEffect(()=>{if(!p){ce.current=!1;return}if(ce.current||O.length===0)return;const ee=O.findIndex((oe,W)=>W>=(P>=0?P:0)&&oe.type!=="provider");y(ee>=0?ee:0),ce.current=!0},[p,O,P]),i.useEffect(()=>{p&&ce.current&&(y(0),M.current&&(M.current.scrollTop=0))},[x,p]),i.useEffect(()=>{if(!p)return;J();const ee=requestAnimationFrame(()=>_.current?.focus());return()=>cancelAnimationFrame(ee)},[p,J]),i.useEffect(()=>{if(!p)return;const ee=()=>J();window.addEventListener("resize",ee),window.addEventListener("scroll",ee,!0);const oe=window.visualViewport;return oe&&(oe.addEventListener("resize",ee),oe.addEventListener("scroll",ee)),()=>{window.removeEventListener("resize",ee),window.removeEventListener("scroll",ee,!0),oe&&(oe.removeEventListener("resize",ee),oe.removeEventListener("scroll",ee))}},[p,J]),i.useEffect(()=>{if(!p)return;const ee=oe=>{const W=oe.target,L=N.current?.contains(W),pe=F.current?.contains(W);!L&&!pe&&(g(!1),w(""))};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[p]);const je=i.useCallback(ee=>{switch(ee.key){case"ArrowDown":if(ee.preventDefault(),!p)g(!0);else{let oe=b;for(let W=1;W<=O.length;W++){const L=(b+W)%O.length;if(O[L]?.type!=="provider"){oe=L;break}}y(oe)}break;case"ArrowUp":if(ee.preventDefault(),p){let oe=b;for(let W=1;W<=O.length;W++){const L=(b-W+O.length)%O.length;if(O[L]?.type!=="provider"){oe=L;break}}y(oe)}break;case"Enter":if(ee.preventDefault(),p){const oe=O[b];oe&&oe.type!=="provider"&&oe.type!=="favorite"&&(s(oe.value),g(!1),w(""))}else g(!0);break;case"Escape":ee.preventDefault(),g(!1),w("");break;case"Tab":p&&(g(!1),w(""));break}},[p,b,O,s]),He=i.useCallback(ee=>{s(ee),g(!1),w("")},[s]),xe=i.useCallback(()=>{w(""),_.current?.focus()},[]),Ne=i.useCallback(()=>{r||g(ee=>!ee)},[r]);i.useEffect(()=>{if(p&&M.current){const ee=M.current.querySelector(`[data-index="${b}"]`);ee&&typeof ee.scrollIntoView=="function"&&ee.scrollIntoView({block:"nearest"})}},[b,p]);const Y=x.length>0,ie=p&&S?t.jsxs("div",{ref:F,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:je,style:{top:`${S.top}px`,left:`${S.left}px`,width:`${S.width}px`,maxHeight:`${S.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:_,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:x,onChange:ee=>w(ee.target.value),onClick:ee=>ee.stopPropagation()}),Y&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:xe,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[z.length," model",z.length!==1?"s":""]}),t.jsxs("div",{ref:M,className:"model-combobox-list",children:[ne.map((ee,oe)=>t.jsx("div",{"data-index":oe,className:`model-combobox-option ${b===oe?"model-combobox-option--highlighted":""} ${n===ee.value?"model-combobox-option--selected":""}`,onClick:()=>He(ee.value),onMouseEnter:()=>y(oe),role:"option","aria-selected":n===ee.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:ee.label})},`${ee.type}-${ee.value}`)),R.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),R.map(({model:ee,fullId:oe},W)=>{const L=W+ne.length,pe=b===L,fe=n===oe;return t.jsxs("div",{"data-index":L,className:`model-combobox-option model-combobox-option--favorite ${pe?"model-combobox-option--highlighted":""} ${fe?"model-combobox-option--selected":""}`,onClick:()=>He(oe),onMouseEnter:()=>y(L),role:"option","aria-selected":fe,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Fn,{provider:ee.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:ee.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:ee.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:B=>{B.stopPropagation(),m(oe)},title:"Remove from favorites","aria-label":`Remove ${ee.name} from favorites`,children:"★"})]},oe)}),t.jsx("div",{className:"model-combobox-divider"})]}),D.map(([ee,oe])=>{const W=O.findIndex(fe=>fe.value===`__group_${ee}`),L=c.includes(ee),pe=oe.filter(fe=>{const B=`${fe.provider}/${fe.id}`;return!u.includes(B)});return pe.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":W,children:[t.jsx(Fn,{provider:ee,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:ee}),d&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${L?"model-combobox-optgroup-favorite--active":""}`,onClick:fe=>{fe.stopPropagation(),d(ee)},title:L?"Remove from favorites":"Add to favorites","aria-label":L?`Remove ${ee} from favorites`:`Add ${ee} to favorites`,children:"★"})]}),pe.map(fe=>{const B=`${fe.provider}/${fe.id}`,ve=O.findIndex(Pe=>Pe.value===B),Fe=b===ve,ae=n===B,qe=u.includes(B);return t.jsxs("div",{"data-index":ve,className:`model-combobox-option ${Fe?"model-combobox-option--highlighted":""} ${ae?"model-combobox-option--selected":""}`,onClick:()=>He(B),onMouseEnter:()=>y(ve),role:"option","aria-selected":ae,children:[t.jsx("span",{className:"model-combobox-option-text",children:fe.name}),t.jsx("span",{className:"model-combobox-option-id",children:fe.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${qe?"model-combobox-option-favorite--active":""}`,onClick:Pe=>{Pe.stopPropagation(),m(B)},title:qe?"Remove from favorites":"Add to favorites","aria-label":qe?`Remove ${fe.name} from favorites`:`Add ${fe.name} to favorites`,children:qe?"★":"☆"})]},B)})]},ee)}),z.length===0&&Y&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",x,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:N,className:"model-combobox",onKeyDown:je,children:t.jsxs("button",{ref:I,type:"button",id:o,className:"model-combobox-trigger",onClick:Ne,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[Z&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Fn,{provider:Z,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:A||a}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),C&&ie?Ra.createPortal(ie,C):null]})}function Gu(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function zn(e,n){if(typeof window>"u")return null;const s=window.localStorage?.getItem;return typeof s!="function"?null:s.call(window.localStorage,Gu(e,n))}function us(e,n,s){if(typeof window>"u")return;const a=window.localStorage?.setItem;typeof a=="function"&&a.call(window.localStorage,Gu(e,s),n)}function Nr(e,n){if(typeof window>"u")return;const s=window.localStorage?.removeItem;typeof s=="function"&&s.call(window.localStorage,Gu(e,n))}const EE=1e4,_E=1e3;function yc(){const[e,n]=i.useState([]),[s,a]=i.useState(!0),[r,o]=i.useState(null),l=i.useRef(null),c=i.useRef(0),d=i.useCallback(async()=>{try{o(null);const b=await ql();n(b)}catch(b){o(b instanceof Error?b.message:"Failed to fetch nodes")}},[]);i.useEffect(()=>{let b=!1;async function y(){a(!0);try{const j=await ql();b||(n(j),o(null))}catch(j){b||o(j instanceof Error?j.message:"Failed to fetch nodes")}finally{b||a(!1)}}y();const S=()=>{if(document.visibilityState!=="visible")return;const j=Date.now();j-c.current<_E||(c.current=j,d())};return document.addEventListener("visibilitychange",S),()=>{b=!0,document.removeEventListener("visibilitychange",S)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},EE),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async b=>{const{projectMappings:y,...S}=b,j=await t1(S);if(y.length>0)try{await H0(j.id,y)}catch(C){const v=C instanceof Error?C.message:"Failed to persist project mappings";let N="";try{await Zm(j.id)}catch(I){N=I instanceof Error?I.message:"Failed to unregister node after mapping failure"}throw await d(),N?new Error(`${v}. Cleanup also failed: ${N}`):new Error(v)}return await d(),j},[d]),m=i.useCallback(async(b,y)=>{const S=await s1(b,y);return n(j=>j.map(C=>C.id===b?S:C)),S},[]),h=i.useCallback(async b=>{await Zm(b),n(y=>y.filter(S=>S.id!==b))},[]),f=i.useCallback(async b=>{const y=await o1(b);n(S=>S.map(j=>j.id===b?{...j,status:y.status,updatedAt:y.checkedAt}:j))},[]),p=i.useCallback(b=>i1(b),[]),g=i.useCallback(async(b,y)=>{const S=await a1(b,y);return n(j=>j.map(C=>C.id===b?{...C,dockerConfig:S}:C)),S},[]),x=i.useCallback(async b=>{const y=await r1(b);return"persistedVersion"in y?y:{persistedVersion:0,deployedVersion:null,needsRecreate:!1}},[]),w=i.useCallback(async b=>n1(b),[]);return{nodes:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h,healthCheck:f,fetchDockerConfig:p,patchDockerConfig:g,fetchDockerDiff:x,discoverRemoteProjects:w}}const Gr="kb-quick-entry-text",ME=["image/png","image/jpeg","image/gif","image/webp"];function AE(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function Gc(e,n){return e&&n?`${e}/${n}`:""}function Jc(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Vb({onCreate:e,addToast:n,tasks:s=[],availableModels:a,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:d,favoriteModels:u,onToggleFavorite:m,onToggleModelFavorite:h}){const[f,p]=i.useState(()=>typeof window<"u"&&zn(Gr,l)||""),[g,x]=i.useState(!1),[w,b]=i.useState(!1),[y,S]=i.useState(!1),j=i.useRef(null),C=i.useRef(null),v=i.useRef(!1),N=i.useRef(l),[I,F]=i.useState([]),_=i.useRef([]),[M,z]=i.useState([]),[U,R]=i.useState(!1),[D,K]=i.useState(""),[Z,ne]=i.useState(null),[O,A]=i.useState([]),[P,$]=i.useState(void 0),[k,J]=i.useState(!1),[ce,je]=i.useState(!1),[He,xe]=i.useState(!1),[Ne,Y]=i.useState(!1),[ie,ee]=i.useState(!1),[oe,W]=i.useState(null),[L,pe]=i.useState(void 0),[fe,B]=i.useState(void 0),[ve,Fe]=i.useState(void 0),[ae,qe]=i.useState(void 0),[Pe,nt]=i.useState(void 0),[Be,de]=i.useState(void 0),Ie=i.useRef(null),$e=i.useRef(null),st=i.useRef(null),Ue=i.useRef(null),me=i.useRef(null),re=i.useRef(null),_e=i.useRef(null),xt=i.useRef(null),[ut,Qe]=i.useState(null),[vt,Ae]=i.useState(null),[Je,dt]=i.useState(null),[Nt,yt]=i.useState(null),Se=i.useRef(null),G=i.useRef(null),[ge,pt]=i.useState(null),[ke]=i.useState(()=>typeof document<"u"?document.body:null),[tt,Rt]=i.useState(!1),[Re,be]=i.useState(null),[rt,lt]=i.useState(a??[]),[gt,St]=i.useState([]),[Lt,Yt]=i.useState([]),[tn,mn]=i.useState(null),[Qt,yn]=i.useState(void 0),[Gt,on]=i.useState(!1),[sn,ln]=i.useState(Ls),[Wt,ye]=i.useState(void 0),{nodes:Le}=yc(),[Ke,mt]=i.useState(!1),[Ve,Pt]=i.useState(!1),Ot=i.useRef(null),bt=i.useRef(null),[Dt,Ft]=i.useState(null),Ht=d??gt,rn=u??Lt,Xt=!e;i.useEffect(()=>{if(a)lt(a),Rt(!1),be(null);else{let X=!1;return Rt(!0),be(null),Ks().then(E=>{X||(lt(E.models),d||St(E.favoriteProviders),u||Yt(E.favoriteModels))}).catch(E=>{X||be(Ee(E)||"Failed to load models")}).finally(()=>{X||Rt(!1)}),gc(l).then(E=>{X||mn(E)}).catch(()=>{}),()=>{X=!0}}},[a,d,u,l]);const an=Gc(L,fe),Me=Gc(ve,ae),it=Gc(Pe,Be),kt=!!(L&&fe),$t=!!(ve&&ae),se=!!(Pe&&Be),te=Number(kt)+Number($t)+Number(se),De=Qt?tn?.modelPresets?.find(X=>X.id===Qt)?.name??"Models":te>0?`${te} model${te===1?"":"s"}`:"Models",ft=i.useCallback((X,E)=>{if(!X||!E)return"Using default";const ue=rt.find(Ce=>Ce.provider===X&&Ce.id===E);return ue?`${ue.provider}/${ue.id}`:`${X}/${E}`},[rt]);i.useEffect(()=>{p(zn(Gr,l)||"")},[l]),i.useEffect(()=>{typeof window<"u"&&us(Gr,f,l)},[f,l]),i.useEffect(()=>{N.current!==l&&(N.current=l,A([]),$(void 0),ne(null),J(!1),Qe(null))},[l]),i.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),i.useEffect(()=>{_.current=I},[I]),i.useEffect(()=>()=>{_.current.forEach(X=>URL.revokeObjectURL(X.previewUrl))},[]);const qt=i.useCallback(()=>{const X=j.current;if(!X)return;X.style.height="auto";const E=Math.min(X.scrollHeight,200);X.style.height=`${E}px`},[]);i.useEffect(()=>{w&&qt()},[f,w,qt]),i.useEffect(()=>{if(!g&&f===""&&j.current){const X=setTimeout(()=>{j.current?.focus()},0);return()=>clearTimeout(X)}},[g,f]),i.useEffect(()=>{U||K("")},[U]),i.useEffect(()=>{if(!Ke)return;const X=E=>{const ue=E.target,Ce=Ot.current?.contains(ue),We=bt.current?.contains(ue);!Ce&&!We&&mt(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[Ke]),i.useEffect(()=>{if(!ie)return;const X=E=>{const ue=E.target,Ce=Ie.current?.contains(ue),We=$e.current?.contains(ue),At=ue instanceof Element&&ue.closest?.(".model-combobox-dropdown--portal")!=null;!Ce&&!We&&!At&&(ee(!1),W(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[ie]),i.useEffect(()=>{if(!ce)return;const X=E=>{const ue=E.target;me.current?.contains(ue)||re.current?.contains(ue)||(je(!1),Ae(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[ce]),i.useEffect(()=>{if(!k)return;const X=E=>{const ue=E.target;st.current?.contains(ue)||Ue.current?.contains(ue)||(J(!1),Qe(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[k]),i.useEffect(()=>{if(!He)return;const X=E=>{const ue=E.target;_e.current?.contains(ue)||xt.current?.contains(ue)||(xe(!1),dt(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[He]);const zt=i.useCallback(()=>{I.forEach(X=>URL.revokeObjectURL(X.previewUrl)),F([]),C.current&&(C.current.value=""),p(""),z([]),ne(null),J(!1),Qe(null),je(!1),Ae(null),xe(!1),dt(null),pe(void 0),B(void 0),Fe(void 0),qe(void 0),nt(void 0),de(void 0),yn(void 0),on(!1),ln(Ls),ye(void 0),R(!1),ee(!1),yt(null),W(null),mt(!1),Pt(!1),b(!1),S(!1),v.current=!0,j.current&&(j.current.style.height="auto"),typeof window<"u"&&Nr(Gr,l)},[I,l]),Pn=i.useCallback(X=>{if(!X||X.length===0)return;const E=[];for(let ue=0;ue<X.length;ue++){const Ce=X[ue];ME.includes(Ce.type)&&E.push({file:Ce,previewUrl:URL.createObjectURL(Ce)})}E.length>0&&F(ue=>[...ue,...E])},[]),he=i.useCallback(X=>{g||Pn(X.clipboardData?.files)},[Pn,g]),ht=i.useCallback(X=>{F(E=>{const ue=E[X];return ue&&URL.revokeObjectURL(ue.previewUrl),E.filter((Ce,We)=>We!==X)})},[]),at=i.useCallback(async()=>{const X=f.trim();if(!X||g||!e)return;const E=f;x(!0),p("");try{const ue=await e({description:X,column:"triage",dependencies:M.length?M:void 0,...Z?{assignedAgentId:Z}:{},modelPresetId:Qt,modelProvider:kt?L:void 0,modelId:kt?fe:void 0,validatorModelProvider:$t?ve:void 0,validatorModelId:$t?ae:void 0,planningModelProvider:se?Pe:void 0,planningModelId:se?Be:void 0,...Gt?{executionMode:"fast"}:{},priority:sn,nodeId:Wt});if(ue&&I.length>0){const Ce=[];for(const We of I)try{await bc(ue.id,We.file,l)}catch{Ce.push(We.file.name)}Ce.length>0&&n(`Failed to upload: ${Ce.join(", ")}`,"error")}zt()}catch(ue){p(E),n(Ee(ue)||"Failed to create task","error")}finally{x(!1)}},[f,g,e,M,Z,kt,L,fe,$t,ve,ae,se,Pe,Be,I,l,n,zt,Gt,sn,Wt]),wt=i.useCallback(X=>{if(X.key==="Enter"){if(X.shiftKey&&w)return;X.preventDefault(),at()}else if(X.key==="Escape"){if(X.preventDefault(),oe){W(null);return}if(ie){ee(!1),yt(null);return}if(U){R(!1);return}if(Ke){mt(!1);return}if(ce){je(!1),Ae(null);return}if(He){xe(!1),dt(null);return}if(k){J(!1),Qe(null);return}f.trim()&&(p(""),j.current&&(j.current.style.height="auto"),typeof window<"u"&&Nr(Gr,l)),b(!1),S(!1),j.current?.blur()}},[at,f,w,U,k,ce,ie,oe,Ke,He,l,S]),Xe=i.useCallback(()=>{v.current&&(v.current=!1)},[]),Et=i.useCallback(()=>{c&&b(!0)},[c]),Zt=i.useCallback(X=>{z(E=>E.includes(X)?E.filter(ue=>ue!==X):[...E,X])},[]),le=i.useCallback(()=>{const X=window.visualViewport;return X&&X.width>0&&X.height>0?{width:X.width,height:X.height,offsetTop:X.offsetTop,offsetLeft:X.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),ct=i.useCallback(()=>{const X=Ie.current;if(!X)return;const E=X.getBoundingClientRect(),{width:ue,height:Ce,offsetTop:We,offsetLeft:At}=le(),q=16,we=16,Oe=4,It=ue<=768,Kt=Math.min(It?Ce*.6:Ce*.5,360),fn=Math.max(E.width*1.35,320),An=It?Math.min(ue-q*2,360):fn,jn=Math.min(An,Math.max(ue-q*2,240)),En=E.top-We,ts=E.bottom-We,Ln=E.left-At,os=Ce-ts,fs=En,ns=Math.max(os-we-Oe,160),Zn=Math.max(fs-we-Oe,160),es=os<Kt&&fs>os,Ss=Math.max(Math.min(es?Zn:ns,Kt),160),ls=Math.min(Math.max(Ln,q),ue-q-jn)+At,ss=es?Math.max(we+We,En-Ss-Oe+We):Math.min(ts+Oe+We,Ce+We-we-Ss);yt({top:ss,left:ls,width:jn,maxHeight:Ss})},[le]),nn=i.useCallback(()=>{const X=Ot.current?.querySelector(".refine-button");if(!X)return;const E=X.getBoundingClientRect(),{width:ue,height:Ce,offsetTop:We,offsetLeft:At}=le(),q=8,we=12,Oe=4,It=Math.min(200,Math.max(Ce-we*2,160)),Kt=Math.min(200,ue-q*2),fn=E.top-We,An=E.bottom-We,jn=E.left-At,En=Ce-An,ts=fn,Ln=En<It&&ts>En,os=Math.min(Math.max(jn,q),ue-q-Kt)+At,fs=Ln?Math.max(we+We,fn-It-Oe+We):Math.min(An+Oe+We,Ce+We-we-It);Ft({top:fs,left:os})},[le]),Rn=i.useCallback(()=>{const X=Se.current;if(!X)return;const E=X.getBoundingClientRect(),{width:ue,height:Ce,offsetTop:We,offsetLeft:At}=le(),q=16,we=16,Oe=4,It=ue<=768,Kt=Math.min(It?Ce*.6:Ce*.5,320),fn=It?Math.min(ue-q*2,360):Math.max(E.width,280),An=Math.min(fn,Math.max(ue-q*2,240)),jn=E.top-We,En=E.bottom-We,ts=E.left-At,Ln=Ce-En,os=jn,fs=Math.max(Ln-we-Oe,200),ns=Math.max(os-we-Oe,200),Zn=Ln<Kt&&os>Ln,es=Math.max(Math.min(Zn?ns:fs,Kt),200),Ss=Math.min(Math.max(ts,q),ue-q-An)+At,ls=Zn?Math.max(we+We,jn-es-Oe+We):Math.min(En+Oe+We,Ce+We-we-es);pt({top:ls,left:Ss,width:An,maxHeight:es})},[le]),Un=i.useCallback(()=>{const X=st.current?.querySelector("button");if(!X)return;const E=X.getBoundingClientRect(),{width:ue,height:Ce,offsetTop:We,offsetLeft:At}=le(),q=16,we=16,Oe=4,It=ue<=768,Kt=Math.min(It?Ce*.6:Ce*.5,320),fn=It?Math.min(ue-q*2,280):Math.max(E.width,240),An=Math.min(fn,Math.max(ue-q*2,200)),jn=E.top-We,En=E.bottom-We,ts=E.left-At,Ln=Ce-En,os=jn,fs=Math.max(Ln-we-Oe,160),ns=Math.max(os-we-Oe,160),Zn=Ln<Kt&&os>Ln,es=Math.max(Math.min(Zn?ns:fs,Kt),160),Ss=Math.min(Math.max(ts,q),ue-q-An)+At,ls=Zn?Math.max(we+We,jn-es-Oe+We):Math.min(En+Oe+We,Ce+We-we-es);Qe({top:ls,left:Ss,width:An,maxHeight:es})},[le]),wn=i.useCallback(()=>{const X=me.current?.querySelector("button");if(!X)return;const E=X.getBoundingClientRect(),{width:ue,height:Ce,offsetTop:We,offsetLeft:At}=le(),q=16,we=16,Oe=4,It=ue<=768,Kt=Math.min(It?Ce*.6:Ce*.5,320),fn=It?Math.min(ue-q*2,280):Math.max(E.width,240),An=Math.min(fn,Math.max(ue-q*2,200)),jn=E.top-We,En=E.bottom-We,ts=E.left-At,Ln=Ce-En,os=jn,fs=Math.max(Ln-we-Oe,160),ns=Math.max(os-we-Oe,160),Zn=Ln<Kt&&os>Ln,es=Math.max(Math.min(Zn?ns:fs,Kt),160),Ss=Math.min(Math.max(ts,q),ue-q-An)+At,ls=Zn?Math.max(we+We,jn-es-Oe+We):Math.min(En+Oe+We,Ce+We-we-es);Ae({top:ls,left:Ss,width:An,maxHeight:es})},[le]),rs=i.useCallback(()=>{const X=_e.current?.querySelector("button");if(!X)return;const E=X.getBoundingClientRect(),{width:ue,height:Ce,offsetTop:We,offsetLeft:At}=le(),q=16,we=16,Oe=4,It=220,Kt=Math.min(Math.max(E.width,200),Math.max(ue-q*2,200)),fn=E.top-We,An=E.bottom-We,jn=E.left-At,En=Ce-An,ts=fn,Ln=Math.max(En-we-Oe,160),os=Math.max(ts-we-Oe,160),fs=En<It&&ts>En,ns=Math.max(Math.min(fs?os:Ln,It),160),Zn=Math.min(Math.max(jn,q),ue-q-Kt)+At,es=fs?Math.max(we+We,fn-ns-Oe+We):Math.min(An+Oe+We,Ce+We-we-ns);dt({top:es,left:Zn,width:Kt,maxHeight:ns})},[le]);i.useEffect(()=>{if(!ie)return;const X=()=>ct();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const E=window.visualViewport;return E&&(E.addEventListener("resize",X),E.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),E&&(E.removeEventListener("resize",X),E.removeEventListener("scroll",X))}},[ie,ct]),i.useEffect(()=>{if(!Ke)return;const X=()=>nn();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const E=window.visualViewport;return E&&(E.addEventListener("resize",X),E.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),E&&(E.removeEventListener("resize",X),E.removeEventListener("scroll",X))}},[Ke,nn]),i.useEffect(()=>{if(!U)return;const X=()=>Rn();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const E=window.visualViewport;return E&&(E.addEventListener("resize",X),E.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),E&&(E.removeEventListener("resize",X),E.removeEventListener("scroll",X))}},[U,Rn]),i.useEffect(()=>{if(!k)return;const X=()=>Un();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const E=window.visualViewport;return E&&(E.addEventListener("resize",X),E.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),E&&(E.removeEventListener("resize",X),E.removeEventListener("scroll",X))}},[k,Un]),i.useEffect(()=>{if(!ce)return;const X=()=>wn();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const E=window.visualViewport;return E&&(E.addEventListener("resize",X),E.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),E&&(E.removeEventListener("resize",X),E.removeEventListener("scroll",X))}},[ce,wn]),i.useEffect(()=>{if(!He)return;const X=()=>rs();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const E=window.visualViewport;return E&&(E.addEventListener("resize",X),E.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),E&&(E.removeEventListener("resize",X),E.removeEventListener("scroll",X))}},[He,rs]);const _s=i.useCallback(X=>{const E=Jc(X);nt(E.provider),de(E.modelId)},[]),bn=i.useCallback(X=>{const E=Jc(X);pe(E.provider),B(E.modelId)},[]),Ut=i.useCallback(X=>{const E=Jc(X);Fe(E.provider),qe(E.modelId)},[]),xs=i.useCallback(async X=>{if(m){m(X);return}const E=gt,Ce=E.includes(X)?E.filter(We=>We!==X):[X,...E];St(Ce);try{await Dn({favoriteProviders:Ce,favoriteModels:Lt})}catch{St(E)}},[gt,Lt,m]),xn=i.useCallback(async X=>{if(h){h(X);return}const E=Lt,Ce=E.includes(X)?E.filter(We=>We!==X):[X,...E];Yt(Ce);try{await Dn({favoriteProviders:gt,favoriteModels:Ce})}catch{Yt(E)}},[Lt,gt,h]),Xn=i.useCallback(()=>{const X=f.trim();if(!X){n("Enter a description first","error");return}r?.(X),zt()},[f,r,n,zt]),$n=i.useCallback(()=>{const X=f.trim();if(!X){n("Enter a description first","error");return}o?.(X),zt()},[f,o,n,zt]),vs=i.useCallback(()=>{at()},[at]),ms=i.useCallback(async X=>{const E=f.trim();if(!(!E||Ve)){mt(!1),Pt(!0);try{const ue=await cb(E,X,l);p(ue),n("Description refined with AI","success"),j.current&&(j.current.style.height="auto",j.current.style.height=`${Math.min(j.current.scrollHeight,200)}px`)}catch(ue){const Ce=db(ue);n(Ce,"error")}finally{Pt(!1)}}},[f,Ve,n,l]),hs=(X,E)=>X.length>E?X.slice(0,E)+"…":X,Jn=i.useCallback(async()=>{if(a){lt(a),be(null),Rt(!1);return}Rt(!0),be(null);try{const X=await Ks();lt(X.models),d||St(X.favoriteProviders),u||Yt(X.favoriteModels)}catch(X){be(Ee(X)||"Failed to load models")}finally{Rt(!1)}},[a,d,u]),ps=i.useCallback(async()=>{if(O.length>0&&P===l){J(!0),Un();return}Y(!0);try{const X=await $r(void 0,l);A(X),$(l),J(!0),Un()}catch(X){const E=Ee(X);n(E?`Failed to load agents: ${E}`:"Failed to load agents","error"),J(!1)}finally{Y(!1)}},[O.length,P,l,n,Un]),Yn=(Z?O.find(X=>X.id===Z):void 0)?.name??Z,ys=Wt?Le.find(X=>X.id===Wt):void 0,ws=y,Ms=i.useCallback(()=>{S(X=>{const E=!X;return b(E),E})},[]);return t.jsxs("div",{className:`quick-entry-box ${y?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:j,className:`quick-entry-input ${w?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:X=>p(X.target.value),onKeyDown:wt,onPaste:he,onFocus:Et,onBlur:Xe,disabled:g||Xt,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":y})}),t.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:Ms,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(Pi,{size:14}):t.jsx(pn,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!ws,"aria-hidden":!ws,children:[ws&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Xn,onMouseDown:X=>X.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx($i,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:$n,onMouseDown:X=>X.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(hc,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Ot,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Ve?"refine-button--loading":""}`,onClick:()=>{mt(X=>{const E=!X;return E?nn():Ft(null),E})},disabled:!f.trim()||Ve,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(gs,{size:12,style:{verticalAlign:"middle"}}),Ve?"Refining...":"Refine"]}),Ke&&ke&&Dt&&Ra.createPortal(t.jsxs("div",{ref:bt,className:"refine-menu refine-menu--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${Dt.top}px`,left:`${Dt.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>ms("clarify"),"data-testid":"refine-clarify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Clarify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Make the description clearer and more specific"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>ms("add-details"),"data-testid":"refine-add-details",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Add details"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Add implementation details and context"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>ms("expand"),"data-testid":"refine-expand",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Expand"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Expand into a more comprehensive description"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>ms("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]}),ke)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:Se,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{R(X=>{const E=!X;return E?(ee(!1),yt(null),W(null),J(!1),Qe(null),je(!1),Ae(null),xe(!1),dt(null),Rn()):pt(null),E})},children:[t.jsx(vr,{size:12,style:{verticalAlign:"middle"}}),M.length>0?`${M.length} deps`:"Deps"]})}),U&&ke&&ge&&(()=>{const X=D.toLowerCase(),E=(X?s.filter(ue=>ue.id.toLowerCase().includes(X)||ue.title&&ue.title.toLowerCase().includes(X)||ue.description&&ue.description.toLowerCase().includes(X)):[...s]).sort((ue,Ce)=>{const We=Ce.createdAt.localeCompare(ue.createdAt);if(We!==0)return We;const At=parseInt(ue.id.slice(ue.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ce.id.slice(Ce.id.lastIndexOf("-")+1),10)||0)-At});return Ra.createPortal(t.jsxs("div",{ref:G,className:"dep-dropdown dep-dropdown--portal",onMouseDown:ue=>ue.preventDefault(),style:{position:"fixed",top:`${ge.top}px`,left:`${ge.left}px`,width:`${ge.width}px`,maxHeight:ge.maxHeight?`${ge.maxHeight}px`:void 0,overflowY:ge.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:D,onChange:ue=>K(ue.target.value),onClick:ue=>ue.stopPropagation()}),E.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):E.map(ue=>t.jsxs("div",{className:`dep-dropdown-item${M.includes(ue.id)?" selected":""}`,onMouseDown:Ce=>Ce.preventDefault(),onClick:()=>Zt(ue.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:ue.id}),t.jsx("span",{className:"dep-dropdown-title",children:hs(ue.title||ue.description||ue.id,60)})]},ue.id))]}),ke)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>C.current?.click(),children:[t.jsx(Xg,{size:12,style:{verticalAlign:"middle"}}),I.length>0?`Attach (${I.length})`:"Attach"]}),t.jsxs("button",{ref:Ie,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{R(!1),J(!1),Qe(null),je(!1),Ae(null),xe(!1),dt(null),W(null),ee(!0),ct()},children:[t.jsx(So,{size:12,style:{verticalAlign:"middle"}}),De]}),t.jsx("div",{className:"node-trigger-wrap",ref:me,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{R(!1),J(!1),Qe(null),ee(!1),yt(null),W(null),xe(!1),dt(null),je(X=>{const E=!X;return E?wn():Ae(null),E})},children:[t.jsx(Co,{size:12,style:{verticalAlign:"middle"}}),` ${ys?.name??"Node"}`,ys&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Oa,{status:ys.status,showLabel:!0})})]})}),ce&&ke&&vt&&Ra.createPortal(t.jsxs("div",{ref:re,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${vt.top}px`,left:`${vt.left}px`,width:`${vt.width}px`,maxHeight:vt.maxHeight?`${vt.maxHeight}px`:void 0,overflowY:vt.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select execution node"}),t.jsx("div",{className:`dep-dropdown-item node-picker-item${Wt==null?" selected":""}`,onMouseDown:X=>X.preventDefault(),onClick:()=>{ye(void 0),je(!1),Ae(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),Le.map(X=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${Wt===X.id?" selected":""}`,onMouseDown:E=>E.preventDefault(),onClick:()=>{ye(X.id),je(!1),Ae(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Oa,{status:X.status})}),t.jsx("span",{className:"node-picker-item-name",children:X.name}),t.jsx("span",{className:"node-picker-item-status",children:AE(X.status)})]},X.id))]}),ke),t.jsx("div",{className:"agent-trigger-wrap",ref:st,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{k?(J(!1),Qe(null)):(je(!1),Ae(null),xe(!1),dt(null),ps())},"data-testid":"quick-entry-agent-button",children:[t.jsx(Kn,{size:12,style:{verticalAlign:"middle"}}),Yn?` ${Yn}`:" Agent"]})}),k&&ke&&ut&&Ra.createPortal(t.jsxs("div",{ref:Ue,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${ut.top}px`,left:`${ut.left}px`,width:`${ut.width}px`,maxHeight:ut.maxHeight?`${ut.maxHeight}px`:void 0,overflowY:ut.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Ne&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Ne&&O.map(X=>t.jsxs("div",{className:`dep-dropdown-item${Z===X.id?" selected":""}`,onMouseDown:E=>E.preventDefault(),onClick:()=>{ne(X.id===Z?null:X.id),J(!1),Qe(null)},children:[t.jsx(Kn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:X.role}),t.jsx("span",{className:"dep-dropdown-title",children:X.name})]},X.id)),!Ne&&O.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),Z&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:X=>X.preventDefault(),onClick:()=>{ne(null),J(!1),Qe(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),ke),t.jsx("div",{className:"priority-trigger-wrap",ref:_e,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-priority-button",onClick:()=>{R(!1),J(!1),Qe(null),je(!1),Ae(null),ee(!1),yt(null),W(null),xe(X=>{const E=!X;return E?rs():dt(null),E})},children:[t.jsx(yw,{size:12,style:{verticalAlign:"middle"}}),` ${sn[0].toUpperCase()}${sn.slice(1)}`]})}),He&&ke&&Je&&Ra.createPortal(t.jsxs("div",{ref:xt,className:"dep-dropdown priority-picker-dropdown priority-picker-dropdown--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${Je.top}px`,left:`${Je.left}px`,width:`${Je.width}px`,maxHeight:Je.maxHeight?`${Je.maxHeight}px`:void 0,overflowY:Je.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select priority"}),pa.map(X=>{const E=`${X[0].toUpperCase()}${X.slice(1)}`;return t.jsx("div",{className:`dep-dropdown-item${sn===X?" selected":""}`,"data-testid":`quick-entry-priority-option-${X}`,onMouseDown:ue=>ue.preventDefault(),onClick:()=>{ln(X),xe(!1),dt(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:E})},X)})]}),ke),t.jsx("button",{type:"button",className:`btn btn-sm ${Gt?"btn-primary":""}`,onClick:()=>on(X=>!X),onMouseDown:X=>X.preventDefault(),"aria-pressed":Gt,"data-testid":"quick-entry-fast-toggle",title:"Toggle fast execution mode",children:"Fast"}),t.jsxs("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:vs,onMouseDown:X=>X.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(eb,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),I.length>0&&t.jsx("div",{className:"inline-create-previews",children:I.map((X,E)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:X.previewUrl,alt:X.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>ht(E),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${E}`,children:"×"})]},X.previewUrl))}),ie&&ke&&Nt&&Ra.createPortal(t.jsx("div",{ref:$e,className:"model-nested-menu model-nested-menu--portal",onMouseDown:X=>X.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${Nt.top}px`,left:`${Nt.left}px`,width:`${Nt.width}px`,maxHeight:Nt.maxHeight?`${Nt.maxHeight}px`:void 0,overflowY:Nt.maxHeight?"auto":void 0},children:oe===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${se?"model-menu-item--active":""}`,onClick:()=>W("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx($i,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:se?ft(Pe,Be):"Using default"}),t.jsx(On,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${kt?"model-menu-item--active":""}`,onClick:()=>W("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(gs,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:kt?ft(L,fe):"Using default"}),t.jsx(On,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${$t?"model-menu-item--active":""}`,onClick:()=>W("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(So,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:$t?ft(ve,ae):"Using default"}),t.jsx(On,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]})]}):t.jsxs("div",{className:"model-submenu",children:[t.jsxs("button",{type:"button",className:"model-submenu-back",onClick:()=>W(null),"data-testid":"model-submenu-back",children:[t.jsx(pn,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[oe==="plan"&&"Plan Model",oe==="executor"&&"Executor Model",oe==="validator"&&"Reviewer Model"]}),t.jsx(Is,{models:rt,value:oe==="plan"?it:oe==="executor"?an:Me,onChange:oe==="plan"?_s:oe==="executor"?bn:Ut,placeholder:"Using default",disabled:tt,id:`model-${oe}-select`,label:`${oe} model`,favoriteProviders:Ht,onToggleFavorite:xs,favoriteModels:rn,onToggleModelFavorite:xn}),Re&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:Re}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:Jn,children:"Retry"})]})]})}),ke)]}),t.jsx("input",{ref:C,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:X=>{Pn(X.target.files),X.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function RE(e){return Hu(e)||e}function IE(e){const n=new Map(e.map(l=>[l.id,l])),s=[],a=new Set,r=new Set;function o(l){if(a.has(l)||r.has(l))return;r.add(l);const c=n.get(l);if(c)for(const d of c.dependencies||[])n.has(d)&&o(d);r.delete(l),a.add(l),s.push(l)}for(const l of e)o(l.id);return s}function TE(e,n,s){const a=e.filter(g=>g.worktree),r=e.filter(g=>!g.worktree),o=new Map;for(const g of a){const x=g.worktree,w=o.get(x)||[];w.push(g),o.set(x,w)}const l=new Map(n.map(g=>[g.id,g])),d=n.filter(g=>g.column==="todo").filter(g=>!g.paused&&(g.dependencies||[]).every(x=>{const w=l.get(x);return w&&(w.column==="done"||w.column==="in-review"||w.column==="archived")})),m=IE(d).map(g=>l.get(g)).filter(g=>g!==void 0&&d.includes(g)),h=[],f=Array.from(o.keys());for(const g of f)h.push({label:RE(g),activeTasks:o.get(g),queuedTasks:[]});r.length>0&&h.push({label:"Unassigned",activeTasks:r,queuedTasks:[]});const p=m.slice(0,s);return p.length>0&&h.push({label:"Up Next",activeTasks:[],queuedTasks:p}),h}const Bh=100,Yc=50,Uh=25;function PE({column:e,tasks:n,projectId:s,maxConcurrent:a,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:d,onNewTask:u,autoMerge:m,onToggleAutoMerge:h,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:w,onDeleteTask:b,onArchiveAllDone:y,collapsed:S,onToggleCollapse:j,allTasks:C,availableModels:v,onPlanningMode:N,onSubtaskBreakdown:I,onOpenDetailWithTab:F,favoriteProviders:_,favoriteModels:M,onToggleFavorite:z,onToggleModelFavorite:U,isSearchActive:R,taskStuckTimeoutMs:D,onOpenMission:K,lastFetchTimeMs:Z,workflowStepNameLookup:ne,blockerFanoutMap:O}){const[A,P]=i.useState(!1),[$,k]=i.useState(Yc),[J,ce]=i.useState(!1),[je,He]=i.useState(!1),[xe,Ne]=i.useState(!1),[Y,ie]=i.useState(!1),ee=i.useRef(null),oe=IC(n.length),{confirm:W}=pi();i.useEffect(()=>{if(!J)return;function _e(ut){ee.current?.contains(ut.target)||ce(!1)}function xt(ut){ut.key==="Escape"&&ce(!1)}return document.addEventListener("mousedown",_e),document.addEventListener("keydown",xt),()=>{document.removeEventListener("mousedown",_e),document.removeEventListener("keydown",xt)}},[J]);const L=e==="archived",pe=L&&S,fe=!L&&!R&&e!=="in-progress"&&n.length>Bh;i.useEffect(()=>{k(_e=>e==="in-progress"||L||n.length<=Bh?Yc:Math.min(Math.max(_e,Yc),n.length))},[e,L,n.length]);const B=i.useCallback(_e=>{L||(_e.preventDefault(),_e.dataTransfer.dropEffect="move",P(!0))},[L]),ve=i.useCallback(_e=>{_e.currentTarget.contains(_e.relatedTarget)||P(!1)},[]),Fe=i.useCallback(async _e=>{_e.preventDefault(),P(!1);const xt=_e.dataTransfer.getData("text/plain");if(!xt)return;const ut=n.find(Qe=>Qe.id===xt);if(!(ut&&ut.column===e))try{const vt=(C?.find(dt=>dt.id===xt)??ut)?.steps.some(dt=>dt.status!=="pending")??!1,Ae=(e==="todo"||e==="triage")&&vt;let Je;if(Ae){if(await W({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Je={preserveProgress:!0};else if(!await W({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(xt,e,Je)}catch(Qe){c(Ee(Qe),"error")}},[c,C,e,W,r,n]),ae=i.useMemo(()=>e!=="in-progress"?[]:TE(n,n,a),[e,n,a]),qe=i.useMemo(()=>fe?n.slice(0,$):n,[fe,n,$]),Pe=Math.max(0,n.length-qe.length),nt=i.useCallback(()=>{k(_e=>Math.min(_e+Uh,n.length))},[n.length]),Be=i.useCallback(async()=>{if(ce(!1),!(n.length===0||!await W({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){He(!0);try{const xt=await Promise.allSettled(n.map(vt=>r(vt.id,"triage"))),ut=xt.filter(vt=>vt.status==="rejected").length,Qe=xt.length-ut;ut===0?c(`Moved ${Qe} task${Qe===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${Qe} of ${xt.length} tasks; ${ut} failed`,"error")}finally{He(!1)}}},[n,r,c,W]),de=i.useMemo(()=>n.filter(_e=>!_e.paused&&!_e.assignedAgentId),[n]),Ie=de.length,$e=e==="todo"||e==="in-progress"||e==="in-review",st=je||xe||Y,Ue=i.useCallback(async()=>{if(!(!o||(ce(!1),Ie===0)||!await W({title:"Stop All Tasks",message:`Stop all ${Ie} ${ds[e].toLowerCase()} task${Ie===1?"":"s"}?`,danger:!0}))){Ne(!0);try{const xt=await Promise.allSettled(de.map(vt=>o(vt.id))),ut=xt.filter(vt=>vt.status==="rejected").length,Qe=xt.length-ut;ut===0?c(`Stopped ${Qe} task${Qe===1?"":"s"}`,"success"):c(`Stopped ${Qe} of ${xt.length} tasks; ${ut} failed`,"error")}finally{Ne(!1)}}},[o,Ie,e,de,c,W]),me=i.useCallback(async()=>{if(ce(!1),n.length===0||!await W({title:"Move All to Todo",message:`Move all ${n.length} ${ds[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))return;const xt=n.some(Qe=>Qe.steps.some(vt=>vt.status!=="pending"));let ut=!1;if(xt){if(await W({title:"Preserve Progress?",message:"Some tasks have completed steps. Keep progress before moving to Todo?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))ut=!0;else if(!await W({title:"Reset Progress?",message:"Reset step progress for tasks before moving to Todo?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}ie(!0);try{const Qe=await Promise.allSettled(n.map(Je=>r(Je.id,"todo",ut?{preserveProgress:!0}:void 0))),vt=Qe.filter(Je=>Je.status==="rejected").length,Ae=Qe.length-vt;vt===0?c(`Moved ${Ae} task${Ae===1?"":"s"} to Todo`,"success"):c(`Moved ${Ae} of ${Qe.length} tasks to Todo; ${vt} failed`,"error")}finally{ie(!1)}},[n,e,r,c,W]),re=i.useCallback(async()=>{if(!(!y||n.length===0||!await W({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const xt=await y();c(`Archived ${xt.length} tasks`,"success")}catch(xt){c(Ee(xt)||"Failed to archive tasks","error")}},[y,n.length,c,W]);return t.jsxs("div",{className:`column${A?" drag-over":""}${L?" column-archived":""}${pe?" column-collapsed":""}`,"data-column":e,onDragOver:B,onDragLeave:ve,onDrop:Fe,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:ds[e]}),t.jsx("span",{className:`column-count${oe?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),u&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:u,children:"+ New Task"}),e==="done"&&y&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:re,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(To,{})}),L&&j&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:j,title:S?"Expand archived tasks":"Collapse archived tasks","aria-label":S?"Expand archived tasks":"Collapse archived tasks",children:S?t.jsx(pn,{size:16}):t.jsx(Pi,{size:16})}),$e&&t.jsxs("div",{className:"column-menu",ref:ee,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ce(_e=>!_e),"aria-haspopup":"menu","aria-expanded":J,"aria-label":`${ds[e]} column actions`,title:"Column actions",disabled:st,children:t.jsx(tw,{})}),J&&t.jsxs("div",{className:"column-menu-popover",role:"menu",children:[e==="todo"&&t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Be(),disabled:n.length===0||je,children:["Replan All",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Planning"]})]}),(e==="in-progress"||e==="in-review")&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Ue(),disabled:Ie===0||xe||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":Ie===0?"No manually pausable tasks":`Pause ${Ie} active unassigned task${Ie===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void me(),disabled:n.length===0||Y,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!pe&&t.jsx("p",{className:"column-desc",children:AC[e]}),!pe&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&d&&t.jsx(Vb,{onCreate:d,addToast:c,tasks:C??[],availableModels:v,onPlanningMode:N,onSubtaskBreakdown:I,projectId:s,autoExpand:!1,favoriteProviders:_,favoriteModels:M,onToggleFavorite:z,onToggleModelFavorite:U}),e==="in-progress"?ae.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):ae.map(_e=>t.jsx(qb,{label:_e.label,activeTasks:_e.activeTasks,queuedTasks:_e.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:F,taskStuckTimeoutMs:D,onOpenMission:K,lastFetchTimeMs:Z,workflowStepNameLookup:ne,blockerFanoutMap:O},_e.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[qe.map(_e=>t.jsx(Mo,{task:_e,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:w,onDeleteTask:b,onOpenDetailWithTab:F,taskStuckTimeoutMs:D,onOpenMission:K,onMoveTask:r,lastFetchTimeMs:Z,workflowStepNameLookup:ne,fanout:O?.get(_e.id)},_e.id)),fe&&Pe>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:nt,children:["Load ",Math.min(Uh,Pe)," more (",Pe," remaining)"]})]}),t.jsx(la,{slotId:"board-column-footer",projectId:s})]})]})}const Wb=i.memo(PE);Wb.displayName="Column";const $E=new Set(["in-progress","in-review"]),DE=new Set(["triage","todo","in-progress","in-review"]);function LE(e,n){return!e||e.column==="done"||e.column==="archived"||e.column==="in-review"&&e.paused===!0||e.column==="in-review"&&e.status==="failed"&&(e.mergeRetries??0)>=n}function OE(e,n){const s=Date.parse(e.columnMovedAt??e.updatedAt);return Number.isFinite(s)?Math.max(0,n-s):0}function FE(e,n,s={}){const a=s.nowMs??Date.now(),r=s.highFanoutTodoThreshold??Wu,o=s.staleHighFanoutAgeThresholdMs??Rb,l=new Map(e.map(m=>[m.id,m])),c=new Map,d=m=>{let h=c.get(m);return h||(h={dependentIds:[],blockedByDependentIds:[],activeCount:0,activeTodoCount:0},c.set(m,h)),h};for(const m of e){const h=DE.has(m.column),f=m.column==="todo";for(const p of m.dependencies??[]){if(!p)continue;const g=d(p);g.dependentIds.push(m.id),h&&(g.activeCount+=1),f&&(g.activeTodoCount+=1)}if(m.blockedBy){const p=d(m.blockedBy);p.dependentIds.push(m.id),p.blockedByDependentIds.push(m.id),h&&(p.activeCount+=1),f&&(p.activeTodoCount+=1)}}const u=new Map;for(const[m,h]of c){const f=l.get(m),p=LE(f,n)?[...h.blockedByDependentIds]:[],g=h.activeTodoCount>=r,x=f?OE(f,a):0,w=f?.column,b=w!==void 0&&g&&$E.has(w)&&x>=o;u.set(m,{totalCount:h.activeCount,activeTodoCount:h.activeTodoCount,dependentIds:h.dependentIds,staleBlockedByDependentIds:p,isHighFanout:g,escalation:b?{blockerId:m,activeTodoCount:h.activeTodoCount,totalActiveCount:h.activeCount,blockingAgeMs:x}:void 0})}return u}const zE=3;function Ju(e,n={}){return FE(e,zE,{staleHighFanoutAgeThresholdMs:n.staleHighFanoutAgeThresholdMs})}function BE(e,n={}){return i.useMemo(()=>Ju(e,n),[e,n.staleHighFanoutAgeThresholdMs])}function UE(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}const Hh=new Map;function HE(e,n){if(e.size!==n.size)return!1;for(const[s,a]of e)if(n.get(s)!==a)return!1;return!0}function qE({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:d,autoMerge:u,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:x,onDeleteTask:w,onArchiveAllDone:b,onLoadArchivedTasks:y,searchQuery:S="",availableModels:j,onPlanningMode:C,onSubtaskBreakdown:v,onOpenDetailWithTab:N,favoriteProviders:I,favoriteModels:F,onToggleFavorite:_,onToggleModelFavorite:M,taskStuckTimeoutMs:z,onOpenMission:U,staleHighFanoutBlockerAgeThresholdMs:R,lastFetchTimeMs:D}){const[K,Z]=i.useState(!0),ne=i.useRef(!1),{fetchBatch:O}=UC(n),A=i.useRef(null),[P,$]=i.useState(Hh),k=BE(e,{staleHighFanoutAgeThresholdMs:R}),J=S.trim()!=="",ce=i.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),je=i.useCallback(()=>{Z(Ne=>{const Y=!Ne;return!Y&&!ne.current&&y&&(ne.current=!0,y()),Y})},[y]),He=i.useMemo(()=>{const Ne={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};for(const ee of e){const oe=Vu(ee.column)?ee.column:Wl;(Ne[oe]??Ne[Wl]).push(ee)}const Y=ce.current,ie={};for(const ee of oa){const oe=Ib(Ne[ee],ee);ie[ee]=UE(Y[ee],oe)?Y[ee]:oe}return ce.current=ie,ie},[e]);i.useEffect(()=>{let Ne=!1;return Uo(n).then(Y=>{if(Ne)return;const ie=new Map(Y.map(ee=>[ee.id,ee.name]));$(ee=>HE(ee,ie)?ee:ie)}).catch(()=>{Ne||$(Y=>Y.size===0?Y:Hh)}),()=>{Ne=!0}},[n]);const xe=i.useMemo(()=>e.filter(Ne=>Ne.prInfo||Ne.issueInfo).map(Ne=>Ne.id),[e]);return i.useEffect(()=>{if(xe.length!==0)return A.current&&clearTimeout(A.current),A.current=setTimeout(()=>{const Ne=[];for(let Y=0;Y<xe.length;Y+=50)Ne.push(xe.slice(Y,Y+50));Ne.forEach(Y=>{O(Y)})},500),()=>{A.current&&clearTimeout(A.current)}},[xe,O]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:oa.map(Ne=>t.jsx(Wb,{column:Ne,tasks:He[Ne],projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:x,onDeleteTask:w,allTasks:e,availableModels:j,onOpenDetailWithTab:N,favoriteProviders:I,favoriteModels:F,onToggleFavorite:_,onToggleModelFavorite:M,isSearchActive:J,taskStuckTimeoutMs:z,onOpenMission:U,lastFetchTimeMs:D,workflowStepNameLookup:P,blockerFanoutMap:k,...Ne==="triage"?{onQuickCreate:c,onNewTask:d,onPlanningMode:C,onSubtaskBreakdown:v}:{},...Ne==="in-review"?{autoMerge:u,onToggleAutoMerge:m}:{},...Ne==="done"?{onArchiveAllDone:b}:{},...Ne==="archived"?{collapsed:K,onToggleCollapse:je}:{}},Ne))})})}function Li(e,n,s){i.useEffect(()=>{if(!n)return;const a=e.current;if(!a)return;if(typeof window<"u"&&("ontouchstart"in window||navigator.maxTouchPoints>0)&&window.innerWidth<=768){a.style.removeProperty("width"),a.style.removeProperty("height");return}try{const u=localStorage.getItem(s);if(u){const{width:m,height:h}=JSON.parse(u);typeof m=="number"&&m>0&&(a.style.width=`${m}px`),typeof h=="number"&&h>0&&(a.style.height=`${h}px`)}}catch{}if(typeof ResizeObserver>"u")return;let o=a.offsetWidth,l=a.offsetHeight,c=null;const d=new ResizeObserver(()=>{const u=a.offsetWidth,m=a.offsetHeight;u===o&&m===l||(o=u,l=m,c&&clearTimeout(c),c=setTimeout(()=>{try{localStorage.setItem(s,JSON.stringify({width:u,height:m}))}catch{}},200))});return d.observe(a),()=>{d.disconnect(),c&&clearTimeout(c)}},[e,n,s])}function VE(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let gr=0,wo=null;function WE(){if(typeof window>"u")return;if(gr>0){gr+=1;return}const e=document.documentElement,n=document.body;wo={htmlOverflow:e.style.overflow,bodyPosition:n.style.position,bodyTop:n.style.top,bodyLeft:n.style.left,bodyRight:n.style.right,bodyWidth:n.style.width,bodyOverflow:n.style.overflow,scrollY:window.scrollY},e.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${wo.scrollY}px`,n.style.left="0",n.style.right="0",n.style.width="100%",n.style.overflow="hidden",gr=1}function KE(){if(typeof window>"u"||gr===0||(gr-=1,gr>0||!wo))return;const e=document.documentElement,n=document.body,{htmlOverflow:s,bodyPosition:a,bodyTop:r,bodyLeft:o,bodyRight:l,bodyWidth:c,bodyOverflow:d,scrollY:u}=wo;e.style.overflow=s,n.style.position=a,n.style.top=r,n.style.left=o,n.style.right=l,n.style.width=c,n.style.overflow=d,wo=null,window.scrollTo(0,0)}function Ni(e){i.useEffect(()=>{if(!(!e||!VE()))return WE(),()=>{KE()}},[e])}function Qi(e){const n=i.useRef(!1),s=i.useCallback(r=>{n.current=r.target===r.currentTarget},[]),a=i.useCallback(r=>{const o=n.current&&r.target===r.currentTarget;n.current=!1,o&&e()},[e]);return{onMouseDown:s,onMouseUp:a}}function GE(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const JE=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,YE=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,QE={};function qh(e,n){return(QE.jsx?YE:JE).test(e)}const XE=/[ \t\n\f\r]/g;function ZE(e){return typeof e=="object"?e.type==="text"?Vh(e.value):!1:Vh(e)}function Vh(e){return e.replace(XE,"")===""}class Ko{constructor(n,s,a){this.normal=s,this.property=n,a&&(this.space=a)}}Ko.prototype.normal={};Ko.prototype.property={};Ko.prototype.space=void 0;function Kb(e,n){const s={},a={};for(const r of e)Object.assign(s,r.property),Object.assign(a,r.normal);return new Ko(s,a,n)}function du(e){return e.toLowerCase()}class Xs{constructor(n,s){this.attribute=s,this.property=n}}Xs.prototype.attribute="";Xs.prototype.booleanish=!1;Xs.prototype.boolean=!1;Xs.prototype.commaOrSpaceSeparated=!1;Xs.prototype.commaSeparated=!1;Xs.prototype.defined=!1;Xs.prototype.mustUseProperty=!1;Xs.prototype.number=!1;Xs.prototype.overloadedBoolean=!1;Xs.prototype.property="";Xs.prototype.spaceSeparated=!1;Xs.prototype.space=void 0;let e2=0;const hn=qa(),ks=qa(),uu=qa(),Mt=qa(),Wn=qa(),br=qa(),ni=qa();function qa(){return 2**++e2}const mu=Object.freeze(Object.defineProperty({__proto__:null,boolean:hn,booleanish:ks,commaOrSpaceSeparated:ni,commaSeparated:br,number:Mt,overloadedBoolean:uu,spaceSeparated:Wn},Symbol.toStringTag,{value:"Module"})),Qc=Object.keys(mu);class Yu extends Xs{constructor(n,s,a,r){let o=-1;if(super(n,s),Wh(this,"space",r),typeof a=="number")for(;++o<Qc.length;){const l=Qc[o];Wh(this,Qc[o],(a&mu[l])===mu[l])}}}Yu.prototype.defined=!0;function Wh(e,n,s){s&&(e[n]=s)}function Lr(e){const n={},s={};for(const[a,r]of Object.entries(e.properties)){const o=new Yu(a,e.transform(e.attributes||{},a),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(a)&&(o.mustUseProperty=!0),n[a]=o,s[du(a)]=a,s[du(o.attribute)]=a}return new Ko(n,s,e.space)}const Gb=Lr({properties:{ariaActiveDescendant:null,ariaAtomic:ks,ariaAutoComplete:null,ariaBusy:ks,ariaChecked:ks,ariaColCount:Mt,ariaColIndex:Mt,ariaColSpan:Mt,ariaControls:Wn,ariaCurrent:null,ariaDescribedBy:Wn,ariaDetails:null,ariaDisabled:ks,ariaDropEffect:Wn,ariaErrorMessage:null,ariaExpanded:ks,ariaFlowTo:Wn,ariaGrabbed:ks,ariaHasPopup:null,ariaHidden:ks,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Wn,ariaLevel:Mt,ariaLive:null,ariaModal:ks,ariaMultiLine:ks,ariaMultiSelectable:ks,ariaOrientation:null,ariaOwns:Wn,ariaPlaceholder:null,ariaPosInSet:Mt,ariaPressed:ks,ariaReadOnly:ks,ariaRelevant:null,ariaRequired:ks,ariaRoleDescription:Wn,ariaRowCount:Mt,ariaRowIndex:Mt,ariaRowSpan:Mt,ariaSelected:ks,ariaSetSize:Mt,ariaSort:null,ariaValueMax:Mt,ariaValueMin:Mt,ariaValueNow:Mt,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Jb(e,n){return n in e?e[n]:n}function Yb(e,n){return Jb(e,n.toLowerCase())}const t2=Lr({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:br,acceptCharset:Wn,accessKey:Wn,action:null,allow:null,allowFullScreen:hn,allowPaymentRequest:hn,allowUserMedia:hn,alt:null,as:null,async:hn,autoCapitalize:null,autoComplete:Wn,autoFocus:hn,autoPlay:hn,blocking:Wn,capture:null,charSet:null,checked:hn,cite:null,className:Wn,cols:Mt,colSpan:null,content:null,contentEditable:ks,controls:hn,controlsList:Wn,coords:Mt|br,crossOrigin:null,data:null,dateTime:null,decoding:null,default:hn,defer:hn,dir:null,dirName:null,disabled:hn,download:uu,draggable:ks,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:hn,formTarget:null,headers:Wn,height:Mt,hidden:uu,high:Mt,href:null,hrefLang:null,htmlFor:Wn,httpEquiv:Wn,id:null,imageSizes:null,imageSrcSet:null,inert:hn,inputMode:null,integrity:null,is:null,isMap:hn,itemId:null,itemProp:Wn,itemRef:Wn,itemScope:hn,itemType:Wn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:hn,low:Mt,manifest:null,max:null,maxLength:Mt,media:null,method:null,min:null,minLength:Mt,multiple:hn,muted:hn,name:null,nonce:null,noModule:hn,noValidate:hn,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:hn,optimum:Mt,pattern:null,ping:Wn,placeholder:null,playsInline:hn,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:hn,referrerPolicy:null,rel:Wn,required:hn,reversed:hn,rows:Mt,rowSpan:Mt,sandbox:Wn,scope:null,scoped:hn,seamless:hn,selected:hn,shadowRootClonable:hn,shadowRootDelegatesFocus:hn,shadowRootMode:null,shape:null,size:Mt,sizes:null,slot:null,span:Mt,spellCheck:ks,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Mt,step:null,style:null,tabIndex:Mt,target:null,title:null,translate:null,type:null,typeMustMatch:hn,useMap:null,value:ks,width:Mt,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Wn,axis:null,background:null,bgColor:null,border:Mt,borderColor:null,bottomMargin:Mt,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:hn,declare:hn,event:null,face:null,frame:null,frameBorder:null,hSpace:Mt,leftMargin:Mt,link:null,longDesc:null,lowSrc:null,marginHeight:Mt,marginWidth:Mt,noResize:hn,noHref:hn,noShade:hn,noWrap:hn,object:null,profile:null,prompt:null,rev:null,rightMargin:Mt,rules:null,scheme:null,scrolling:ks,standby:null,summary:null,text:null,topMargin:Mt,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Mt,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:hn,disableRemotePlayback:hn,prefix:null,property:null,results:Mt,security:null,unselectable:null},space:"html",transform:Yb}),n2=Lr({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:ni,accentHeight:Mt,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Mt,amplitude:Mt,arabicForm:null,ascent:Mt,attributeName:null,attributeType:null,azimuth:Mt,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Mt,by:null,calcMode:null,capHeight:Mt,className:Wn,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:Mt,diffuseConstant:Mt,direction:null,display:null,dur:null,divisor:Mt,dominantBaseline:null,download:hn,dx:null,dy:null,edgeMode:null,editable:null,elevation:Mt,enableBackground:null,end:null,event:null,exponent:Mt,externalResourcesRequired:null,fill:null,fillOpacity:Mt,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:br,g2:br,glyphName:br,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Mt,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Mt,horizOriginX:Mt,horizOriginY:Mt,id:null,ideographic:Mt,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Mt,k:Mt,k1:Mt,k2:Mt,k3:Mt,k4:Mt,kernelMatrix:ni,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Mt,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:Mt,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:Mt,overlineThickness:Mt,paintOrder:null,panose1:null,path:null,pathLength:Mt,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Wn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Mt,pointsAtY:Mt,pointsAtZ:Mt,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:ni,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:ni,rev:ni,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:ni,requiredFeatures:ni,requiredFonts:ni,requiredFormats:ni,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:Mt,specularExponent:Mt,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Mt,strikethroughThickness:Mt,string:null,stroke:null,strokeDashArray:ni,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Mt,strokeOpacity:Mt,strokeWidth:null,style:null,surfaceScale:Mt,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:ni,tabIndex:Mt,tableValues:null,target:null,targetX:Mt,targetY:Mt,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:ni,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Mt,underlineThickness:Mt,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Mt,values:null,vAlphabetic:Mt,vMathematical:Mt,vectorEffect:null,vHanging:Mt,vIdeographic:Mt,version:null,vertAdvY:Mt,vertOriginX:Mt,vertOriginY:Mt,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Mt,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Jb}),Qb=Lr({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,n){return"xlink:"+n.slice(5).toLowerCase()}}),Xb=Lr({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Yb}),Zb=Lr({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),s2={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},i2=/[A-Z]/g,Kh=/-[a-z]/g,a2=/^data[-\w.:]+$/i;function r2(e,n){const s=du(n);let a=n,r=Xs;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&a2.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(Kh,l2);a="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!Kh.test(o)){let l=o.replace(i2,o2);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=Yu}return new r(a,n)}function o2(e){return"-"+e.toLowerCase()}function l2(e){return e.charAt(1).toUpperCase()}const c2=Kb([Gb,t2,Qb,Xb,Zb],"html"),Qu=Kb([Gb,n2,Qb,Xb,Zb],"svg");function d2(e){return e.join(" ").trim()}var ir={},Xc,Gh;function u2(){if(Gh)return Xc;Gh=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,l=/^[;\s]*/,c=/^\s+|\s+$/g,d=`
652
+ `,u="/",m="*",h="",f="comment",p="declaration";function g(w,b){if(typeof w!="string")throw new TypeError("First argument must be a string");if(!w)return[];b=b||{};var y=1,S=1;function j(R){var D=R.match(n);D&&(y+=D.length);var K=R.lastIndexOf(d);S=~K?R.length-K:S+R.length}function C(){var R={line:y,column:S};return function(D){return D.position=new v(R),F(),D}}function v(R){this.start=R,this.end={line:y,column:S},this.source=b.source}v.prototype.content=w;function N(R){var D=new Error(b.source+":"+y+":"+S+": "+R);if(D.reason=R,D.filename=b.source,D.line=y,D.column=S,D.source=w,!b.silent)throw D}function I(R){var D=R.exec(w);if(D){var K=D[0];return j(K),w=w.slice(K.length),D}}function F(){I(s)}function _(R){var D;for(R=R||[];D=M();)D!==!1&&R.push(D);return R}function M(){var R=C();if(!(u!=w.charAt(0)||m!=w.charAt(1))){for(var D=2;h!=w.charAt(D)&&(m!=w.charAt(D)||u!=w.charAt(D+1));)++D;if(D+=2,h===w.charAt(D-1))return N("End of comment missing");var K=w.slice(2,D-2);return S+=2,j(K),w=w.slice(D),S+=2,R({type:f,comment:K})}}function z(){var R=C(),D=I(a);if(D){if(M(),!I(r))return N("property missing ':'");var K=I(o),Z=R({type:p,property:x(D[0].replace(e,h)),value:K?x(K[0].replace(e,h)):h});return I(l),Z}}function U(){var R=[];_(R);for(var D;D=z();)D!==!1&&(R.push(D),_(R));return R}return F(),U()}function x(w){return w?w.replace(c,h):h}return Xc=g,Xc}var Jh;function m2(){if(Jh)return ir;Jh=1;var e=ir&&ir.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(ir,"__esModule",{value:!0}),ir.default=s;const n=e(u2());function s(a,r){let o=null;if(!a||typeof a!="string")return o;const l=(0,n.default)(a),c=typeof r=="function";return l.forEach(d=>{if(d.type!=="declaration")return;const{property:u,value:m}=d;c?r(u,m,d):m&&(o=o||{},o[u]=m)}),o}return ir}var Jr={},Yh;function h2(){if(Yh)return Jr;Yh=1,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,s=/^[^-]+$/,a=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(u){return!u||s.test(u)||e.test(u)},l=function(u,m){return m.toUpperCase()},c=function(u,m){return"".concat(m,"-")},d=function(u,m){return m===void 0&&(m={}),o(u)?u:(u=u.toLowerCase(),m.reactCompat?u=u.replace(r,c):u=u.replace(a,c),u.replace(n,l))};return Jr.camelCase=d,Jr}var Yr,Qh;function p2(){if(Qh)return Yr;Qh=1;var e=Yr&&Yr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(m2()),s=h2();function a(r,o){var l={};return!r||typeof r!="string"||(0,n.default)(r,function(c,d){c&&d&&(l[(0,s.camelCase)(c,o)]=d)}),l}return a.default=a,Yr=a,Yr}var f2=p2();const g2=Bg(f2),ex=tx("end"),Xu=tx("start");function tx(e){return n;function n(s){const a=s&&s.position&&s.position[e]||{};if(typeof a.line=="number"&&a.line>0&&typeof a.column=="number"&&a.column>0)return{line:a.line,column:a.column,offset:typeof a.offset=="number"&&a.offset>-1?a.offset:void 0}}}function b2(e){const n=Xu(e),s=ex(e);if(n&&s)return{start:n,end:s}}function ko(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Xh(e.position):"start"in e||"end"in e?Xh(e):"line"in e||"column"in e?hu(e):""}function hu(e){return Zh(e&&e.line)+":"+Zh(e&&e.column)}function Xh(e){return hu(e&&e.start)+"-"+hu(e&&e.end)}function Zh(e){return e&&typeof e=="number"?e:1}class Bs extends Error{constructor(n,s,a){super(),typeof s=="string"&&(a=s,s=void 0);let r="",o={},l=!1;if(s&&("line"in s&&"column"in s?o={place:s}:"start"in s&&"end"in s?o={place:s}:"type"in s?o={ancestors:[s],place:s.position}:o={...s}),typeof n=="string"?r=n:!o.cause&&n&&(l=!0,r=n.message,o.cause=n),!o.ruleId&&!o.source&&typeof a=="string"){const d=a.indexOf(":");d===-1?o.ruleId=a:(o.source=a.slice(0,d),o.ruleId=a.slice(d+1))}if(!o.place&&o.ancestors&&o.ancestors){const d=o.ancestors[o.ancestors.length-1];d&&(o.place=d.position)}const c=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=c?c.line:void 0,this.name=ko(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=l&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Bs.prototype.file="";Bs.prototype.name="";Bs.prototype.reason="";Bs.prototype.message="";Bs.prototype.stack="";Bs.prototype.column=void 0;Bs.prototype.line=void 0;Bs.prototype.ancestors=void 0;Bs.prototype.cause=void 0;Bs.prototype.fatal=void 0;Bs.prototype.place=void 0;Bs.prototype.ruleId=void 0;Bs.prototype.source=void 0;const Zu={}.hasOwnProperty,x2=new Map,v2=/[A-Z]/g,y2=new Set(["table","tbody","thead","tfoot","tr"]),w2=new Set(["td","th"]),nx="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function k2(e,n){if(!n||n.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const s=n.filePath||void 0;let a;if(n.development){if(typeof n.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");a=A2(s,n.jsxDEV)}else{if(typeof n.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof n.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");a=M2(s,n.jsx,n.jsxs)}const r={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:a,elementAttributeNameCase:n.elementAttributeNameCase||"react",evaluater:n.createEvaluater?n.createEvaluater():void 0,filePath:s,ignoreInvalidStyle:n.ignoreInvalidStyle||!1,passKeys:n.passKeys!==!1,passNode:n.passNode||!1,schema:n.space==="svg"?Qu:c2,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=sx(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function sx(e,n,s){if(n.type==="element")return j2(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return N2(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return C2(e,n,s);if(n.type==="mdxjsEsm")return S2(e,n);if(n.type==="root")return E2(e,n,s);if(n.type==="text")return _2(e,n)}function j2(e,n,s){const a=e.schema;let r=a;n.tagName.toLowerCase()==="svg"&&a.space==="html"&&(r=Qu,e.schema=r),e.ancestors.push(n);const o=ax(e,n.tagName,!1),l=R2(e,n);let c=tm(e,n);return y2.has(n.tagName)&&(c=c.filter(function(d){return typeof d=="string"?!ZE(d):!0})),ix(e,l,o,n),em(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function N2(e,n){if(n.data&&n.data.estree&&e.evaluater){const a=n.data.estree.body[0];return a.type,e.evaluater.evaluateExpression(a.expression)}Ao(e,n.position)}function S2(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);Ao(e,n.position)}function C2(e,n,s){const a=e.schema;let r=a;n.name==="svg"&&a.space==="html"&&(r=Qu,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:ax(e,n.name,!0),l=I2(e,n),c=tm(e,n);return ix(e,l,o,n),em(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function E2(e,n,s){const a={};return em(a,tm(e,n)),e.create(n,e.Fragment,a,s)}function _2(e,n){return n.value}function ix(e,n,s,a){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=a)}function em(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function M2(e,n,s){return a;function a(r,o,l,c){const u=Array.isArray(l.children)?s:n;return c?u(o,l,c):u(o,l)}}function A2(e,n){return s;function s(a,r,o,l){const c=Array.isArray(o.children),d=Xu(a);return n(r,o,l,c,{columnNumber:d?d.column-1:void 0,fileName:e,lineNumber:d?d.line:void 0},void 0)}}function R2(e,n){const s={};let a,r;for(r in n.properties)if(r!=="children"&&Zu.call(n.properties,r)){const o=T2(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&w2.has(n.tagName)?a=c:s[l]=c}}if(a){const o=s.style||(s.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=a}return s}function I2(e,n){const s={};for(const a of n.attributes)if(a.type==="mdxJsxExpressionAttribute")if(a.data&&a.data.estree&&e.evaluater){const o=a.data.estree.body[0];o.type;const l=o.expression;l.type;const c=l.properties[0];c.type,Object.assign(s,e.evaluater.evaluateExpression(c.argument))}else Ao(e,n.position);else{const r=a.name;let o;if(a.value&&typeof a.value=="object")if(a.value.data&&a.value.data.estree&&e.evaluater){const c=a.value.data.estree.body[0];c.type,o=e.evaluater.evaluateExpression(c.expression)}else Ao(e,n.position);else o=a.value===null?!0:a.value;s[r]=o}return s}function tm(e,n){const s=[];let a=-1;const r=e.passKeys?new Map:x2;for(;++a<n.children.length;){const o=n.children[a];let l;if(e.passKeys){const d=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(d){const u=r.get(d)||0;l=d+"-"+u,r.set(d,u+1)}}const c=sx(e,o,l);c!==void 0&&s.push(c)}return s}function T2(e,n,s){const a=r2(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=a.commaSeparated?GE(s):d2(s)),a.property==="style"){let r=typeof s=="object"?s:P2(e,String(s));return e.stylePropertyNameCase==="css"&&(r=$2(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&a.space?s2[a.property]||a.property:a.attribute,s]}}function P2(e,n){try{return g2(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const a=s,r=new Bs("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:a,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=nx+"#cannot-parse-style-attribute",r}}function ax(e,n,s){let a;if(!s)a={type:"Literal",value:n};else if(n.includes(".")){const r=n.split(".");let o=-1,l;for(;++o<r.length;){const c=qh(r[o])?{type:"Identifier",name:r[o]}:{type:"Literal",value:r[o]};l=l?{type:"MemberExpression",object:l,property:c,computed:!!(o&&c.type==="Literal"),optional:!1}:c}a=l}else a=qh(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(a.type==="Literal"){const r=a.value;return Zu.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(a);Ao(e)}function Ao(e,n){const s=new Bs("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:n,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw s.file=e.filePath||void 0,s.url=nx+"#cannot-handle-mdx-estrees-without-createevaluater",s}function $2(e){const n={};let s;for(s in e)Zu.call(e,s)&&(n[D2(s)]=e[s]);return n}function D2(e){let n=e.replace(v2,L2);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function L2(e){return"-"+e.toLowerCase()}const Zc={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},O2={};function nm(e,n){const s=O2,a=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return rx(e,a,r)}function rx(e,n,s){if(F2(e)){if("value"in e)return e.type==="html"&&!s?"":e.value;if(n&&"alt"in e&&e.alt)return e.alt;if("children"in e)return ep(e.children,n,s)}return Array.isArray(e)?ep(e,n,s):""}function ep(e,n,s){const a=[];let r=-1;for(;++r<e.length;)a[r]=rx(e[r],n,s);return a.join("")}function F2(e){return!!(e&&typeof e=="object")}const tp=document.createElement("i");function sm(e){const n="&"+e+";";tp.innerHTML=n;const s=tp.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function ii(e,n,s,a){const r=e.length;let o=0,l;if(n<0?n=-n>r?0:r+n:n=n>r?r:n,s=s>0?s:0,a.length<1e4)l=Array.from(a),l.unshift(n,s),e.splice(...l);else for(s&&e.splice(n,s);o<a.length;)l=a.slice(o,o+1e4),l.unshift(n,0),e.splice(...l),o+=1e4,n+=1e4}function ui(e,n){return e.length>0?(ii(e,e.length,0,n),e):n}const np={}.hasOwnProperty;function ox(e){const n={};let s=-1;for(;++s<e.length;)z2(n,e[s]);return n}function z2(e,n){let s;for(s in n){const r=(np.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){np.call(r,l)||(r[l]=[]);const c=o[l];B2(r[l],Array.isArray(c)?c:c?[c]:[])}}}function B2(e,n){let s=-1;const a=[];for(;++s<n.length;)(n[s].add==="after"?e:a).push(n[s]);ii(e,0,0,a)}function lx(e,n){const s=Number.parseInt(e,n);return s<9||s===11||s>13&&s<32||s>126&&s<160||s>55295&&s<57344||s>64975&&s<65008||(s&65535)===65535||(s&65535)===65534||s>1114111?"�":String.fromCodePoint(s)}function yi(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Vs=fa(/[A-Za-z]/),zs=fa(/[\dA-Za-z]/),U2=fa(/[#-'*+\--9=?A-Z^-~]/);function Jl(e){return e!==null&&(e<32||e===127)}const pu=fa(/\d/),H2=fa(/[\dA-Fa-f]/),q2=fa(/[!-/:-@[-`{-~]/);function en(e){return e!==null&&e<-2}function Bn(e){return e!==null&&(e<0||e===32)}function vn(e){return e===-2||e===-1||e===32}const wc=fa(/\p{P}|\p{S}/u),za=fa(/\s/);function fa(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Or(e){const n=[];let s=-1,a=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&zs(e.charCodeAt(s+1))&&zs(e.charCodeAt(s+2)))r=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(l=String.fromCharCode(o));else if(o>55295&&o<57344){const c=e.charCodeAt(s+1);o<56320&&c>56319&&c<57344?(l=String.fromCharCode(o,c),r=1):l="�"}else l=String.fromCharCode(o);l&&(n.push(e.slice(a,s),encodeURIComponent(l)),a=s+r+1,l=""),r&&(s+=r,r=0)}return n.join("")+e.slice(a)}function Cn(e,n,s,a){const r=a?a-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(d){return vn(d)?(e.enter(s),c(d)):n(d)}function c(d){return vn(d)&&o++<r?(e.consume(d),c):(e.exit(s),n(d))}}const V2={tokenize:W2};function W2(e){const n=e.attempt(this.parser.constructs.contentInitial,a,r);let s;return n;function a(c){if(c===null){e.consume(c);return}return e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),Cn(e,n,"linePrefix")}function r(c){return e.enter("paragraph"),o(c)}function o(c){const d=e.enter("chunkText",{contentType:"text",previous:s});return s&&(s.next=d),s=d,l(c)}function l(c){if(c===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(c);return}return en(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const K2={tokenize:G2},sp={tokenize:J2};function G2(e){const n=this,s=[];let a=0,r,o,l;return c;function c(S){if(a<s.length){const j=s[a];return n.containerState=j[1],e.attempt(j[0].continuation,d,u)(S)}return u(S)}function d(S){if(a++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const j=n.events.length;let C=j,v;for(;C--;)if(n.events[C][0]==="exit"&&n.events[C][1].type==="chunkFlow"){v=n.events[C][1].end;break}b(a);let N=j;for(;N<n.events.length;)n.events[N][1].end={...v},N++;return ii(n.events,C+1,0,n.events.slice(j)),n.events.length=N,u(S)}return c(S)}function u(S){if(a===s.length){if(!r)return f(S);if(r.currentConstruct&&r.currentConstruct.concrete)return g(S);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(sp,m,h)(S)}function m(S){return r&&y(),b(a),f(S)}function h(S){return n.parser.lazy[n.now().line]=a!==s.length,l=n.now().offset,g(S)}function f(S){return n.containerState={},e.attempt(sp,p,g)(S)}function p(S){return a++,s.push([n.currentConstruct,n.containerState]),f(S)}function g(S){if(S===null){r&&y(),b(0),e.consume(S);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),x(S)}function x(S){if(S===null){w(e.exit("chunkFlow"),!0),b(0),e.consume(S);return}return en(S)?(e.consume(S),w(e.exit("chunkFlow")),a=0,n.interrupt=void 0,c):(e.consume(S),x)}function w(S,j){const C=n.sliceStream(S);if(j&&C.push(null),S.previous=o,o&&(o.next=S),o=S,r.defineSkip(S.start),r.write(C),n.parser.lazy[S.start.line]){let v=r.events.length;for(;v--;)if(r.events[v][1].start.offset<l&&(!r.events[v][1].end||r.events[v][1].end.offset>l))return;const N=n.events.length;let I=N,F,_;for(;I--;)if(n.events[I][0]==="exit"&&n.events[I][1].type==="chunkFlow"){if(F){_=n.events[I][1].end;break}F=!0}for(b(a),v=N;v<n.events.length;)n.events[v][1].end={..._},v++;ii(n.events,I+1,0,n.events.slice(N)),n.events.length=v}}function b(S){let j=s.length;for(;j-- >S;){const C=s[j];n.containerState=C[1],C[0].exit.call(n,e)}s.length=S}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function J2(e,n,s){return Cn(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Sr(e){if(e===null||Bn(e)||za(e))return 1;if(wc(e))return 2}function kc(e,n,s){const a=[];let r=-1;for(;++r<e.length;){const o=e[r].resolveAll;o&&!a.includes(o)&&(n=o(n,s),a.push(o))}return n}const fu={name:"attention",resolveAll:Y2,tokenize:Q2};function Y2(e,n){let s=-1,a,r,o,l,c,d,u,m;for(;++s<e.length;)if(e[s][0]==="enter"&&e[s][1].type==="attentionSequence"&&e[s][1]._close){for(a=s;a--;)if(e[a][0]==="exit"&&e[a][1].type==="attentionSequence"&&e[a][1]._open&&n.sliceSerialize(e[a][1]).charCodeAt(0)===n.sliceSerialize(e[s][1]).charCodeAt(0)){if((e[a][1]._close||e[s][1]._open)&&(e[s][1].end.offset-e[s][1].start.offset)%3&&!((e[a][1].end.offset-e[a][1].start.offset+e[s][1].end.offset-e[s][1].start.offset)%3))continue;d=e[a][1].end.offset-e[a][1].start.offset>1&&e[s][1].end.offset-e[s][1].start.offset>1?2:1;const h={...e[a][1].end},f={...e[s][1].start};ip(h,-d),ip(f,d),l={type:d>1?"strongSequence":"emphasisSequence",start:h,end:{...e[a][1].end}},c={type:d>1?"strongSequence":"emphasisSequence",start:{...e[s][1].start},end:f},o={type:d>1?"strongText":"emphasisText",start:{...e[a][1].end},end:{...e[s][1].start}},r={type:d>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[a][1].end={...l.start},e[s][1].start={...c.end},u=[],e[a][1].end.offset-e[a][1].start.offset&&(u=ui(u,[["enter",e[a][1],n],["exit",e[a][1],n]])),u=ui(u,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),u=ui(u,kc(n.parser.constructs.insideSpan.null,e.slice(a+1,s),n)),u=ui(u,[["exit",o,n],["enter",c,n],["exit",c,n],["exit",r,n]]),e[s][1].end.offset-e[s][1].start.offset?(m=2,u=ui(u,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,ii(e,a-1,s-a+3,u),s=a+u.length-m-2;break}}for(s=-1;++s<e.length;)e[s][1].type==="attentionSequence"&&(e[s][1].type="data");return e}function Q2(e,n){const s=this.parser.constructs.attentionMarkers.null,a=this.previous,r=Sr(a);let o;return l;function l(d){return o=d,e.enter("attentionSequence"),c(d)}function c(d){if(d===o)return e.consume(d),c;const u=e.exit("attentionSequence"),m=Sr(d),h=!m||m===2&&r||s.includes(d),f=!r||r===2&&m||s.includes(a);return u._open=!!(o===42?h:h&&(r||!f)),u._close=!!(o===42?f:f&&(m||!h)),n(d)}}function ip(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const X2={name:"autolink",tokenize:Z2};function Z2(e,n,s){let a=0;return r;function r(p){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o}function o(p){return Vs(p)?(e.consume(p),l):p===64?s(p):u(p)}function l(p){return p===43||p===45||p===46||zs(p)?(a=1,c(p)):u(p)}function c(p){return p===58?(e.consume(p),a=0,d):(p===43||p===45||p===46||zs(p))&&a++<32?(e.consume(p),c):(a=0,u(p))}function d(p){return p===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):p===null||p===32||p===60||Jl(p)?s(p):(e.consume(p),d)}function u(p){return p===64?(e.consume(p),m):U2(p)?(e.consume(p),u):s(p)}function m(p){return zs(p)?h(p):s(p)}function h(p){return p===46?(e.consume(p),a=0,m):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):f(p)}function f(p){if((p===45||zs(p))&&a++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const Go={partial:!0,tokenize:e_};function e_(e,n,s){return a;function a(o){return vn(o)?Cn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||en(o)?n(o):s(o)}}const cx={continuation:{tokenize:n_},exit:s_,name:"blockQuote",tokenize:t_};function t_(e,n,s){const a=this;return r;function r(l){if(l===62){const c=a.containerState;return c.open||(e.enter("blockQuote",{_container:!0}),c.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(l),e.exit("blockQuoteMarker"),o}return s(l)}function o(l){return vn(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function n_(e,n,s){const a=this;return r;function r(l){return vn(l)?Cn(e,o,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(cx,n,s)(l)}}function s_(e){e.exit("blockQuote")}const dx={name:"characterEscape",tokenize:i_};function i_(e,n,s){return a;function a(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),r}function r(o){return q2(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const ux={name:"characterReference",tokenize:a_};function a_(e,n,s){const a=this;let r=0,o,l;return c;function c(h){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),d}function d(h){return h===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(h),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),o=31,l=zs,m(h))}function u(h){return h===88||h===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(h),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,l=H2,m):(e.enter("characterReferenceValue"),o=7,l=pu,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===zs&&!sm(a.sliceSerialize(f))?s(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return l(h)&&r++<o?(e.consume(h),m):s(h)}}const ap={partial:!0,tokenize:o_},rp={concrete:!0,name:"codeFenced",tokenize:r_};function r_(e,n,s){const a=this,r={partial:!0,tokenize:C};let o=0,l=0,c;return d;function d(v){return u(v)}function u(v){const N=a.events[a.events.length-1];return o=N&&N[1].type==="linePrefix"?N[2].sliceSerialize(N[1],!0).length:0,c=v,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(v)}function m(v){return v===c?(l++,e.consume(v),m):l<3?s(v):(e.exit("codeFencedFenceSequence"),vn(v)?Cn(e,h,"whitespace")(v):h(v))}function h(v){return v===null||en(v)?(e.exit("codeFencedFence"),a.interrupt?n(v):e.check(ap,x,j)(v)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(v))}function f(v){return v===null||en(v)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(v)):vn(v)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Cn(e,p,"whitespace")(v)):v===96&&v===c?s(v):(e.consume(v),f)}function p(v){return v===null||en(v)?h(v):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(v))}function g(v){return v===null||en(v)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(v)):v===96&&v===c?s(v):(e.consume(v),g)}function x(v){return e.attempt(r,j,w)(v)}function w(v){return e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),b}function b(v){return o>0&&vn(v)?Cn(e,y,"linePrefix",o+1)(v):y(v)}function y(v){return v===null||en(v)?e.check(ap,x,j)(v):(e.enter("codeFlowValue"),S(v))}function S(v){return v===null||en(v)?(e.exit("codeFlowValue"),y(v)):(e.consume(v),S)}function j(v){return e.exit("codeFenced"),n(v)}function C(v,N,I){let F=0;return _;function _(D){return v.enter("lineEnding"),v.consume(D),v.exit("lineEnding"),M}function M(D){return v.enter("codeFencedFence"),vn(D)?Cn(v,z,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(D):z(D)}function z(D){return D===c?(v.enter("codeFencedFenceSequence"),U(D)):I(D)}function U(D){return D===c?(F++,v.consume(D),U):F>=l?(v.exit("codeFencedFenceSequence"),vn(D)?Cn(v,R,"whitespace")(D):R(D)):I(D)}function R(D){return D===null||en(D)?(v.exit("codeFencedFence"),N(D)):I(D)}}}function o_(e,n,s){const a=this;return r;function r(l){return l===null?s(l):(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o)}function o(l){return a.parser.lazy[a.now().line]?s(l):n(l)}}const ed={name:"codeIndented",tokenize:c_},l_={partial:!0,tokenize:d_};function c_(e,n,s){const a=this;return r;function r(u){return e.enter("codeIndented"),Cn(e,o,"linePrefix",5)(u)}function o(u){const m=a.events[a.events.length-1];return m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?l(u):s(u)}function l(u){return u===null?d(u):en(u)?e.attempt(l_,l,d)(u):(e.enter("codeFlowValue"),c(u))}function c(u){return u===null||en(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),c)}function d(u){return e.exit("codeIndented"),n(u)}}function d_(e,n,s){const a=this;return r;function r(l){return a.parser.lazy[a.now().line]?s(l):en(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):Cn(e,o,"linePrefix",5)(l)}function o(l){const c=a.events[a.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):en(l)?r(l):s(l)}}const u_={name:"codeText",previous:h_,resolve:m_,tokenize:p_};function m_(e){let n=e.length-4,s=3,a,r;if((e[s][1].type==="lineEnding"||e[s][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(a=s;++a<n;)if(e[a][1].type==="codeTextData"){e[s][1].type="codeTextPadding",e[n][1].type="codeTextPadding",s+=2,n-=2;break}}for(a=s-1,n++;++a<=n;)r===void 0?a!==n&&e[a][1].type!=="lineEnding"&&(r=a):(a===n||e[a][1].type==="lineEnding")&&(e[r][1].type="codeTextData",a!==r+2&&(e[r][1].end=e[a-1][1].end,e.splice(r+2,a-r-2),n-=a-r-2,a=r+2),r=void 0);return e}function h_(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function p_(e,n,s){let a=0,r,o;return l;function l(h){return e.enter("codeText"),e.enter("codeTextSequence"),c(h)}function c(h){return h===96?(e.consume(h),a++,c):(e.exit("codeTextSequence"),d(h))}function d(h){return h===null?s(h):h===32?(e.enter("space"),e.consume(h),e.exit("space"),d):h===96?(o=e.enter("codeTextSequence"),r=0,m(h)):en(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),d):(e.enter("codeTextData"),u(h))}function u(h){return h===null||h===32||h===96||en(h)?(e.exit("codeTextData"),d(h)):(e.consume(h),u)}function m(h){return h===96?(e.consume(h),r++,m):r===a?(e.exit("codeTextSequence"),e.exit("codeText"),n(h)):(o.type="codeTextData",u(h))}}class f_{constructor(n){this.left=n?[...n]:[],this.right=[]}get(n){if(n<0||n>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+n+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return n<this.left.length?this.left[n]:this.right[this.right.length-n+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(n,s){const a=s??Number.POSITIVE_INFINITY;return a<this.left.length?this.left.slice(n,a):n>this.left.length?this.right.slice(this.right.length-a+this.left.length,this.right.length-n+this.left.length).reverse():this.left.slice(n).concat(this.right.slice(this.right.length-a+this.left.length).reverse())}splice(n,s,a){const r=s||0;this.setCursor(Math.trunc(n));const o=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return a&&Qr(this.left,a),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(n){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(n)}pushMany(n){this.setCursor(Number.POSITIVE_INFINITY),Qr(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Qr(this.right,n.reverse())}setCursor(n){if(!(n===this.left.length||n>this.left.length&&this.right.length===0||n<0&&this.left.length===0))if(n<this.left.length){const s=this.left.splice(n,Number.POSITIVE_INFINITY);Qr(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Qr(this.left,s.reverse())}}}function Qr(e,n){let s=0;if(n.length<1e4)e.push(...n);else for(;s<n.length;)e.push(...n.slice(s,s+1e4)),s+=1e4}function mx(e){const n={};let s=-1,a,r,o,l,c,d,u;const m=new f_(e);for(;++s<m.length;){for(;s in n;)s=n[s];if(a=m.get(s),s&&a[1].type==="chunkFlow"&&m.get(s-1)[1].type==="listItemPrefix"&&(d=a[1]._tokenizer.events,o=0,o<d.length&&d[o][1].type==="lineEndingBlank"&&(o+=2),o<d.length&&d[o][1].type==="content"))for(;++o<d.length&&d[o][1].type!=="content";)d[o][1].type==="chunkText"&&(d[o][1]._isInFirstContentOfListItem=!0,o++);if(a[0]==="enter")a[1].contentType&&(Object.assign(n,g_(m,s)),s=n[s],u=!0);else if(a[1]._container){for(o=s,r=void 0;o--;)if(l=m.get(o),l[1].type==="lineEnding"||l[1].type==="lineEndingBlank")l[0]==="enter"&&(r&&(m.get(r)[1].type="lineEndingBlank"),l[1].type="lineEnding",r=o);else if(!(l[1].type==="linePrefix"||l[1].type==="listItemIndent"))break;r&&(a[1].end={...m.get(r)[1].start},c=m.slice(r,s),c.unshift(a),m.splice(r,s-r+1,c))}}return ii(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!u}function g_(e,n){const s=e.get(n)[1],a=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=a.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,d=[],u={};let m,h,f=-1,p=s,g=0,x=0;const w=[x];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=a.sliceStream(p),p.next||m.push(null),h&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(m),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),h=p,p=p.next}for(p=s;++f<c.length;)c[f][0]==="exit"&&c[f-1][0]==="enter"&&c[f][1].type===c[f-1][1].type&&c[f][1].start.line!==c[f][1].end.line&&(x=f+1,w.push(x),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):w.pop(),f=w.length;f--;){const b=c.slice(w[f],w[f+1]),y=o.pop();d.push([y,y+b.length-1]),e.splice(y,2,b)}for(d.reverse(),f=-1;++f<d.length;)u[g+d[f][0]]=g+d[f][1],g+=d[f][1]-d[f][0]-1;return u}const b_={resolve:v_,tokenize:y_},x_={partial:!0,tokenize:w_};function v_(e){return mx(e),e}function y_(e,n){let s;return a;function a(c){return e.enter("content"),s=e.enter("chunkContent",{contentType:"content"}),r(c)}function r(c){return c===null?o(c):en(c)?e.check(x_,l,o)(c):(e.consume(c),r)}function o(c){return e.exit("chunkContent"),e.exit("content"),n(c)}function l(c){return e.consume(c),e.exit("chunkContent"),s.next=e.enter("chunkContent",{contentType:"content",previous:s}),s=s.next,r}}function w_(e,n,s){const a=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Cn(e,o,"linePrefix")}function o(l){if(l===null||en(l))return s(l);const c=a.events[a.events.length-1];return!a.parser.constructs.disable.null.includes("codeIndented")&&c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):e.interrupt(a.parser.constructs.flow,s,n)(l)}}function hx(e,n,s,a,r,o,l,c,d){const u=d||Number.POSITIVE_INFINITY;let m=0;return h;function h(b){return b===60?(e.enter(a),e.enter(r),e.enter(o),e.consume(b),e.exit(o),f):b===null||b===32||b===41||Jl(b)?s(b):(e.enter(a),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),x(b))}function f(b){return b===62?(e.enter(o),e.consume(b),e.exit(o),e.exit(r),e.exit(a),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(b))}function p(b){return b===62?(e.exit("chunkString"),e.exit(c),f(b)):b===null||b===60||en(b)?s(b):(e.consume(b),b===92?g:p)}function g(b){return b===60||b===62||b===92?(e.consume(b),p):p(b)}function x(b){return!m&&(b===null||b===41||Bn(b))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(a),n(b)):m<u&&b===40?(e.consume(b),m++,x):b===41?(e.consume(b),m--,x):b===null||b===32||b===40||Jl(b)?s(b):(e.consume(b),b===92?w:x)}function w(b){return b===40||b===41||b===92?(e.consume(b),x):x(b)}}function px(e,n,s,a,r,o){const l=this;let c=0,d;return u;function u(p){return e.enter(a),e.enter(r),e.consume(p),e.exit(r),e.enter(o),m}function m(p){return c>999||p===null||p===91||p===93&&!d||p===94&&!c&&"_hiddenFootnoteSupport"in l.parser.constructs?s(p):p===93?(e.exit(o),e.enter(r),e.consume(p),e.exit(r),e.exit(a),n):en(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),m):(e.enter("chunkString",{contentType:"string"}),h(p))}function h(p){return p===null||p===91||p===93||en(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),d||(d=!vn(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function fx(e,n,s,a,r,o){let l;return c;function c(f){return f===34||f===39||f===40?(e.enter(a),e.enter(r),e.consume(f),e.exit(r),l=f===40?41:f,d):s(f)}function d(f){return f===l?(e.enter(r),e.consume(f),e.exit(r),e.exit(a),n):(e.enter(o),u(f))}function u(f){return f===l?(e.exit(o),d(l)):f===null?s(f):en(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),Cn(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(f))}function m(f){return f===l||f===null||en(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?h:m)}function h(f){return f===l||f===92?(e.consume(f),m):m(f)}}function jo(e,n){let s;return a;function a(r){return en(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,a):vn(r)?Cn(e,a,s?"linePrefix":"lineSuffix")(r):n(r)}}const k_={name:"definition",tokenize:N_},j_={partial:!0,tokenize:S_};function N_(e,n,s){const a=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return px.call(a,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=yi(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),d):s(p)}function d(p){return Bn(p)?jo(e,u)(p):u(p)}function u(p){return hx(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(j_,h,h)(p)}function h(p){return vn(p)?Cn(e,f,"whitespace")(p):f(p)}function f(p){return p===null||en(p)?(e.exit("definition"),a.parser.defined.push(r),n(p)):s(p)}}function S_(e,n,s){return a;function a(c){return Bn(c)?jo(e,r)(c):s(c)}function r(c){return fx(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return vn(c)?Cn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||en(c)?n(c):s(c)}}const C_={name:"hardBreakEscape",tokenize:E_};function E_(e,n,s){return a;function a(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return en(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const __={name:"headingAtx",resolve:M_,tokenize:A_};function M_(e,n){let s=e.length-2,a=3,r,o;return e[a][1].type==="whitespace"&&(a+=2),s-2>a&&e[s][1].type==="whitespace"&&(s-=2),e[s][1].type==="atxHeadingSequence"&&(a===s-1||s-4>a&&e[s-2][1].type==="whitespace")&&(s-=a+1===s?2:4),s>a&&(r={type:"atxHeadingText",start:e[a][1].start,end:e[s][1].end},o={type:"chunkText",start:e[a][1].start,end:e[s][1].end,contentType:"text"},ii(e,a,s-a+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function A_(e,n,s){let a=0;return r;function r(m){return e.enter("atxHeading"),o(m)}function o(m){return e.enter("atxHeadingSequence"),l(m)}function l(m){return m===35&&a++<6?(e.consume(m),l):m===null||Bn(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),d(m)):m===null||en(m)?(e.exit("atxHeading"),n(m)):vn(m)?Cn(e,c,"whitespace")(m):(e.enter("atxHeadingText"),u(m))}function d(m){return m===35?(e.consume(m),d):(e.exit("atxHeadingSequence"),c(m))}function u(m){return m===null||m===35||Bn(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),u)}}const R_=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],op=["pre","script","style","textarea"],I_={concrete:!0,name:"htmlFlow",resolveTo:$_,tokenize:D_},T_={partial:!0,tokenize:O_},P_={partial:!0,tokenize:L_};function $_(e){let n=e.length;for(;n--&&!(e[n][0]==="enter"&&e[n][1].type==="htmlFlow"););return n>1&&e[n-2][1].type==="linePrefix"&&(e[n][1].start=e[n-2][1].start,e[n+1][1].start=e[n-2][1].start,e.splice(n-2,2)),e}function D_(e,n,s){const a=this;let r,o,l,c,d;return u;function u(k){return m(k)}function m(k){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(k),h}function h(k){return k===33?(e.consume(k),f):k===47?(e.consume(k),o=!0,x):k===63?(e.consume(k),r=3,a.interrupt?n:A):Vs(k)?(e.consume(k),l=String.fromCharCode(k),w):s(k)}function f(k){return k===45?(e.consume(k),r=2,p):k===91?(e.consume(k),r=5,c=0,g):Vs(k)?(e.consume(k),r=4,a.interrupt?n:A):s(k)}function p(k){return k===45?(e.consume(k),a.interrupt?n:A):s(k)}function g(k){const J="CDATA[";return k===J.charCodeAt(c++)?(e.consume(k),c===J.length?a.interrupt?n:z:g):s(k)}function x(k){return Vs(k)?(e.consume(k),l=String.fromCharCode(k),w):s(k)}function w(k){if(k===null||k===47||k===62||Bn(k)){const J=k===47,ce=l.toLowerCase();return!J&&!o&&op.includes(ce)?(r=1,a.interrupt?n(k):z(k)):R_.includes(l.toLowerCase())?(r=6,J?(e.consume(k),b):a.interrupt?n(k):z(k)):(r=7,a.interrupt&&!a.parser.lazy[a.now().line]?s(k):o?y(k):S(k))}return k===45||zs(k)?(e.consume(k),l+=String.fromCharCode(k),w):s(k)}function b(k){return k===62?(e.consume(k),a.interrupt?n:z):s(k)}function y(k){return vn(k)?(e.consume(k),y):_(k)}function S(k){return k===47?(e.consume(k),_):k===58||k===95||Vs(k)?(e.consume(k),j):vn(k)?(e.consume(k),S):_(k)}function j(k){return k===45||k===46||k===58||k===95||zs(k)?(e.consume(k),j):C(k)}function C(k){return k===61?(e.consume(k),v):vn(k)?(e.consume(k),C):S(k)}function v(k){return k===null||k===60||k===61||k===62||k===96?s(k):k===34||k===39?(e.consume(k),d=k,N):vn(k)?(e.consume(k),v):I(k)}function N(k){return k===d?(e.consume(k),d=null,F):k===null||en(k)?s(k):(e.consume(k),N)}function I(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||Bn(k)?C(k):(e.consume(k),I)}function F(k){return k===47||k===62||vn(k)?S(k):s(k)}function _(k){return k===62?(e.consume(k),M):s(k)}function M(k){return k===null||en(k)?z(k):vn(k)?(e.consume(k),M):s(k)}function z(k){return k===45&&r===2?(e.consume(k),K):k===60&&r===1?(e.consume(k),Z):k===62&&r===4?(e.consume(k),P):k===63&&r===3?(e.consume(k),A):k===93&&r===5?(e.consume(k),O):en(k)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(T_,$,U)(k)):k===null||en(k)?(e.exit("htmlFlowData"),U(k)):(e.consume(k),z)}function U(k){return e.check(P_,R,$)(k)}function R(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),D}function D(k){return k===null||en(k)?U(k):(e.enter("htmlFlowData"),z(k))}function K(k){return k===45?(e.consume(k),A):z(k)}function Z(k){return k===47?(e.consume(k),l="",ne):z(k)}function ne(k){if(k===62){const J=l.toLowerCase();return op.includes(J)?(e.consume(k),P):z(k)}return Vs(k)&&l.length<8?(e.consume(k),l+=String.fromCharCode(k),ne):z(k)}function O(k){return k===93?(e.consume(k),A):z(k)}function A(k){return k===62?(e.consume(k),P):k===45&&r===2?(e.consume(k),A):z(k)}function P(k){return k===null||en(k)?(e.exit("htmlFlowData"),$(k)):(e.consume(k),P)}function $(k){return e.exit("htmlFlow"),n(k)}}function L_(e,n,s){const a=this;return r;function r(l){return en(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o):s(l)}function o(l){return a.parser.lazy[a.now().line]?s(l):n(l)}}function O_(e,n,s){return a;function a(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(Go,n,s)}}const F_={name:"htmlText",tokenize:z_};function z_(e,n,s){const a=this;let r,o,l;return c;function c(A){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(A),d}function d(A){return A===33?(e.consume(A),u):A===47?(e.consume(A),C):A===63?(e.consume(A),S):Vs(A)?(e.consume(A),I):s(A)}function u(A){return A===45?(e.consume(A),m):A===91?(e.consume(A),o=0,g):Vs(A)?(e.consume(A),y):s(A)}function m(A){return A===45?(e.consume(A),p):s(A)}function h(A){return A===null?s(A):A===45?(e.consume(A),f):en(A)?(l=h,Z(A)):(e.consume(A),h)}function f(A){return A===45?(e.consume(A),p):h(A)}function p(A){return A===62?K(A):A===45?f(A):h(A)}function g(A){const P="CDATA[";return A===P.charCodeAt(o++)?(e.consume(A),o===P.length?x:g):s(A)}function x(A){return A===null?s(A):A===93?(e.consume(A),w):en(A)?(l=x,Z(A)):(e.consume(A),x)}function w(A){return A===93?(e.consume(A),b):x(A)}function b(A){return A===62?K(A):A===93?(e.consume(A),b):x(A)}function y(A){return A===null||A===62?K(A):en(A)?(l=y,Z(A)):(e.consume(A),y)}function S(A){return A===null?s(A):A===63?(e.consume(A),j):en(A)?(l=S,Z(A)):(e.consume(A),S)}function j(A){return A===62?K(A):S(A)}function C(A){return Vs(A)?(e.consume(A),v):s(A)}function v(A){return A===45||zs(A)?(e.consume(A),v):N(A)}function N(A){return en(A)?(l=N,Z(A)):vn(A)?(e.consume(A),N):K(A)}function I(A){return A===45||zs(A)?(e.consume(A),I):A===47||A===62||Bn(A)?F(A):s(A)}function F(A){return A===47?(e.consume(A),K):A===58||A===95||Vs(A)?(e.consume(A),_):en(A)?(l=F,Z(A)):vn(A)?(e.consume(A),F):K(A)}function _(A){return A===45||A===46||A===58||A===95||zs(A)?(e.consume(A),_):M(A)}function M(A){return A===61?(e.consume(A),z):en(A)?(l=M,Z(A)):vn(A)?(e.consume(A),M):F(A)}function z(A){return A===null||A===60||A===61||A===62||A===96?s(A):A===34||A===39?(e.consume(A),r=A,U):en(A)?(l=z,Z(A)):vn(A)?(e.consume(A),z):(e.consume(A),R)}function U(A){return A===r?(e.consume(A),r=void 0,D):A===null?s(A):en(A)?(l=U,Z(A)):(e.consume(A),U)}function R(A){return A===null||A===34||A===39||A===60||A===61||A===96?s(A):A===47||A===62||Bn(A)?F(A):(e.consume(A),R)}function D(A){return A===47||A===62||Bn(A)?F(A):s(A)}function K(A){return A===62?(e.consume(A),e.exit("htmlTextData"),e.exit("htmlText"),n):s(A)}function Z(A){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),ne}function ne(A){return vn(A)?Cn(e,O,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):O(A)}function O(A){return e.enter("htmlTextData"),l(A)}}const im={name:"labelEnd",resolveAll:q_,resolveTo:V_,tokenize:W_},B_={tokenize:K_},U_={tokenize:G_},H_={tokenize:J_};function q_(e){let n=-1;const s=[];for(;++n<e.length;){const a=e[n][1];if(s.push(e[n]),a.type==="labelImage"||a.type==="labelLink"||a.type==="labelEnd"){const r=a.type==="labelImage"?4:2;a.type="data",n+=r}}return e.length!==s.length&&ii(e,0,e.length,s),e}function V_(e,n){let s=e.length,a=0,r,o,l,c;for(;s--;)if(r=e[s][1],o){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;e[s][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(l){if(e[s][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(o=s,r.type!=="labelLink")){a=2;break}}else r.type==="labelEnd"&&(l=s);const d={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[o][1].start},end:{...e[l][1].end}},m={type:"labelText",start:{...e[o+a+2][1].end},end:{...e[l-2][1].start}};return c=[["enter",d,n],["enter",u,n]],c=ui(c,e.slice(o+1,o+a+3)),c=ui(c,[["enter",m,n]]),c=ui(c,kc(n.parser.constructs.insideSpan.null,e.slice(o+a+4,l-3),n)),c=ui(c,[["exit",m,n],e[l-2],e[l-1],["exit",u,n]]),c=ui(c,e.slice(l+1)),c=ui(c,[["exit",d,n]]),ii(e,o,e.length,c),e}function W_(e,n,s){const a=this;let r=a.events.length,o,l;for(;r--;)if((a.events[r][1].type==="labelImage"||a.events[r][1].type==="labelLink")&&!a.events[r][1]._balanced){o=a.events[r][1];break}return c;function c(f){return o?o._inactive?h(f):(l=a.parser.defined.includes(yi(a.sliceSerialize({start:o.end,end:a.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),d):s(f)}function d(f){return f===40?e.attempt(B_,m,l?m:h)(f):f===91?e.attempt(U_,m,l?u:h)(f):l?m(f):h(f)}function u(f){return e.attempt(H_,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function K_(e,n,s){return a;function a(h){return e.enter("resource"),e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),r}function r(h){return Bn(h)?jo(e,o)(h):o(h)}function o(h){return h===41?m(h):hx(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return Bn(h)?jo(e,d)(h):m(h)}function c(h){return s(h)}function d(h){return h===34||h===39||h===40?fx(e,u,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function u(h){return Bn(h)?jo(e,m)(h):m(h)}function m(h){return h===41?(e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),e.exit("resource"),n):s(h)}}function G_(e,n,s){const a=this;return r;function r(c){return px.call(a,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return a.parser.defined.includes(yi(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function J_(e,n,s){return a;function a(o){return e.enter("reference"),e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),r}function r(o){return o===93?(e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),e.exit("reference"),n):s(o)}}const Y_={name:"labelStartImage",resolveAll:im.resolveAll,tokenize:Q_};function Q_(e,n,s){const a=this;return r;function r(c){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(c),e.exit("labelImageMarker"),o}function o(c){return c===91?(e.enter("labelMarker"),e.consume(c),e.exit("labelMarker"),e.exit("labelImage"),l):s(c)}function l(c){return c===94&&"_hiddenFootnoteSupport"in a.parser.constructs?s(c):n(c)}}const X_={name:"labelStartLink",resolveAll:im.resolveAll,tokenize:Z_};function Z_(e,n,s){const a=this;return r;function r(l){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(l),e.exit("labelMarker"),e.exit("labelLink"),o}function o(l){return l===94&&"_hiddenFootnoteSupport"in a.parser.constructs?s(l):n(l)}}const td={name:"lineEnding",tokenize:eM};function eM(e,n){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),Cn(e,n,"linePrefix")}}const $l={name:"thematicBreak",tokenize:tM};function tM(e,n,s){let a=0,r;return o;function o(u){return e.enter("thematicBreak"),l(u)}function l(u){return r=u,c(u)}function c(u){return u===r?(e.enter("thematicBreakSequence"),d(u)):a>=3&&(u===null||en(u))?(e.exit("thematicBreak"),n(u)):s(u)}function d(u){return u===r?(e.consume(u),a++,d):(e.exit("thematicBreakSequence"),vn(u)?Cn(e,c,"whitespace")(u):c(u))}}const Js={continuation:{tokenize:aM},exit:oM,name:"list",tokenize:iM},nM={partial:!0,tokenize:lM},sM={partial:!0,tokenize:rM};function iM(e,n,s){const a=this,r=a.events[a.events.length-1];let o=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,l=0;return c;function c(p){const g=a.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!a.containerState.marker||p===a.containerState.marker:pu(p)){if(a.containerState.type||(a.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check($l,s,u)(p):u(p);if(!a.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),d(p)}return s(p)}function d(p){return pu(p)&&++l<10?(e.consume(p),d):(!a.interrupt||l<2)&&(a.containerState.marker?p===a.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),u(p)):s(p)}function u(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),a.containerState.marker=a.containerState.marker||p,e.check(Go,a.interrupt?s:m,e.attempt(nM,f,h))}function m(p){return a.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return vn(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):s(p)}function f(p){return a.containerState.size=o+a.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function aM(e,n,s){const a=this;return a.containerState._closeFlow=void 0,e.check(Go,r,o);function r(c){return a.containerState.furtherBlankLines=a.containerState.furtherBlankLines||a.containerState.initialBlankLine,Cn(e,n,"listItemIndent",a.containerState.size+1)(c)}function o(c){return a.containerState.furtherBlankLines||!vn(c)?(a.containerState.furtherBlankLines=void 0,a.containerState.initialBlankLine=void 0,l(c)):(a.containerState.furtherBlankLines=void 0,a.containerState.initialBlankLine=void 0,e.attempt(sM,n,l)(c))}function l(c){return a.containerState._closeFlow=!0,a.interrupt=void 0,Cn(e,e.attempt(Js,n,s),"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function rM(e,n,s){const a=this;return Cn(e,r,"listItemIndent",a.containerState.size+1);function r(o){const l=a.events[a.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===a.containerState.size?n(o):s(o)}}function oM(e){e.exit(this.containerState.type)}function lM(e,n,s){const a=this;return Cn(e,r,"listItemPrefixWhitespace",a.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const l=a.events[a.events.length-1];return!vn(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const lp={name:"setextUnderline",resolveTo:cM,tokenize:dM};function cM(e,n){let s=e.length,a,r,o;for(;s--;)if(e[s][0]==="enter"){if(e[s][1].type==="content"){a=s;break}e[s][1].type==="paragraph"&&(r=s)}else e[s][1].type==="content"&&e.splice(s,1),!o&&e[s][1].type==="definition"&&(o=s);const l={type:"setextHeading",start:{...e[a][1].start},end:{...e[e.length-1][1].end}};return e[r][1].type="setextHeadingText",o?(e.splice(r,0,["enter",l,n]),e.splice(o+1,0,["exit",e[a][1],n]),e[a][1].end={...e[o][1].end}):e[a][1]=l,e.push(["exit",l,n]),e}function dM(e,n,s){const a=this;let r;return o;function o(u){let m=a.events.length,h;for(;m--;)if(a.events[m][1].type!=="lineEnding"&&a.events[m][1].type!=="linePrefix"&&a.events[m][1].type!=="content"){h=a.events[m][1].type==="paragraph";break}return!a.parser.lazy[a.now().line]&&(a.interrupt||h)?(e.enter("setextHeadingLine"),r=u,l(u)):s(u)}function l(u){return e.enter("setextHeadingLineSequence"),c(u)}function c(u){return u===r?(e.consume(u),c):(e.exit("setextHeadingLineSequence"),vn(u)?Cn(e,d,"lineSuffix")(u):d(u))}function d(u){return u===null||en(u)?(e.exit("setextHeadingLine"),n(u)):s(u)}}const uM={tokenize:mM};function mM(e){const n=this,s=e.attempt(Go,a,e.attempt(this.parser.constructs.flowInitial,r,Cn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(b_,r)),"linePrefix")));return s;function a(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),n.currentConstruct=void 0,s}function r(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),n.currentConstruct=void 0,s}}const hM={resolveAll:bx()},pM=gx("string"),fM=gx("text");function gx(e){return{resolveAll:bx(e==="text"?gM:void 0),tokenize:n};function n(s){const a=this,r=this.parser.constructs[e],o=s.attempt(r,l,c);return l;function l(m){return u(m)?o(m):c(m)}function c(m){if(m===null){s.consume(m);return}return s.enter("data"),s.consume(m),d}function d(m){return u(m)?(s.exit("data"),o(m)):(s.consume(m),d)}function u(m){if(m===null)return!0;const h=r[m];let f=-1;if(h)for(;++f<h.length;){const p=h[f];if(!p.previous||p.previous.call(a,a.previous))return!0}return!1}}}function bx(e){return n;function n(s,a){let r=-1,o;for(;++r<=s.length;)o===void 0?s[r]&&s[r][1].type==="data"&&(o=r,r++):(!s[r]||s[r][1].type!=="data")&&(r!==o+2&&(s[o][1].end=s[r-1][1].end,s.splice(o+2,r-o-2),r=o+2),o=void 0);return e?e(s,a):s}}function gM(e,n){let s=0;for(;++s<=e.length;)if((s===e.length||e[s][1].type==="lineEnding")&&e[s-1][1].type==="data"){const a=e[s-1][1],r=n.sliceStream(a);let o=r.length,l=-1,c=0,d;for(;o--;){const u=r[o];if(typeof u=="string"){for(l=u.length;u.charCodeAt(l-1)===32;)c++,l--;if(l)break;l=-1}else if(u===-2)d=!0,c++;else if(u!==-1){o++;break}}if(n._contentTypeTextTrailing&&s===e.length&&(c=0),c){const u={type:s===e.length||d||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?l:a.start._bufferIndex+l,_index:a.start._index+o,line:a.end.line,column:a.end.column-c,offset:a.end.offset-c},end:{...a.end}};a.end={...u.start},a.start.offset===a.end.offset?Object.assign(a,u):(e.splice(s,0,["enter",u,n],["exit",u,n]),s+=2)}s++}return e}const bM={42:Js,43:Js,45:Js,48:Js,49:Js,50:Js,51:Js,52:Js,53:Js,54:Js,55:Js,56:Js,57:Js,62:cx},xM={91:k_},vM={[-2]:ed,[-1]:ed,32:ed},yM={35:__,42:$l,45:[lp,$l],60:I_,61:lp,95:$l,96:rp,126:rp},wM={38:ux,92:dx},kM={[-5]:td,[-4]:td,[-3]:td,33:Y_,38:ux,42:fu,60:[X2,F_],91:X_,92:[C_,dx],93:im,95:fu,96:u_},jM={null:[fu,hM]},NM={null:[42,95]},SM={null:[]},CM=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:NM,contentInitial:xM,disable:SM,document:bM,flow:yM,flowInitial:vM,insideSpan:jM,string:wM,text:kM},Symbol.toStringTag,{value:"Module"}));function EM(e,n,s){let a={_bufferIndex:-1,_index:0,line:s&&s.line||1,column:s&&s.column||1,offset:s&&s.offset||0};const r={},o=[];let l=[],c=[];const d={attempt:N(C),check:N(v),consume:y,enter:S,exit:j,interrupt:N(v,{interrupt:!0})},u={code:null,containerState:{},defineSkip:x,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:h};let m=n.tokenize.call(u,d);return n.resolveAll&&o.push(n),u;function h(M){return l=ui(l,M),w(),l[l.length-1]!==null?[]:(I(n,0),u.events=kc(o,u.events,u),u.events)}function f(M,z){return MM(p(M),z)}function p(M){return _M(l,M)}function g(){const{_bufferIndex:M,_index:z,line:U,column:R,offset:D}=a;return{_bufferIndex:M,_index:z,line:U,column:R,offset:D}}function x(M){r[M.line]=M.column,_()}function w(){let M;for(;a._index<l.length;){const z=l[a._index];if(typeof z=="string")for(M=a._index,a._bufferIndex<0&&(a._bufferIndex=0);a._index===M&&a._bufferIndex<z.length;)b(z.charCodeAt(a._bufferIndex));else b(z)}}function b(M){m=m(M)}function y(M){en(M)?(a.line++,a.column=1,a.offset+=M===-3?2:1,_()):M!==-1&&(a.column++,a.offset++),a._bufferIndex<0?a._index++:(a._bufferIndex++,a._bufferIndex===l[a._index].length&&(a._bufferIndex=-1,a._index++)),u.previous=M}function S(M,z){const U=z||{};return U.type=M,U.start=g(),u.events.push(["enter",U,u]),c.push(U),U}function j(M){const z=c.pop();return z.end=g(),u.events.push(["exit",z,u]),z}function C(M,z){I(M,z.from)}function v(M,z){z.restore()}function N(M,z){return U;function U(R,D,K){let Z,ne,O,A;return Array.isArray(R)?$(R):"tokenize"in R?$([R]):P(R);function P(je){return He;function He(xe){const Ne=xe!==null&&je[xe],Y=xe!==null&&je.null,ie=[...Array.isArray(Ne)?Ne:Ne?[Ne]:[],...Array.isArray(Y)?Y:Y?[Y]:[]];return $(ie)(xe)}}function $(je){return Z=je,ne=0,je.length===0?K:k(je[ne])}function k(je){return He;function He(xe){return A=F(),O=je,je.partial||(u.currentConstruct=je),je.name&&u.parser.constructs.disable.null.includes(je.name)?ce():je.tokenize.call(z?Object.assign(Object.create(u),z):u,d,J,ce)(xe)}}function J(je){return M(O,A),D}function ce(je){return A.restore(),++ne<Z.length?k(Z[ne]):K}}}function I(M,z){M.resolveAll&&!o.includes(M)&&o.push(M),M.resolve&&ii(u.events,z,u.events.length-z,M.resolve(u.events.slice(z),u)),M.resolveTo&&(u.events=M.resolveTo(u.events,u))}function F(){const M=g(),z=u.previous,U=u.currentConstruct,R=u.events.length,D=Array.from(c);return{from:R,restore:K};function K(){a=M,u.previous=z,u.currentConstruct=U,u.events.length=R,c=D,_()}}function _(){a.line in r&&a.column<2&&(a.column=r[a.line],a.offset+=r[a.line]-1)}}function _M(e,n){const s=n.start._index,a=n.start._bufferIndex,r=n.end._index,o=n.end._bufferIndex;let l;if(s===r)l=[e[s].slice(a,o)];else{if(l=e.slice(s,r),a>-1){const c=l[0];typeof c=="string"?l[0]=c.slice(a):l.shift()}o>0&&l.push(e[r].slice(0,o))}return l}function MM(e,n){let s=-1;const a=[];let r;for(;++s<e.length;){const o=e[s];let l;if(typeof o=="string")l=o;else switch(o){case-5:{l="\r";break}case-4:{l=`
653
+ `;break}case-3:{l=`\r
654
+ `;break}case-2:{l=n?" ":" ";break}case-1:{if(!n&&r)continue;l=" ";break}default:l=String.fromCharCode(o)}r=o===-2,a.push(l)}return a.join("")}function AM(e){const a={constructs:ox([CM,...(e||{}).extensions||[]]),content:r(V2),defined:[],document:r(K2),flow:r(uM),lazy:{},string:r(pM),text:r(fM)};return a;function r(o){return l;function l(c){return EM(a,o,c)}}}function RM(e){for(;!mx(e););return e}const cp=/[\0\t\n\r]/g;function IM(){let e=1,n="",s=!0,a;return r;function r(o,l,c){const d=[];let u,m,h,f,p;for(o=n+(typeof o=="string"?o.toString():new TextDecoder(l||void 0).decode(o)),h=0,n="",s&&(o.charCodeAt(0)===65279&&h++,s=void 0);h<o.length;){if(cp.lastIndex=h,u=cp.exec(o),f=u&&u.index!==void 0?u.index:o.length,p=o.charCodeAt(f),!u){n=o.slice(h);break}if(p===10&&h===f&&a)d.push(-3),a=void 0;else switch(a&&(d.push(-5),a=void 0),h<f&&(d.push(o.slice(h,f)),e+=f-h),p){case 0:{d.push(65533),e++;break}case 9:{for(m=Math.ceil(e/4)*4,d.push(-2);e++<m;)d.push(-1);break}case 10:{d.push(-4),e=1;break}default:a=!0,e=1}h=f+1}return c&&(a&&d.push(-5),n&&d.push(n),d.push(null)),d}}const TM=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function PM(e){return e.replace(TM,$M)}function $M(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return lx(s.slice(o?2:1),o?16:10)}return sm(s)||e}const xx={}.hasOwnProperty;function DM(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),LM(s)(RM(AM(s).document().write(IM()(e,n,!0))))}function LM(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(ve),autolinkProtocol:F,autolinkEmail:F,atxHeading:o(L),blockQuote:o(Y),characterEscape:F,characterReference:F,codeFenced:o(ie),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(ie,l),codeText:o(ee,l),codeTextData:F,data:F,codeFlowValue:F,definition:o(oe),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(W),hardBreakEscape:o(pe),hardBreakTrailing:o(pe),htmlFlow:o(fe,l),htmlFlowData:F,htmlText:o(fe,l),htmlTextData:F,image:o(B),label:l,link:o(ve),listItem:o(ae),listItemValue:f,listOrdered:o(Fe,h),listUnordered:o(Fe),paragraph:o(qe),reference:k,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(L),strong:o(Pe),thematicBreak:o(Be)},exit:{atxHeading:d(),atxHeadingSequence:C,autolink:d(),autolinkEmail:Ne,autolinkProtocol:xe,blockQuote:d(),characterEscapeValue:_,characterReferenceMarkerHexadecimal:ce,characterReferenceMarkerNumeric:ce,characterReferenceValue:je,characterReference:He,codeFenced:d(w),codeFencedFence:x,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:_,codeIndented:d(b),codeText:d(D),codeTextData:_,data:_,definition:d(),definitionDestinationString:j,definitionLabelString:y,definitionTitleString:S,emphasis:d(),hardBreakEscape:d(z),hardBreakTrailing:d(z),htmlFlow:d(U),htmlFlowData:_,htmlText:d(R),htmlTextData:_,image:d(Z),label:O,labelText:ne,lineEnding:M,link:d(K),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:J,resourceDestinationString:A,resourceTitleString:P,resource:$,setextHeading:d(I),setextHeadingLineSequence:N,setextHeadingText:v,strong:d(),thematicBreak:d()}};vx(n,(e||{}).mdastExtensions||[]);const s={};return a;function a(de){let Ie={type:"root",children:[]};const $e={stack:[Ie],tokenStack:[],config:n,enter:c,exit:u,buffer:l,resume:m,data:s},st=[];let Ue=-1;for(;++Ue<de.length;)if(de[Ue][1].type==="listOrdered"||de[Ue][1].type==="listUnordered")if(de[Ue][0]==="enter")st.push(Ue);else{const me=st.pop();Ue=r(de,me,Ue)}for(Ue=-1;++Ue<de.length;){const me=n[de[Ue][0]];xx.call(me,de[Ue][1].type)&&me[de[Ue][1].type].call(Object.assign({sliceSerialize:de[Ue][2].sliceSerialize},$e),de[Ue][1])}if($e.tokenStack.length>0){const me=$e.tokenStack[$e.tokenStack.length-1];(me[1]||dp).call($e,void 0,me[0])}for(Ie.position={start:sa(de.length>0?de[0][1].start:{line:1,column:1,offset:0}),end:sa(de.length>0?de[de.length-2][1].end:{line:1,column:1,offset:0})},Ue=-1;++Ue<n.transforms.length;)Ie=n.transforms[Ue](Ie)||Ie;return Ie}function r(de,Ie,$e){let st=Ie-1,Ue=-1,me=!1,re,_e,xt,ut;for(;++st<=$e;){const Qe=de[st];switch(Qe[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Qe[0]==="enter"?Ue++:Ue--,ut=void 0;break}case"lineEndingBlank":{Qe[0]==="enter"&&(re&&!ut&&!Ue&&!xt&&(xt=st),ut=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ut=void 0}if(!Ue&&Qe[0]==="enter"&&Qe[1].type==="listItemPrefix"||Ue===-1&&Qe[0]==="exit"&&(Qe[1].type==="listUnordered"||Qe[1].type==="listOrdered")){if(re){let vt=st;for(_e=void 0;vt--;){const Ae=de[vt];if(Ae[1].type==="lineEnding"||Ae[1].type==="lineEndingBlank"){if(Ae[0]==="exit")continue;_e&&(de[_e][1].type="lineEndingBlank",me=!0),Ae[1].type="lineEnding",_e=vt}else if(!(Ae[1].type==="linePrefix"||Ae[1].type==="blockQuotePrefix"||Ae[1].type==="blockQuotePrefixWhitespace"||Ae[1].type==="blockQuoteMarker"||Ae[1].type==="listItemIndent"))break}xt&&(!_e||xt<_e)&&(re._spread=!0),re.end=Object.assign({},_e?de[_e][1].start:Qe[1].end),de.splice(_e||st,0,["exit",re,Qe[2]]),st++,$e++}if(Qe[1].type==="listItemPrefix"){const vt={type:"listItem",_spread:!1,start:Object.assign({},Qe[1].start),end:void 0};re=vt,de.splice(st,0,["enter",vt,Qe[2]]),st++,$e++,xt=void 0,ut=!0}}}return de[Ie][1]._spread=me,$e}function o(de,Ie){return $e;function $e(st){c.call(this,de(st),st),Ie&&Ie.call(this,st)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(de,Ie,$e){this.stack[this.stack.length-1].children.push(de),this.stack.push(de),this.tokenStack.push([Ie,$e||void 0]),de.position={start:sa(Ie.start),end:void 0}}function d(de){return Ie;function Ie($e){de&&de.call(this,$e),u.call(this,$e)}}function u(de,Ie){const $e=this.stack.pop(),st=this.tokenStack.pop();if(st)st[0].type!==de.type&&(Ie?Ie.call(this,de,st[0]):(st[1]||dp).call(this,de,st[0]));else throw new Error("Cannot close `"+de.type+"` ("+ko({start:de.start,end:de.end})+"): it’s not open");$e.position.end=sa(de.end)}function m(){return nm(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(de){if(this.data.expectingFirstListItemValue){const Ie=this.stack[this.stack.length-2];Ie.start=Number.parseInt(this.sliceSerialize(de),10),this.data.expectingFirstListItemValue=void 0}}function p(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.lang=de}function g(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.meta=de}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function w(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.value=de.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.value=de.replace(/(\r?\n|\r)$/g,"")}function y(de){const Ie=this.resume(),$e=this.stack[this.stack.length-1];$e.label=Ie,$e.identifier=yi(this.sliceSerialize(de)).toLowerCase()}function S(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.title=de}function j(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.url=de}function C(de){const Ie=this.stack[this.stack.length-1];if(!Ie.depth){const $e=this.sliceSerialize(de).length;Ie.depth=$e}}function v(){this.data.setextHeadingSlurpLineEnding=!0}function N(de){const Ie=this.stack[this.stack.length-1];Ie.depth=this.sliceSerialize(de).codePointAt(0)===61?1:2}function I(){this.data.setextHeadingSlurpLineEnding=void 0}function F(de){const $e=this.stack[this.stack.length-1].children;let st=$e[$e.length-1];(!st||st.type!=="text")&&(st=nt(),st.position={start:sa(de.start),end:void 0},$e.push(st)),this.stack.push(st)}function _(de){const Ie=this.stack.pop();Ie.value+=this.sliceSerialize(de),Ie.position.end=sa(de.end)}function M(de){const Ie=this.stack[this.stack.length-1];if(this.data.atHardBreak){const $e=Ie.children[Ie.children.length-1];$e.position.end=sa(de.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(Ie.type)&&(F.call(this,de),_.call(this,de))}function z(){this.data.atHardBreak=!0}function U(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.value=de}function R(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.value=de}function D(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.value=de}function K(){const de=this.stack[this.stack.length-1];if(this.data.inReference){const Ie=this.data.referenceType||"shortcut";de.type+="Reference",de.referenceType=Ie,delete de.url,delete de.title}else delete de.identifier,delete de.label;this.data.referenceType=void 0}function Z(){const de=this.stack[this.stack.length-1];if(this.data.inReference){const Ie=this.data.referenceType||"shortcut";de.type+="Reference",de.referenceType=Ie,delete de.url,delete de.title}else delete de.identifier,delete de.label;this.data.referenceType=void 0}function ne(de){const Ie=this.sliceSerialize(de),$e=this.stack[this.stack.length-2];$e.label=PM(Ie),$e.identifier=yi(Ie).toLowerCase()}function O(){const de=this.stack[this.stack.length-1],Ie=this.resume(),$e=this.stack[this.stack.length-1];if(this.data.inReference=!0,$e.type==="link"){const st=de.children;$e.children=st}else $e.alt=Ie}function A(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.url=de}function P(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.title=de}function $(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function J(de){const Ie=this.resume(),$e=this.stack[this.stack.length-1];$e.label=Ie,$e.identifier=yi(this.sliceSerialize(de)).toLowerCase(),this.data.referenceType="full"}function ce(de){this.data.characterReferenceType=de.type}function je(de){const Ie=this.sliceSerialize(de),$e=this.data.characterReferenceType;let st;$e?(st=lx(Ie,$e==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):st=sm(Ie);const Ue=this.stack[this.stack.length-1];Ue.value+=st}function He(de){const Ie=this.stack.pop();Ie.position.end=sa(de.end)}function xe(de){_.call(this,de);const Ie=this.stack[this.stack.length-1];Ie.url=this.sliceSerialize(de)}function Ne(de){_.call(this,de);const Ie=this.stack[this.stack.length-1];Ie.url="mailto:"+this.sliceSerialize(de)}function Y(){return{type:"blockquote",children:[]}}function ie(){return{type:"code",lang:null,meta:null,value:""}}function ee(){return{type:"inlineCode",value:""}}function oe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function W(){return{type:"emphasis",children:[]}}function L(){return{type:"heading",depth:0,children:[]}}function pe(){return{type:"break"}}function fe(){return{type:"html",value:""}}function B(){return{type:"image",title:null,url:"",alt:null}}function ve(){return{type:"link",title:null,url:"",children:[]}}function Fe(de){return{type:"list",ordered:de.type==="listOrdered",start:null,spread:de._spread,children:[]}}function ae(de){return{type:"listItem",spread:de._spread,checked:null,children:[]}}function qe(){return{type:"paragraph",children:[]}}function Pe(){return{type:"strong",children:[]}}function nt(){return{type:"text",value:""}}function Be(){return{type:"thematicBreak"}}}function sa(e){return{line:e.line,column:e.column,offset:e.offset}}function vx(e,n){let s=-1;for(;++s<n.length;){const a=n[s];Array.isArray(a)?vx(e,a):OM(e,a)}}function OM(e,n){let s;for(s in n)if(xx.call(n,s))switch(s){case"canContainEols":{const a=n[s];a&&e[s].push(...a);break}case"transforms":{const a=n[s];a&&e[s].push(...a);break}case"enter":case"exit":{const a=n[s];a&&Object.assign(e[s],a);break}}}function dp(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+ko({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+ko({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+ko({start:n.start,end:n.end})+") is still open")}function FM(e){const n=this;n.parser=s;function s(a){return DM(a,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function zM(e,n){const s={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(n),!0)};return e.patch(n,s),e.applyData(n,s)}function BM(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
655
+ `}]}function UM(e,n){const s=n.value?n.value+`
656
+ `:"",a={},r=n.lang?n.lang.split(/\s+/):[];r.length>0&&(a.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:a,children:[{type:"text",value:s}]};return n.meta&&(o.data={meta:n.meta}),e.patch(n,o),o=e.applyData(n,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(n,o),o}function HM(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function qM(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function VM(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",a=String(n.identifier).toUpperCase(),r=Or(a.toLowerCase()),o=e.footnoteOrder.indexOf(a);let l,c=e.footnoteCounts.get(a);c===void 0?(c=0,e.footnoteOrder.push(a),l=e.footnoteOrder.length):l=o+1,c+=1,e.footnoteCounts.set(a,c);const d={type:"element",tagName:"a",properties:{href:"#"+s+"fn-"+r,id:s+"fnref-"+r+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(n,d);const u={type:"element",tagName:"sup",properties:{},children:[d]};return e.patch(n,u),e.applyData(n,u)}function WM(e,n){const s={type:"element",tagName:"h"+n.depth,properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function KM(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function yx(e,n){const s=n.referenceType;let a="]";if(s==="collapsed"?a+="[]":s==="full"&&(a+="["+(n.label||n.identifier)+"]"),n.type==="imageReference")return[{type:"text",value:"!["+n.alt+a}];const r=e.all(n),o=r[0];o&&o.type==="text"?o.value="["+o.value:r.unshift({type:"text",value:"["});const l=r[r.length-1];return l&&l.type==="text"?l.value+=a:r.push({type:"text",value:a}),r}function GM(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return yx(e,n);const r={src:Or(a.url||""),alt:n.alt};a.title!==null&&a.title!==void 0&&(r.title=a.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(n,o),e.applyData(n,o)}function JM(e,n){const s={src:Or(n.url)};n.alt!==null&&n.alt!==void 0&&(s.alt=n.alt),n.title!==null&&n.title!==void 0&&(s.title=n.title);const a={type:"element",tagName:"img",properties:s,children:[]};return e.patch(n,a),e.applyData(n,a)}function YM(e,n){const s={type:"text",value:n.value.replace(/\r?\n|\r/g," ")};e.patch(n,s);const a={type:"element",tagName:"code",properties:{},children:[s]};return e.patch(n,a),e.applyData(n,a)}function QM(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return yx(e,n);const r={href:Or(a.url||"")};a.title!==null&&a.title!==void 0&&(r.title=a.title);const o={type:"element",tagName:"a",properties:r,children:e.all(n)};return e.patch(n,o),e.applyData(n,o)}function XM(e,n){const s={href:Or(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const a={type:"element",tagName:"a",properties:s,children:e.all(n)};return e.patch(n,a),e.applyData(n,a)}function ZM(e,n,s){const a=e.all(n),r=s?eA(s):wx(n),o={},l=[];if(typeof n.checked=="boolean"){const m=a[0];let h;m&&m.type==="element"&&m.tagName==="p"?h=m:(h={type:"element",tagName:"p",properties:{},children:[]},a.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:n.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let c=-1;for(;++c<a.length;){const m=a[c];(r||c!==0||m.type!=="element"||m.tagName!=="p")&&l.push({type:"text",value:`
657
+ `}),m.type==="element"&&m.tagName==="p"&&!r?l.push(...m.children):l.push(m)}const d=a[a.length-1];d&&(r||d.type!=="element"||d.tagName!=="p")&&l.push({type:"text",value:`
658
+ `});const u={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,u),e.applyData(n,u)}function eA(e){let n=!1;if(e.type==="list"){n=e.spread||!1;const s=e.children;let a=-1;for(;!n&&++a<s.length;)n=wx(s[a])}return n}function wx(e){const n=e.spread;return n??e.children.length>1}function tA(e,n){const s={},a=e.all(n);let r=-1;for(typeof n.start=="number"&&n.start!==1&&(s.start=n.start);++r<a.length;){const l=a[r];if(l.type==="element"&&l.tagName==="li"&&l.properties&&Array.isArray(l.properties.className)&&l.properties.className.includes("task-list-item")){s.className=["contains-task-list"];break}}const o={type:"element",tagName:n.ordered?"ol":"ul",properties:s,children:e.wrap(a,!0)};return e.patch(n,o),e.applyData(n,o)}function nA(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function sA(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function iA(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function aA(e,n){const s=e.all(n),a=s.shift(),r=[];if(a){const l={type:"element",tagName:"thead",properties:{},children:e.wrap([a],!0)};e.patch(n.children[0],l),r.push(l)}if(s.length>0){const l={type:"element",tagName:"tbody",properties:{},children:e.wrap(s,!0)},c=Xu(n.children[1]),d=ex(n.children[n.children.length-1]);c&&d&&(l.position={start:c,end:d}),r.push(l)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(n,o),e.applyData(n,o)}function rA(e,n,s){const a=s?s.children:void 0,o=(a?a.indexOf(n):1)===0?"th":"td",l=s&&s.type==="table"?s.align:void 0,c=l?l.length:n.children.length;let d=-1;const u=[];for(;++d<c;){const h=n.children[d],f={},p=l?l[d]:void 0;p&&(f.align=p);let g={type:"element",tagName:o,properties:f,children:[]};h&&(g.children=e.all(h),e.patch(h,g),g=e.applyData(h,g)),u.push(g)}const m={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(n,m),e.applyData(n,m)}function oA(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const up=9,mp=32;function lA(e){const n=String(e),s=/\r?\n|\r/g;let a=s.exec(n),r=0;const o=[];for(;a;)o.push(hp(n.slice(r,a.index),r>0,!0),a[0]),r=a.index+a[0].length,a=s.exec(n);return o.push(hp(n.slice(r),r>0,!1)),o.join("")}function hp(e,n,s){let a=0,r=e.length;if(n){let o=e.codePointAt(a);for(;o===up||o===mp;)a++,o=e.codePointAt(a)}if(s){let o=e.codePointAt(r-1);for(;o===up||o===mp;)r--,o=e.codePointAt(r-1)}return r>a?e.slice(a,r):""}function cA(e,n){const s={type:"text",value:lA(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function dA(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const uA={blockquote:zM,break:BM,code:UM,delete:HM,emphasis:qM,footnoteReference:VM,heading:WM,html:KM,imageReference:GM,image:JM,inlineCode:YM,linkReference:QM,link:XM,listItem:ZM,list:tA,paragraph:nA,root:sA,strong:iA,table:aA,tableCell:oA,tableRow:rA,text:cA,thematicBreak:dA,toml:rl,yaml:rl,definition:rl,footnoteDefinition:rl};function rl(){}const kx=-1,jc=0,No=1,Yl=2,am=3,rm=4,om=5,lm=6,jx=7,Nx=8,pp=typeof self=="object"?self:globalThis,mA=(e,n)=>{const s=(r,o)=>(e.set(o,r),r),a=r=>{if(e.has(r))return e.get(r);const[o,l]=n[r];switch(o){case jc:case kx:return s(l,r);case No:{const c=s([],r);for(const d of l)c.push(a(d));return c}case Yl:{const c=s({},r);for(const[d,u]of l)c[a(d)]=a(u);return c}case am:return s(new Date(l),r);case rm:{const{source:c,flags:d}=l;return s(new RegExp(c,d),r)}case om:{const c=s(new Map,r);for(const[d,u]of l)c.set(a(d),a(u));return c}case lm:{const c=s(new Set,r);for(const d of l)c.add(a(d));return c}case jx:{const{name:c,message:d}=l;return s(new pp[c](d),r)}case Nx:return s(BigInt(l),r);case"BigInt":return s(Object(BigInt(l)),r);case"ArrayBuffer":return s(new Uint8Array(l).buffer,l);case"DataView":{const{buffer:c}=new Uint8Array(l);return s(new DataView(c),l)}}return s(new pp[o](l),r)};return a},fp=e=>mA(new Map,e)(0),ar="",{toString:hA}={},{keys:pA}=Object,Xr=e=>{const n=typeof e;if(n!=="object"||!e)return[jc,n];const s=hA.call(e).slice(8,-1);switch(s){case"Array":return[No,ar];case"Object":return[Yl,ar];case"Date":return[am,ar];case"RegExp":return[rm,ar];case"Map":return[om,ar];case"Set":return[lm,ar];case"DataView":return[No,s]}return s.includes("Array")?[No,s]:s.includes("Error")?[jx,s]:[Yl,s]},ol=([e,n])=>e===jc&&(n==="function"||n==="symbol"),fA=(e,n,s,a)=>{const r=(l,c)=>{const d=a.push(l)-1;return s.set(c,d),d},o=l=>{if(s.has(l))return s.get(l);let[c,d]=Xr(l);switch(c){case jc:{let m=l;switch(d){case"bigint":c=Nx,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+d);m=null;break;case"undefined":return r([kx],l)}return r([c,m],l)}case No:{if(d){let f=l;return d==="DataView"?f=new Uint8Array(l.buffer):d==="ArrayBuffer"&&(f=new Uint8Array(l)),r([d,[...f]],l)}const m=[],h=r([c,m],l);for(const f of l)m.push(o(f));return h}case Yl:{if(d)switch(d){case"BigInt":return r([d,l.toString()],l);case"Boolean":case"Number":case"String":return r([d,l.valueOf()],l)}if(n&&"toJSON"in l)return o(l.toJSON());const m=[],h=r([c,m],l);for(const f of pA(l))(e||!ol(Xr(l[f])))&&m.push([o(f),o(l[f])]);return h}case am:return r([c,l.toISOString()],l);case rm:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case om:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(ol(Xr(f))||ol(Xr(p))))&&m.push([o(f),o(p)]);return h}case lm:{const m=[],h=r([c,m],l);for(const f of l)(e||!ol(Xr(f)))&&m.push(o(f));return h}}const{message:u}=l;return r([c,{name:d,message:u}],l)};return o},gp=(e,{json:n,lossy:s}={})=>{const a=[];return fA(!(n||s),!!n,new Map,a)(e),a},Ql=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?fp(gp(e,n)):structuredClone(e):(e,n)=>fp(gp(e,n));function gA(e,n){const s=[{type:"text",value:"↩"}];return n>1&&s.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(n)}]}),s}function bA(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function xA(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||gA,a=e.options.footnoteBackLabel||bA,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let d=-1;for(;++d<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[d]);if(!u)continue;const m=e.all(u),h=String(u.identifier).toUpperCase(),f=Or(h.toLowerCase());let p=0;const g=[],x=e.footnoteCounts.get(h);for(;x!==void 0&&++p<=x;){g.length>0&&g.push({type:"text",value:" "});let y=typeof s=="string"?s:s(d,p);typeof y=="string"&&(y={type:"text",value:y}),g.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof a=="string"?a:a(d,p),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const w=m[m.length-1];if(w&&w.type==="element"&&w.tagName==="p"){const y=w.children[w.children.length-1];y&&y.type==="text"?y.value+=" ":w.children.push({type:"text",value:" "}),w.children.push(...g)}else m.push(...g);const b={type:"element",tagName:"li",properties:{id:n+"fn-"+f},children:e.wrap(m,!0)};e.patch(u,b),c.push(b)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Ql(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
659
+ `},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
660
+ `}]}}const Nc=(function(e){if(e==null)return kA;if(typeof e=="function")return Sc(e);if(typeof e=="object")return Array.isArray(e)?vA(e):yA(e);if(typeof e=="string")return wA(e);throw new Error("Expected function, string, or object as test")});function vA(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=Nc(e[s]);return Sc(a);function a(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function yA(e){const n=e;return Sc(s);function s(a){const r=a;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function wA(e){return Sc(n);function n(s){return s&&s.type===e}}function Sc(e){return n;function n(s,a,r){return!!(jA(s)&&e.call(this,s,typeof a=="number"?a:void 0,r||void 0))}}function kA(){return!0}function jA(e){return e!==null&&typeof e=="object"&&"type"in e}const Sx=[],NA=!0,gu=!1,SA="skip";function Cx(e,n,s,a){let r;typeof n=="function"&&typeof s!="function"?(a=s,s=n):r=n;const o=Nc(r),l=a?-1:1;c(e,void 0,[])();function c(d,u,m){const h=d&&typeof d=="object"?d:{};if(typeof h.type=="string"){const p=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(d.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=Sx,g,x,w;if((!n||o(d,u,m[m.length-1]||void 0))&&(p=CA(s(d,m)),p[0]===gu))return p;if("children"in d&&d.children){const b=d;if(b.children&&p[0]!==SA)for(x=(a?b.children.length:-1)+l,w=m.concat(b);x>-1&&x<b.children.length;){const y=b.children[x];if(g=c(y,x,w)(),g[0]===gu)return g;x=typeof g[1]=="number"?g[1]:x+l}}return p}}}function CA(e){return Array.isArray(e)?e:typeof e=="number"?[NA,e]:e==null?Sx:[e]}function cm(e,n,s,a){let r,o,l;typeof n=="function"&&typeof s!="function"?(o=void 0,l=n,r=s):(o=n,l=s,r=a),Cx(e,o,c,r);function c(d,u){const m=u[u.length-1],h=m?m.children.indexOf(d):void 0;return l(d,h,m)}}const bu={}.hasOwnProperty,EA={};function _A(e,n){const s=n||EA,a=new Map,r=new Map,o=new Map,l={...uA,...s.handlers},c={all:u,applyData:AA,definitionById:a,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:d,options:s,patch:MA,wrap:IA};return cm(e,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const h=m.type==="definition"?a:r,f=String(m.identifier).toUpperCase();h.has(f)||h.set(f,m)}}),c;function d(m,h){const f=m.type,p=c.handlers[f];if(bu.call(c.handlers,f)&&p)return p(c,m,h);if(c.options.passThrough&&c.options.passThrough.includes(f)){if("children"in m){const{children:x,...w}=m,b=Ql(w);return b.children=c.all(m),b}return Ql(m)}return(c.options.unknownHandler||RA)(c,m,h)}function u(m){const h=[];if("children"in m){const f=m.children;let p=-1;for(;++p<f.length;){const g=c.one(f[p],m);if(g){if(p&&f[p-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=bp(g.value)),!Array.isArray(g)&&g.type==="element")){const x=g.children[0];x&&x.type==="text"&&(x.value=bp(x.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function MA(e,n){e.position&&(n.position=b2(e))}function AA(e,n){let s=n;if(e&&e.data){const a=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;if(typeof a=="string")if(s.type==="element")s.tagName=a;else{const l="children"in s?s.children:[s];s={type:"element",tagName:a,properties:{},children:l}}s.type==="element"&&o&&Object.assign(s.properties,Ql(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function RA(e,n){const s=n.data||{},a="value"in n&&!(bu.call(s,"hProperties")||bu.call(s,"hChildren"))?{type:"text",value:n.value}:{type:"element",tagName:"div",properties:{},children:e.all(n)};return e.patch(n,a),e.applyData(n,a)}function IA(e,n){const s=[];let a=-1;for(n&&s.push({type:"text",value:`
661
+ `});++a<e.length;)a&&s.push({type:"text",value:`
662
+ `}),s.push(e[a]);return n&&e.length>0&&s.push({type:"text",value:`
663
+ `}),s}function bp(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function xp(e,n){const s=_A(e,n),a=s.one(e,void 0),r=xA(s),o=Array.isArray(a)?{type:"root",children:a}:a||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
664
+ `},r),o}function TA(e,n){return e&&"run"in e?async function(s,a){const r=xp(s,{file:a,...n});await e.run(r,a)}:function(s,a){return xp(s,{file:a,...e||n})}}function vp(e){if(e)throw e}var nd,yp;function PA(){if(yp)return nd;yp=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,a=Object.getOwnPropertyDescriptor,r=function(u){return typeof Array.isArray=="function"?Array.isArray(u):n.call(u)==="[object Array]"},o=function(u){if(!u||n.call(u)!=="[object Object]")return!1;var m=e.call(u,"constructor"),h=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!m&&!h)return!1;var f;for(f in u);return typeof f>"u"||e.call(u,f)},l=function(u,m){s&&m.name==="__proto__"?s(u,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):u[m.name]=m.newValue},c=function(u,m){if(m==="__proto__")if(e.call(u,m)){if(a)return a(u,m).value}else return;return u[m]};return nd=function d(){var u,m,h,f,p,g,x=arguments[0],w=1,b=arguments.length,y=!1;for(typeof x=="boolean"&&(y=x,x=arguments[1]||{},w=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});w<b;++w)if(u=arguments[w],u!=null)for(m in u)h=c(x,m),f=c(u,m),x!==f&&(y&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=h&&r(h)?h:[]):g=h&&o(h)?h:{},l(x,{name:m,newValue:d(y,g,f)})):typeof f<"u"&&l(x,{name:m,newValue:f}));return x},nd}var $A=PA();const sd=Bg($A);function xu(e){if(typeof e!="object"||e===null)return!1;const n=Object.getPrototypeOf(e);return(n===null||n===Object.prototype||Object.getPrototypeOf(n)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function DA(){const e=[],n={run:s,use:a};return n;function s(...r){let o=-1;const l=r.pop();if(typeof l!="function")throw new TypeError("Expected function as last argument, not "+l);c(null,...r);function c(d,...u){const m=e[++o];let h=-1;if(d){l(d);return}for(;++h<r.length;)(u[h]===null||u[h]===void 0)&&(u[h]=r[h]);r=u,m?LA(m,c)(...u):l(null,...u)}}function a(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),n}}function LA(e,n){let s;return a;function a(...l){const c=e.length>l.length;let d;c&&l.push(r);try{d=e.apply(this,l)}catch(u){const m=u;if(c&&s)throw m;return r(m)}c||(d&&d.then&&typeof d.then=="function"?d.then(o,r):d instanceof Error?r(d):o(d))}function r(l,...c){s||(s=!0,n(l,...c))}function o(l){r(null,l)}}const Ri={basename:OA,dirname:FA,extname:zA,join:BA,sep:"/"};function OA(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Jo(e);let s=0,a=-1,r=e.length,o;if(n===void 0||n.length===0||n.length>e.length){for(;r--;)if(e.codePointAt(r)===47){if(o){s=r+1;break}}else a<0&&(o=!0,a=r+1);return a<0?"":e.slice(s,a)}if(n===e)return"";let l=-1,c=n.length-1;for(;r--;)if(e.codePointAt(r)===47){if(o){s=r+1;break}}else l<0&&(o=!0,l=r+1),c>-1&&(e.codePointAt(r)===n.codePointAt(c--)?c<0&&(a=r):(c=-1,a=l));return s===a?a=l:a<0&&(a=e.length),e.slice(s,a)}function FA(e){if(Jo(e),e.length===0)return".";let n=-1,s=e.length,a;for(;--s;)if(e.codePointAt(s)===47){if(a){n=s;break}}else a||(a=!0);return n<0?e.codePointAt(0)===47?"/":".":n===1&&e.codePointAt(0)===47?"//":e.slice(0,n)}function zA(e){Jo(e);let n=e.length,s=-1,a=0,r=-1,o=0,l;for(;n--;){const c=e.codePointAt(n);if(c===47){if(l){a=n+1;break}continue}s<0&&(l=!0,s=n+1),c===46?r<0?r=n:o!==1&&(o=1):r>-1&&(o=-1)}return r<0||s<0||o===0||o===1&&r===s-1&&r===a+1?"":e.slice(r,s)}function BA(...e){let n=-1,s;for(;++n<e.length;)Jo(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":UA(s)}function UA(e){Jo(e);const n=e.codePointAt(0)===47;let s=HA(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function HA(e,n){let s="",a=0,r=-1,o=0,l=-1,c,d;for(;++l<=e.length;){if(l<e.length)c=e.codePointAt(l);else{if(c===47)break;c=47}if(c===47){if(!(r===l-1||o===1))if(r!==l-1&&o===2){if(s.length<2||a!==2||s.codePointAt(s.length-1)!==46||s.codePointAt(s.length-2)!==46){if(s.length>2){if(d=s.lastIndexOf("/"),d!==s.length-1){d<0?(s="",a=0):(s=s.slice(0,d),a=s.length-1-s.lastIndexOf("/")),r=l,o=0;continue}}else if(s.length>0){s="",a=0,r=l,o=0;continue}}n&&(s=s.length>0?s+"/..":"..",a=2)}else s.length>0?s+="/"+e.slice(r+1,l):s=e.slice(r+1,l),a=l-r-1;r=l,o=0}else c===46&&o>-1?o++:o=-1}return s}function Jo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const qA={cwd:VA};function VA(){return"/"}function vu(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function WA(e){if(typeof e=="string")e=new URL(e);else if(!vu(e)){const n=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw n.code="ERR_INVALID_ARG_TYPE",n}if(e.protocol!=="file:"){const n=new TypeError("The URL must be of scheme file");throw n.code="ERR_INVALID_URL_SCHEME",n}return KA(e)}function KA(e){if(e.hostname!==""){const a=new TypeError('File URL host must be "localhost" or empty on darwin');throw a.code="ERR_INVALID_FILE_URL_HOST",a}const n=e.pathname;let s=-1;for(;++s<n.length;)if(n.codePointAt(s)===37&&n.codePointAt(s+1)===50){const a=n.codePointAt(s+2);if(a===70||a===102){const r=new TypeError("File URL path must not include encoded / characters");throw r.code="ERR_INVALID_FILE_URL_PATH",r}}return decodeURIComponent(n)}const id=["history","path","basename","stem","extname","dirname"];class Ex{constructor(n){let s;n?vu(n)?s={path:n}:typeof n=="string"||GA(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":qA.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let a=-1;for(;++a<id.length;){const o=id[a];o in s&&s[o]!==void 0&&s[o]!==null&&(this[o]=o==="history"?[...s[o]]:s[o])}let r;for(r in s)id.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Ri.basename(this.path):void 0}set basename(n){rd(n,"basename"),ad(n,"basename"),this.path=Ri.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Ri.dirname(this.path):void 0}set dirname(n){wp(this.basename,"dirname"),this.path=Ri.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Ri.extname(this.path):void 0}set extname(n){if(ad(n,"extname"),wp(this.dirname,"extname"),n){if(n.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(n.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Ri.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){vu(n)&&(n=WA(n)),rd(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Ri.basename(this.path,this.extname):void 0}set stem(n){rd(n,"stem"),ad(n,"stem"),this.path=Ri.join(this.dirname||"",n+(this.extname||""))}fail(n,s,a){const r=this.message(n,s,a);throw r.fatal=!0,r}info(n,s,a){const r=this.message(n,s,a);return r.fatal=void 0,r}message(n,s,a){const r=new Bs(n,s,a);return this.path&&(r.name=this.path+":"+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(n){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(n||void 0).decode(this.value)}}function ad(e,n){if(e&&e.includes(Ri.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Ri.sep+"`")}function rd(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function wp(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function GA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const JA=(function(e){const a=this.constructor.prototype,r=a[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,a),o}),YA={}.hasOwnProperty;class dm extends JA{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=DA()}copy(){const n=new dm;let s=-1;for(;++s<this.attachers.length;){const a=this.attachers[s];n.use(...a)}return n.data(sd(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(cd("data",this.frozen),this.namespace[n]=s,this):YA.call(this.namespace,n)&&this.namespace[n]||void 0:n?(cd("data",this.frozen),this.namespace=n,this):this.namespace}freeze(){if(this.frozen)return this;const n=this;for(;++this.freezeIndex<this.attachers.length;){const[s,...a]=this.attachers[this.freezeIndex];if(a[0]===!1)continue;a[0]===!0&&(a[0]=void 0);const r=s.call(n,...a);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(n){this.freeze();const s=ll(n),a=this.parser||this.Parser;return od("parse",a),a(String(s),s)}process(n,s){const a=this;return this.freeze(),od("process",this.parser||this.Parser),ld("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=ll(n),d=a.parse(c);a.run(d,c,function(m,h,f){if(m||!h||!f)return u(m);const p=h,g=a.stringify(p,f);ZA(g)?f.value=g:f.result=g,u(m,f)});function u(m,h){m||!h?l(m):o?o(h):s(void 0,h)}}}processSync(n){let s=!1,a;return this.freeze(),od("processSync",this.parser||this.Parser),ld("processSync",this.compiler||this.Compiler),this.process(n,r),jp("processSync","process",s),a;function r(o,l){s=!0,vp(o),a=l}}run(n,s,a){kp(n),this.freeze();const r=this.transformers;return!a&&typeof s=="function"&&(a=s,s=void 0),a?o(void 0,a):new Promise(o);function o(l,c){const d=ll(s);r.run(n,d,u);function u(m,h,f){const p=h||n;m?c(m):l?l(p):a(void 0,p,f)}}}runSync(n,s){let a=!1,r;return this.run(n,s,o),jp("runSync","run",a),r;function o(l,c){vp(l),r=c,a=!0}}stringify(n,s){this.freeze();const a=ll(s),r=this.compiler||this.Compiler;return ld("stringify",r),kp(n),r(n,a)}use(n,...s){const a=this.attachers,r=this.namespace;if(cd("use",this.frozen),n!=null)if(typeof n=="function")d(n,s);else if(typeof n=="object")Array.isArray(n)?c(n):l(n);else throw new TypeError("Expected usable value, not `"+n+"`");return this;function o(u){if(typeof u=="function")d(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[m,...h]=u;d(m,h)}else l(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function l(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");c(u.plugins),u.settings&&(r.settings=sd(!0,r.settings,u.settings))}function c(u){let m=-1;if(u!=null)if(Array.isArray(u))for(;++m<u.length;){const h=u[m];o(h)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function d(u,m){let h=-1,f=-1;for(;++h<a.length;)if(a[h][0]===u){f=h;break}if(f===-1)a.push([u,...m]);else if(m.length>0){let[p,...g]=m;const x=a[f][1];xu(x)&&xu(p)&&(p=sd(!0,x,p)),a[f]=[u,p,...g]}}}}const QA=new dm().freeze();function od(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function ld(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function cd(e,n){if(n)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function kp(e){if(!xu(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function jp(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function ll(e){return XA(e)?e:new Ex(e)}function XA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function ZA(e){return typeof e=="string"||eR(e)}function eR(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const tR="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Np=[],Sp={allowDangerousHtml:!0},nR=/^(https?|ircs?|mailto|xmpp)$/i,sR=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function ki(e){const n=iR(e),s=aR(e);return rR(n.runSync(n.parse(s),s),e)}function iR(e){const n=e.rehypePlugins||Np,s=e.remarkPlugins||Np,a=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Sp}:Sp;return QA().use(FM).use(s).use(TA,a).use(n)}function aR(e){const n=e.children||"",s=new Ex;return typeof n=="string"&&(s.value=n),s}function rR(e,n){const s=n.allowedElements,a=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,d=n.urlTransform||oR;for(const m of sR)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+tR+m.id,void 0);return cm(e,u),k2(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function u(m,h,f){if(m.type==="raw"&&f&&typeof h=="number")return l?f.children.splice(h,1):f.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let p;for(p in Zc)if(Object.hasOwn(Zc,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],x=Zc[p];(x===null||x.includes(m.tagName))&&(m.properties[p]=d(String(g||""),p,m))}}if(m.type==="element"){let p=s?!s.includes(m.tagName):o?o.includes(m.tagName):!1;if(!p&&a&&typeof h=="number"&&(p=!a(m,h,f)),p&&f&&typeof h=="number")return c&&m.children?f.children.splice(h,1,...m.children):f.children.splice(h,1),h}}}function oR(e){const n=e.indexOf(":"),s=e.indexOf("?"),a=e.indexOf("#"),r=e.indexOf("/");return n===-1||r!==-1&&n>r||s!==-1&&n>s||a!==-1&&n>a||nR.test(e.slice(0,n))?e:""}function Cp(e,n){const s=String(e);if(typeof n!="string")throw new TypeError("Expected character");let a=0,r=s.indexOf(n);for(;r!==-1;)a++,r=s.indexOf(n,r+n.length);return a}function lR(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function cR(e,n,s){const r=Nc((s||{}).ignore||[]),o=dR(n);let l=-1;for(;++l<o.length;)Cx(e,"text",c);function c(u,m){let h=-1,f;for(;++h<m.length;){const p=m[h],g=f?f.children:void 0;if(r(p,g?g.indexOf(p):void 0,f))return;f=p}if(f)return d(u,m)}function d(u,m){const h=m[m.length-1],f=o[l][0],p=o[l][1];let g=0;const w=h.children.indexOf(u);let b=!1,y=[];f.lastIndex=0;let S=f.exec(u.value);for(;S;){const j=S.index,C={index:S.index,input:S.input,stack:[...m,u]};let v=p(...S,C);if(typeof v=="string"&&(v=v.length>0?{type:"text",value:v}:void 0),v===!1?f.lastIndex=j+1:(g!==j&&y.push({type:"text",value:u.value.slice(g,j)}),Array.isArray(v)?y.push(...v):v&&y.push(v),g=j+S[0].length,b=!0),!f.global)break;S=f.exec(u.value)}return b?(g<u.value.length&&y.push({type:"text",value:u.value.slice(g)}),h.children.splice(w,1,...y)):y=[u],w+y.length}}function dR(e){const n=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const s=!e[0]||Array.isArray(e[0])?e:[e];let a=-1;for(;++a<s.length;){const r=s[a];n.push([uR(r[0]),mR(r[1])])}return n}function uR(e){return typeof e=="string"?new RegExp(lR(e),"g"):e}function mR(e){return typeof e=="function"?e:function(){return e}}const dd="phrasing",ud=["autolink","link","image","label"];function hR(){return{transforms:[yR],enter:{literalAutolink:fR,literalAutolinkEmail:md,literalAutolinkHttp:md,literalAutolinkWww:md},exit:{literalAutolink:vR,literalAutolinkEmail:xR,literalAutolinkHttp:gR,literalAutolinkWww:bR}}}function pR(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:dd,notInConstruct:ud},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:dd,notInConstruct:ud},{character:":",before:"[ps]",after:"\\/",inConstruct:dd,notInConstruct:ud}]}}function fR(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function md(e){this.config.enter.autolinkProtocol.call(this,e)}function gR(e){this.config.exit.autolinkProtocol.call(this,e)}function bR(e){this.config.exit.data.call(this,e);const n=this.stack[this.stack.length-1];n.type,n.url="http://"+this.sliceSerialize(e)}function xR(e){this.config.exit.autolinkEmail.call(this,e)}function vR(e){this.exit(e)}function yR(e){cR(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,wR],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,kR]],{ignore:["link","linkReference"]})}function wR(e,n,s,a,r){let o="";if(!_x(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!jR(s)))return!1;const l=NR(s+a);if(!l[0])return!1;const c={type:"link",title:null,url:o+n+l[0],children:[{type:"text",value:n+l[0]}]};return l[1]?[c,{type:"text",value:l[1]}]:c}function kR(e,n,s,a){return!_x(a,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function jR(e){const n=e.split(".");return!(n.length<2||n[n.length-1]&&(/_/.test(n[n.length-1])||!/[a-zA-Z\d]/.test(n[n.length-1]))||n[n.length-2]&&(/_/.test(n[n.length-2])||!/[a-zA-Z\d]/.test(n[n.length-2])))}function NR(e){const n=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!n)return[e,void 0];e=e.slice(0,n.index);let s=n[0],a=s.indexOf(")");const r=Cp(e,"(");let o=Cp(e,")");for(;a!==-1&&r>o;)e+=s.slice(0,a+1),s=s.slice(a+1),a=s.indexOf(")"),o++;return[e,s]}function _x(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||za(s)||wc(s))&&(!n||s!==47)}Mx.peek=TR;function SR(){this.buffer()}function CR(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function ER(){this.buffer()}function _R(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function MR(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=yi(this.sliceSerialize(e)).toLowerCase(),s.label=n}function AR(e){this.exit(e)}function RR(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=yi(this.sliceSerialize(e)).toLowerCase(),s.label=n}function IR(e){this.exit(e)}function TR(){return"["}function Mx(e,n,s,a){const r=s.createTracker(a);let o=r.move("[^");const l=s.enter("footnoteReference"),c=s.enter("reference");return o+=r.move(s.safe(s.associationId(e),{after:"]",before:o})),c(),l(),o+=r.move("]"),o}function PR(){return{enter:{gfmFootnoteCallString:SR,gfmFootnoteCall:CR,gfmFootnoteDefinitionLabelString:ER,gfmFootnoteDefinition:_R},exit:{gfmFootnoteCallString:MR,gfmFootnoteCall:AR,gfmFootnoteDefinitionLabelString:RR,gfmFootnoteDefinition:IR}}}function $R(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Mx},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function s(a,r,o,l){const c=o.createTracker(l);let d=c.move("[^");const u=o.enter("footnoteDefinition"),m=o.enter("label");return d+=c.move(o.safe(o.associationId(a),{before:d,after:"]"})),m(),d+=c.move("]:"),a.children&&a.children.length>0&&(c.shift(4),d+=c.move((n?`
665
+ `:" ")+o.indentLines(o.containerFlow(a,c.current()),n?Ax:DR))),u(),d}}function DR(e,n,s){return n===0?e:Ax(e,n,s)}function Ax(e,n,s){return(s?"":" ")+e}const LR=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Rx.peek=UR;function OR(){return{canContainEols:["delete"],enter:{strikethrough:zR},exit:{strikethrough:BR}}}function FR(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:LR}],handlers:{delete:Rx}}}function zR(e){this.enter({type:"delete",children:[]},e)}function BR(e){this.exit(e)}function Rx(e,n,s,a){const r=s.createTracker(a),o=s.enter("strikethrough");let l=r.move("~~");return l+=s.containerPhrasing(e,{...r.current(),before:l,after:"~"}),l+=r.move("~~"),o(),l}function UR(){return"~"}function HR(e){return e.length}function qR(e,n){const s=n||{},a=(s.align||[]).concat(),r=s.stringLength||HR,o=[],l=[],c=[],d=[];let u=0,m=-1;for(;++m<e.length;){const x=[],w=[];let b=-1;for(e[m].length>u&&(u=e[m].length);++b<e[m].length;){const y=VR(e[m][b]);if(s.alignDelimiters!==!1){const S=r(y);w[b]=S,(d[b]===void 0||S>d[b])&&(d[b]=S)}x.push(y)}l[m]=x,c[m]=w}let h=-1;if(typeof a=="object"&&"length"in a)for(;++h<u;)o[h]=Ep(a[h]);else{const x=Ep(a);for(;++h<u;)o[h]=x}h=-1;const f=[],p=[];for(;++h<u;){const x=o[h];let w="",b="";x===99?(w=":",b=":"):x===108?w=":":x===114&&(b=":");let y=s.alignDelimiters===!1?1:Math.max(1,d[h]-w.length-b.length);const S=w+"-".repeat(y)+b;s.alignDelimiters!==!1&&(y=w.length+y+b.length,y>d[h]&&(d[h]=y),p[h]=y),f[h]=S}l.splice(1,0,f),c.splice(1,0,p),m=-1;const g=[];for(;++m<l.length;){const x=l[m],w=c[m];h=-1;const b=[];for(;++h<u;){const y=x[h]||"";let S="",j="";if(s.alignDelimiters!==!1){const C=d[h]-(w[h]||0),v=o[h];v===114?S=" ".repeat(C):v===99?C%2?(S=" ".repeat(C/2+.5),j=" ".repeat(C/2-.5)):(S=" ".repeat(C/2),j=S):j=" ".repeat(C)}s.delimiterStart!==!1&&!h&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&b.push(" "),s.alignDelimiters!==!1&&b.push(S),b.push(y),s.alignDelimiters!==!1&&b.push(j),s.padding!==!1&&b.push(" "),(s.delimiterEnd!==!1||h!==u-1)&&b.push("|")}g.push(s.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return g.join(`
666
+ `)}function VR(e){return e==null?"":String(e)}function Ep(e){const n=typeof e=="string"?e.codePointAt(0):0;return n===67||n===99?99:n===76||n===108?108:n===82||n===114?114:0}function WR(e,n,s,a){const r=s.enter("blockquote"),o=s.createTracker(a);o.move("> "),o.shift(2);const l=s.indentLines(s.containerFlow(e,o.current()),KR);return r(),l}function KR(e,n,s){return">"+(s?"":" ")+e}function GR(e,n){return _p(e,n.inConstruct,!0)&&!_p(e,n.notInConstruct,!1)}function _p(e,n,s){if(typeof n=="string"&&(n=[n]),!n||n.length===0)return s;let a=-1;for(;++a<n.length;)if(e.includes(n[a]))return!0;return!1}function Mp(e,n,s,a){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
667
+ `&&GR(s.stack,s.unsafe[r]))return/[ \t]/.test(a.before)?"":" ";return`\\
668
+ `}function JR(e,n){const s=String(e);let a=s.indexOf(n),r=a,o=0,l=0;if(typeof n!="string")throw new TypeError("Expected substring");for(;a!==-1;)a===r?++o>l&&(l=o):o=1,r=a+n.length,a=s.indexOf(n,r);return l}function YR(e,n){return!!(n.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function QR(e){const n=e.options.fence||"`";if(n!=="`"&&n!=="~")throw new Error("Cannot serialize code with `"+n+"` for `options.fence`, expected `` ` `` or `~`");return n}function XR(e,n,s,a){const r=QR(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(YR(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,ZR);return h(),f}const c=s.createTracker(a),d=r.repeat(Math.max(JR(o,r)+1,3)),u=s.enter("codeFenced");let m=c.move(d);if(e.lang){const h=s.enter(`codeFencedLang${l}`);m+=c.move(s.safe(e.lang,{before:m,after:" ",encode:["`"],...c.current()})),h()}if(e.lang&&e.meta){const h=s.enter(`codeFencedMeta${l}`);m+=c.move(" "),m+=c.move(s.safe(e.meta,{before:m,after:`
669
+ `,encode:["`"],...c.current()})),h()}return m+=c.move(`
670
+ `),o&&(m+=c.move(o+`
671
+ `)),m+=c.move(d),u(),m}function ZR(e,n,s){return(s?"":" ")+e}function um(e){const n=e.options.quote||'"';if(n!=='"'&&n!=="'")throw new Error("Cannot serialize title with `"+n+"` for `options.quote`, expected `\"`, or `'`");return n}function eI(e,n,s,a){const r=um(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("definition");let c=s.enter("label");const d=s.createTracker(a);let u=d.move("[");return u+=d.move(s.safe(s.associationId(e),{before:u,after:"]",...d.current()})),u+=d.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),u+=d.move("<"),u+=d.move(s.safe(e.url,{before:u,after:">",...d.current()})),u+=d.move(">")):(c=s.enter("destinationRaw"),u+=d.move(s.safe(e.url,{before:u,after:e.title?" ":`
672
+ `,...d.current()}))),c(),e.title&&(c=s.enter(`title${o}`),u+=d.move(" "+r),u+=d.move(s.safe(e.title,{before:u,after:r,...d.current()})),u+=d.move(r),c()),l(),u}function tI(e){const n=e.options.emphasis||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize emphasis with `"+n+"` for `options.emphasis`, expected `*`, or `_`");return n}function Ro(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Xl(e,n,s){const a=Sr(e),r=Sr(n);return a===void 0?r===void 0?s==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:a===1?r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Ix.peek=nI;function Ix(e,n,s,a){const r=tI(s),o=s.enter("emphasis"),l=s.createTracker(a),c=l.move(r);let d=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const u=d.charCodeAt(0),m=Xl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=Ro(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=Xl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+Ro(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function nI(e,n,s){return s.options.emphasis||"*"}function sI(e,n){let s=!1;return cm(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return s=!0,gu}),!!((!e.depth||e.depth<3)&&nm(e)&&(n.options.setext||s))}function iI(e,n,s,a){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(a);if(sI(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),f=s.containerPhrasing(e,{...o.current(),before:`
673
+ `,after:`
674
+ `});return h(),m(),f+`
675
+ `+(r===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
676
+ `))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),d=s.enter("phrasing");o.move(l+" ");let u=s.containerPhrasing(e,{before:"# ",after:`
677
+ `,...o.current()});return/^[\t ]/.test(u)&&(u=Ro(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,s.options.closeAtx&&(u+=" "+l),d(),c(),u}Tx.peek=aI;function Tx(e){return e.value||""}function aI(){return"<"}Px.peek=rI;function Px(e,n,s,a){const r=um(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("image");let c=s.enter("label");const d=s.createTracker(a);let u=d.move("![");return u+=d.move(s.safe(e.alt,{before:u,after:"]",...d.current()})),u+=d.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),u+=d.move("<"),u+=d.move(s.safe(e.url,{before:u,after:">",...d.current()})),u+=d.move(">")):(c=s.enter("destinationRaw"),u+=d.move(s.safe(e.url,{before:u,after:e.title?" ":")",...d.current()}))),c(),e.title&&(c=s.enter(`title${o}`),u+=d.move(" "+r),u+=d.move(s.safe(e.title,{before:u,after:r,...d.current()})),u+=d.move(r),c()),u+=d.move(")"),l(),u}function rI(){return"!"}$x.peek=oI;function $x(e,n,s,a){const r=e.referenceType,o=s.enter("imageReference");let l=s.enter("label");const c=s.createTracker(a);let d=c.move("![");const u=s.safe(e.alt,{before:d,after:"]",...c.current()});d+=c.move(u+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:d,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!u||u!==h?d+=c.move(h+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function oI(){return"!"}Dx.peek=lI;function Dx(e,n,s){let a=e.value||"",r="`",o=-1;for(;new RegExp("(^|[^`])"+r+"([^`]|$)").test(a);)r+="`";for(/[^ \r\n]/.test(a)&&(/^[ \r\n]/.test(a)&&/[ \r\n]$/.test(a)||/^`|`$/.test(a))&&(a=" "+a+" ");++o<s.unsafe.length;){const l=s.unsafe[o],c=s.compilePattern(l);let d;if(l.atBreak)for(;d=c.exec(a);){let u=d.index;a.charCodeAt(u)===10&&a.charCodeAt(u-1)===13&&u--,a=a.slice(0,u)+" "+a.slice(d.index+1)}}return r+a+r}function lI(){return"`"}function Lx(e,n){const s=nm(e);return!!(!n.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(s===e.url||"mailto:"+s===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}Ox.peek=cI;function Ox(e,n,s,a){const r=um(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(a);let c,d;if(Lx(e,s)){const m=s.stack;s.stack=[],c=s.enter("autolink");let h=l.move("<");return h+=l.move(s.containerPhrasing(e,{before:h,after:">",...l.current()})),h+=l.move(">"),c(),s.stack=m,h}c=s.enter("link"),d=s.enter("label");let u=l.move("[");return u+=l.move(s.containerPhrasing(e,{before:u,after:"](",...l.current()})),u+=l.move("]("),d(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(d=s.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(s.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(d=s.enter("destinationRaw"),u+=l.move(s.safe(e.url,{before:u,after:e.title?" ":")",...l.current()}))),d(),e.title&&(d=s.enter(`title${o}`),u+=l.move(" "+r),u+=l.move(s.safe(e.title,{before:u,after:r,...l.current()})),u+=l.move(r),d()),u+=l.move(")"),c(),u}function cI(e,n,s){return Lx(e,s)?"<":"["}Fx.peek=dI;function Fx(e,n,s,a){const r=e.referenceType,o=s.enter("linkReference");let l=s.enter("label");const c=s.createTracker(a);let d=c.move("[");const u=s.containerPhrasing(e,{before:d,after:"]",...c.current()});d+=c.move(u+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:d,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!u||u!==h?d+=c.move(h+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function dI(){return"["}function mm(e){const n=e.options.bullet||"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bullet`, expected `*`, `+`, or `-`");return n}function uI(e){const n=mm(e),s=e.options.bulletOther;if(!s)return n==="*"?"-":"*";if(s!=="*"&&s!=="+"&&s!=="-")throw new Error("Cannot serialize items with `"+s+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(s===n)throw new Error("Expected `bullet` (`"+n+"`) and `bulletOther` (`"+s+"`) to be different");return s}function mI(e){const n=e.options.bulletOrdered||".";if(n!=="."&&n!==")")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOrdered`, expected `.` or `)`");return n}function zx(e){const n=e.options.rule||"*";if(n!=="*"&&n!=="-"&&n!=="_")throw new Error("Cannot serialize rules with `"+n+"` for `options.rule`, expected `*`, `-`, or `_`");return n}function hI(e,n,s,a){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?mI(s):mm(s);const c=e.ordered?l==="."?")":".":uI(s);let d=n&&s.bulletLastUsed?l===s.bulletLastUsed:!1;if(!e.ordered){const m=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&m&&(!m.children||!m.children[0])&&s.stack[s.stack.length-1]==="list"&&s.stack[s.stack.length-2]==="listItem"&&s.stack[s.stack.length-3]==="list"&&s.stack[s.stack.length-4]==="listItem"&&s.indexStack[s.indexStack.length-1]===0&&s.indexStack[s.indexStack.length-2]===0&&s.indexStack[s.indexStack.length-3]===0&&(d=!0),zx(s)===l&&m){let h=-1;for(;++h<e.children.length;){const f=e.children[h];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){d=!0;break}}}}d&&(l=c),s.bulletCurrent=l;const u=s.containerFlow(e,a);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),u}function pI(e){const n=e.options.listItemIndent||"one";if(n!=="tab"&&n!=="one"&&n!=="mixed")throw new Error("Cannot serialize items with `"+n+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return n}function fI(e,n,s,a){const r=pI(s);let o=s.bulletCurrent||mm(s);n&&n.type==="list"&&n.ordered&&(o=(typeof n.start=="number"&&n.start>-1?n.start:1)+(s.options.incrementListMarker===!1?0:n.children.indexOf(e))+o);let l=o.length+1;(r==="tab"||r==="mixed"&&(n&&n.type==="list"&&n.spread||e.spread))&&(l=Math.ceil(l/4)*4);const c=s.createTracker(a);c.move(o+" ".repeat(l-o.length)),c.shift(l);const d=s.enter("listItem"),u=s.indentLines(s.containerFlow(e,c.current()),m);return d(),u;function m(h,f,p){return f?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function gI(e,n,s,a){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,a);return o(),r(),l}const bI=Nc(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function xI(e,n,s,a){return(e.children.some(function(l){return bI(l)})?s.containerPhrasing:s.containerFlow).call(s,e,a)}function vI(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Bx.peek=yI;function Bx(e,n,s,a){const r=vI(s),o=s.enter("strong"),l=s.createTracker(a),c=l.move(r+r);let d=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const u=d.charCodeAt(0),m=Xl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=Ro(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=Xl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+Ro(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function yI(e,n,s){return s.options.strong||"*"}function wI(e,n,s,a){return s.safe(e.value,a)}function kI(e){const n=e.options.ruleRepetition||3;if(n<3)throw new Error("Cannot serialize rules with repetition `"+n+"` for `options.ruleRepetition`, expected `3` or more");return n}function jI(e,n,s){const a=(zx(s)+(s.options.ruleSpaces?" ":"")).repeat(kI(s));return s.options.ruleSpaces?a.slice(0,-1):a}const Ux={blockquote:WR,break:Mp,code:XR,definition:eI,emphasis:Ix,hardBreak:Mp,heading:iI,html:Tx,image:Px,imageReference:$x,inlineCode:Dx,link:Ox,linkReference:Fx,list:hI,listItem:fI,paragraph:gI,root:xI,strong:Bx,text:wI,thematicBreak:jI};function NI(){return{enter:{table:SI,tableData:Ap,tableHeader:Ap,tableRow:EI},exit:{codeText:_I,table:CI,tableData:hd,tableHeader:hd,tableRow:hd}}}function SI(e){const n=e._align;this.enter({type:"table",align:n.map(function(s){return s==="none"?null:s}),children:[]},e),this.data.inTable=!0}function CI(e){this.exit(e),this.data.inTable=void 0}function EI(e){this.enter({type:"tableRow",children:[]},e)}function hd(e){this.exit(e)}function Ap(e){this.enter({type:"tableCell",children:[]},e)}function _I(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,MI));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function MI(e,n){return n==="|"?n:e}function AI(e){const n=e||{},s=n.tableCellPadding,a=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
678
+ `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:d,tableRow:c}};function l(p,g,x,w){return u(m(p,x,w),p.align)}function c(p,g,x,w){const b=h(p,x,w),y=u([b]);return y.slice(0,y.indexOf(`
679
+ `))}function d(p,g,x,w){const b=x.enter("tableCell"),y=x.enter("phrasing"),S=x.containerPhrasing(p,{...w,before:o,after:o});return y(),b(),S}function u(p,g){return qR(p,{align:g,alignDelimiters:a,padding:s,stringLength:r})}function m(p,g,x){const w=p.children;let b=-1;const y=[],S=g.enter("table");for(;++b<w.length;)y[b]=h(w[b],g,x);return S(),y}function h(p,g,x){const w=p.children;let b=-1;const y=[],S=g.enter("tableRow");for(;++b<w.length;)y[b]=d(w[b],p,g,x);return S(),y}function f(p,g,x){let w=Ux.inlineCode(p,g,x);return x.stack.includes("tableCell")&&(w=w.replace(/\|/g,"\\$&")),w}}function RI(){return{exit:{taskListCheckValueChecked:Rp,taskListCheckValueUnchecked:Rp,paragraph:TI}}}function II(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:PI}}}function Rp(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function TI(e){const n=this.stack[this.stack.length-2];if(n&&n.type==="listItem"&&typeof n.checked=="boolean"){const s=this.stack[this.stack.length-1];s.type;const a=s.children[0];if(a&&a.type==="text"){const r=n.children;let o=-1,l;for(;++o<r.length;){const c=r[o];if(c.type==="paragraph"){l=c;break}}l===s&&(a.value=a.value.slice(1),a.value.length===0?s.children.shift():s.position&&a.position&&typeof a.position.start.offset=="number"&&(a.position.start.column++,a.position.start.offset++,s.position.start=Object.assign({},a.position.start)))}}this.exit(e)}function PI(e,n,s,a){const r=e.children[0],o=typeof e.checked=="boolean"&&r&&r.type==="paragraph",l="["+(e.checked?"x":" ")+"] ",c=s.createTracker(a);o&&c.move(l);let d=Ux.listItem(e,n,s,{...a,...c.current()});return o&&(d=d.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),d;function u(m){return m+l}}function $I(){return[hR(),PR(),OR(),NI(),RI()]}function DI(e){return{extensions:[pR(),$R(e),FR(),AI(e),II()]}}const LI={tokenize:HI,partial:!0},Hx={tokenize:qI,partial:!0},qx={tokenize:VI,partial:!0},Vx={tokenize:WI,partial:!0},OI={tokenize:KI,partial:!0},Wx={name:"wwwAutolink",tokenize:BI,previous:Gx},Kx={name:"protocolAutolink",tokenize:UI,previous:Jx},Xi={name:"emailAutolink",tokenize:zI,previous:Yx},Oi={};function FI(){return{text:Oi}}let Aa=48;for(;Aa<123;)Oi[Aa]=Xi,Aa++,Aa===58?Aa=65:Aa===91&&(Aa=97);Oi[43]=Xi;Oi[45]=Xi;Oi[46]=Xi;Oi[95]=Xi;Oi[72]=[Xi,Kx];Oi[104]=[Xi,Kx];Oi[87]=[Xi,Wx];Oi[119]=[Xi,Wx];function zI(e,n,s){const a=this;let r,o;return l;function l(h){return!yu(h)||!Yx.call(a,a.previous)||hm(a.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return yu(h)?(e.consume(h),c):h===64?(e.consume(h),d):s(h)}function d(h){return h===46?e.check(OI,m,u)(h):h===45||h===95||zs(h)?(o=!0,e.consume(h),d):m(h)}function u(h){return e.consume(h),r=!0,d}function m(h){return o&&r&&Vs(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function BI(e,n,s){const a=this;return r;function r(l){return l!==87&&l!==119||!Gx.call(a,a.previous)||hm(a.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(LI,e.attempt(Hx,e.attempt(qx,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function UI(e,n,s){const a=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Jx.call(a,a.previous)&&!hm(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(Vs(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const f=r.toLowerCase();if(f==="http"||f==="https")return e.consume(h),d}return s(h)}function d(h){return h===47?(e.consume(h),o?u:(o=!0,d)):s(h)}function u(h){return h===null||Jl(h)||Bn(h)||za(h)||wc(h)?s(h):e.attempt(Hx,e.attempt(qx,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function HI(e,n,s){let a=0;return r;function r(l){return(l===87||l===119)&&a<3?(a++,e.consume(l),r):l===46&&a===3?(e.consume(l),o):s(l)}function o(l){return l===null?s(l):n(l)}}function qI(e,n,s){let a,r,o;return l;function l(u){return u===46||u===95?e.check(Vx,d,c)(u):u===null||Bn(u)||za(u)||u!==45&&wc(u)?d(u):(o=!0,e.consume(u),l)}function c(u){return u===95?a=!0:(r=a,a=void 0),e.consume(u),l}function d(u){return r||a||!o?s(u):n(u)}}function VI(e,n){let s=0,a=0;return r;function r(l){return l===40?(s++,e.consume(l),r):l===41&&a<s?o(l):l===33||l===34||l===38||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===60||l===63||l===93||l===95||l===126?e.check(Vx,n,o)(l):l===null||Bn(l)||za(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&a++,e.consume(l),r}}function WI(e,n,s){return a;function a(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),a):c===38?(e.consume(c),o):c===93?(e.consume(c),r):c===60||c===null||Bn(c)||za(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||Bn(c)||za(c)?n(c):a(c)}function o(c){return Vs(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),a):Vs(c)?(e.consume(c),l):s(c)}}function KI(e,n,s){return a;function a(o){return e.consume(o),r}function r(o){return zs(o)?s(o):n(o)}}function Gx(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Bn(e)}function Jx(e){return!Vs(e)}function Yx(e){return!(e===47||yu(e))}function yu(e){return e===43||e===45||e===46||e===95||zs(e)}function hm(e){let n=e.length,s=!1;for(;n--;){const a=e[n][1];if((a.type==="labelLink"||a.type==="labelImage")&&!a._balanced){s=!0;break}if(a._gfmAutolinkLiteralWalkedInto){s=!1;break}}return e.length>0&&!s&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),s}const GI={tokenize:nT,partial:!0};function JI(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:ZI,continuation:{tokenize:eT},exit:tT}},text:{91:{name:"gfmFootnoteCall",tokenize:XI},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:YI,resolveTo:QI}}}}function YI(e,n,s){const a=this;let r=a.events.length;const o=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let l;for(;r--;){const d=a.events[r][1];if(d.type==="labelImage"){l=d;break}if(d.type==="gfmFootnoteCall"||d.type==="labelLink"||d.type==="label"||d.type==="image"||d.type==="link")break}return c;function c(d){if(!l||!l._balanced)return s(d);const u=yi(a.sliceSerialize({start:l.end,end:a.now()}));return u.codePointAt(0)!==94||!o.includes(u.slice(1))?s(d):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),n(d))}}function QI(e,n){let s=e.length;for(;s--;)if(e[s][1].type==="labelImage"&&e[s][0]==="enter"){e[s][1];break}e[s+1][1].type="data",e[s+3][1].type="gfmFootnoteCallLabelMarker";const a={type:"gfmFootnoteCall",start:Object.assign({},e[s+3][1].start),end:Object.assign({},e[e.length-1][1].end)},r={type:"gfmFootnoteCallMarker",start:Object.assign({},e[s+3][1].end),end:Object.assign({},e[s+3][1].end)};r.end.column++,r.end.offset++,r.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},r.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},c=[e[s+1],e[s+2],["enter",a,n],e[s+3],e[s+4],["enter",r,n],["exit",r,n],["enter",o,n],["enter",l,n],["exit",l,n],["exit",o,n],e[e.length-2],e[e.length-1],["exit",a,n]];return e.splice(s,e.length-s+1,...c),e}function XI(e,n,s){const a=this,r=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let o=0,l;return c;function c(h){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),d}function d(h){return h!==94?s(h):(e.enter("gfmFootnoteCallMarker"),e.consume(h),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(h){if(o>999||h===93&&!l||h===null||h===91||Bn(h))return s(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return r.includes(yi(a.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return Bn(h)||(l=!0),o++,e.consume(h),h===92?m:u}function m(h){return h===91||h===92||h===93?(e.consume(h),o++,u):u(h)}}function ZI(e,n,s){const a=this,r=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let o,l=0,c;return d;function d(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):s(g)}function m(g){if(l>999||g===93&&!c||g===null||g===91||Bn(g))return s(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return o=yi(a.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return Bn(g)||(c=!0),l++,e.consume(g),g===92?h:m}function h(g){return g===91||g===92||g===93?(e.consume(g),l++,m):m(g)}function f(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),r.includes(o)||r.push(o),Cn(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function eT(e,n,s){return e.check(Go,n,e.attempt(GI,n,s))}function tT(e){e.exit("gfmFootnoteDefinition")}function nT(e,n,s){const a=this;return Cn(e,r,"gfmFootnoteDefinitionIndent",5);function r(o){const l=a.events[a.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?n(o):s(o)}}function sT(e){let s=(e||{}).singleTilde;const a={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:a},insideSpan:{null:[a]},attentionMarkers:{null:[126]}};function r(l,c){let d=-1;for(;++d<l.length;)if(l[d][0]==="enter"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._close){let u=d;for(;u--;)if(l[u][0]==="exit"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._open&&l[d][1].end.offset-l[d][1].start.offset===l[u][1].end.offset-l[u][1].start.offset){l[d][1].type="strikethroughSequence",l[u][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[u][1].start),end:Object.assign({},l[d][1].end)},h={type:"strikethroughText",start:Object.assign({},l[u][1].end),end:Object.assign({},l[d][1].start)},f=[["enter",m,c],["enter",l[u][1],c],["exit",l[u][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&ii(f,f.length,0,kc(p,l.slice(u+1,d),c)),ii(f,f.length,0,[["exit",h,c],["enter",l[d][1],c],["exit",l[d][1],c],["exit",m,c]]),ii(l,u-1,d-u+3,f),d=u+f.length-2;break}}for(d=-1;++d<l.length;)l[d][1].type==="strikethroughSequenceTemporary"&&(l[d][1].type="data");return l}function o(l,c,d){const u=this.previous,m=this.events;let h=0;return f;function f(g){return u===126&&m[m.length-1][1].type!=="characterEscape"?d(g):(l.enter("strikethroughSequenceTemporary"),p(g))}function p(g){const x=Sr(u);if(g===126)return h>1?d(g):(l.consume(g),h++,p);if(h<2&&!s)return d(g);const w=l.exit("strikethroughSequenceTemporary"),b=Sr(g);return w._open=!b||b===2&&!!x,w._close=!x||x===2&&!!b,c(g)}}}class iT{constructor(){this.map=[]}add(n,s,a){aT(this,n,s,a)}consume(n){if(this.map.sort(function(o,l){return o[0]-l[0]}),this.map.length===0)return;let s=this.map.length;const a=[];for(;s>0;)s-=1,a.push(n.slice(this.map[s][0]+this.map[s][1]),this.map[s][2]),n.length=this.map[s][0];a.push(n.slice()),n.length=0;let r=a.pop();for(;r;){for(const o of r)n.push(o);r=a.pop()}this.map.length=0}}function aT(e,n,s,a){let r=0;if(!(s===0&&a.length===0)){for(;r<e.map.length;){if(e.map[r][0]===n){e.map[r][1]+=s,e.map[r][2].push(...a);return}r+=1}e.map.push([n,s,a])}}function rT(e,n){let s=!1;const a=[];for(;n<e.length;){const r=e[n];if(s){if(r[0]==="enter")r[1].type==="tableContent"&&a.push(e[n+1][1].type==="tableDelimiterMarker"?"left":"none");else if(r[1].type==="tableContent"){if(e[n-1][1].type==="tableDelimiterMarker"){const o=a.length-1;a[o]=a[o]==="left"?"center":"right"}}else if(r[1].type==="tableDelimiterRow")break}else r[0]==="enter"&&r[1].type==="tableDelimiterRow"&&(s=!0);n+=1}return a}function oT(){return{flow:{null:{name:"table",tokenize:lT,resolveAll:cT}}}}function lT(e,n,s){const a=this;let r=0,o=0,l;return c;function c(_){let M=a.events.length-1;for(;M>-1;){const R=a.events[M][1].type;if(R==="lineEnding"||R==="linePrefix")M--;else break}const z=M>-1?a.events[M][1].type:null,U=z==="tableHead"||z==="tableRow"?v:d;return U===v&&a.parser.lazy[a.now().line]?s(_):U(_)}function d(_){return e.enter("tableHead"),e.enter("tableRow"),u(_)}function u(_){return _===124||(l=!0,o+=1),m(_)}function m(_){return _===null?s(_):en(_)?o>1?(o=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),p):s(_):vn(_)?Cn(e,m,"whitespace")(_):(o+=1,l&&(l=!1,r+=1),_===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(_)))}function h(_){return _===null||_===124||Bn(_)?(e.exit("data"),m(_)):(e.consume(_),_===92?f:h)}function f(_){return _===92||_===124?(e.consume(_),h):h(_)}function p(_){return a.interrupt=!1,a.parser.lazy[a.now().line]?s(_):(e.enter("tableDelimiterRow"),l=!1,vn(_)?Cn(e,g,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(_):g(_))}function g(_){return _===45||_===58?w(_):_===124?(l=!0,e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),x):C(_)}function x(_){return vn(_)?Cn(e,w,"whitespace")(_):w(_)}function w(_){return _===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),b):_===45?(o+=1,b(_)):_===null||en(_)?j(_):C(_)}function b(_){return _===45?(e.enter("tableDelimiterFiller"),y(_)):C(_)}function y(_){return _===45?(e.consume(_),y):_===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),S):(e.exit("tableDelimiterFiller"),S(_))}function S(_){return vn(_)?Cn(e,j,"whitespace")(_):j(_)}function j(_){return _===124?g(_):_===null||en(_)?!l||r!==o?C(_):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(_)):C(_)}function C(_){return s(_)}function v(_){return e.enter("tableRow"),N(_)}function N(_){return _===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),N):_===null||en(_)?(e.exit("tableRow"),n(_)):vn(_)?Cn(e,N,"whitespace")(_):(e.enter("data"),I(_))}function I(_){return _===null||_===124||Bn(_)?(e.exit("data"),N(_)):(e.consume(_),_===92?F:I)}function F(_){return _===92||_===124?(e.consume(_),I):I(_)}}function cT(e,n){let s=-1,a=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,d=0,u,m,h;const f=new iT;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,d!==0&&(Ip(f,n,d,u,m),m=void 0,d=0),u={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",u,n]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(a=!0,h=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",m,n]])),r=g.type==="tableDelimiterRow"?2:m?3:1):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(a=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=cl(f,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):g.type==="tableCellDivider"&&(a?a=!1:(o[1]!==0&&(l[0]=l[1],h=cl(f,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):g.type==="tableHead"?(c=!0,d=s):g.type==="tableRow"||g.type==="tableDelimiterRow"?(d=s,o[1]!==0?(l[0]=l[1],h=cl(f,n,o,r,s,h)):l[1]!==0&&(h=cl(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(d!==0&&Ip(f,n,d,u,m),f.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=rT(n.events,s))}return e}function cl(e,n,s,a,r,o){const l=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},mr(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const d=mr(n.events,s[1]);if(o={type:l,start:Object.assign({},d),end:Object.assign({},d)},e.add(s[1],0,[["enter",o,n]]),s[2]!==0){const u=mr(n.events,s[2]),m=mr(n.events,s[3]),h={type:c,start:Object.assign({},u),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,n]]),a!==2){const f=n.events[s[2]],p=n.events[s[3]];if(f[1].end=Object.assign({},p[1].end),f[1].type="chunkText",f[1].contentType="text",s[3]>s[2]+1){const g=s[2]+1,x=s[3]-s[2]-1;e.add(g,x,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},mr(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Ip(e,n,s,a,r){const o=[],l=mr(n.events,s);r&&(r.end=Object.assign({},l),o.push(["exit",r,n])),a.end=Object.assign({},l),o.push(["exit",a,n]),e.add(s+1,0,o)}function mr(e,n){const s=e[n],a=s[0]==="enter"?"start":"end";return s[1][a]}const dT={name:"tasklistCheck",tokenize:mT};function uT(){return{text:{91:dT}}}function mT(e,n,s){const a=this;return r;function r(d){return a.previous!==null||!a._gfmTasklistFirstContentOfListItem?s(d):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),o)}function o(d){return Bn(d)?(e.enter("taskListCheckValueUnchecked"),e.consume(d),e.exit("taskListCheckValueUnchecked"),l):d===88||d===120?(e.enter("taskListCheckValueChecked"),e.consume(d),e.exit("taskListCheckValueChecked"),l):s(d)}function l(d){return d===93?(e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):s(d)}function c(d){return en(d)?n(d):vn(d)?e.check({tokenize:hT},n,s)(d):s(d)}}function hT(e,n,s){return Cn(e,a,"whitespace");function a(r){return r===null?s(r):n(r)}}function pT(e){return ox([FI(),JI(),sT(e),oT(),uT()])}const fT={};function ji(e){const n=this,s=e||fT,a=n.data(),r=a.micromarkExtensions||(a.micromarkExtensions=[]),o=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),l=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);r.push(pT(s)),o.push($I()),l.push(DI(s))}const gT=45e3,bT=3e3,xT=2e3,vT=1500,Tp="fusion:sse-client-id";let rr=null;const ca=new Map;function Pp(){const e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function Qx(){if(!(typeof window>"u")){if(rr)return rr;try{const e=window.sessionStorage.getItem(Tp);if(e)return rr=e,e;const n=Pp();return window.sessionStorage.setItem(Tp,n),rr=n,n}catch{return rr=Pp(),rr}}}function Xx(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Zx(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function yT(e){const n=Qx();if(!n)return e;const s=Xx(e);return!s||!Zx(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function pm(e,n){const s=Qx();if(!s)return;const a=Xx(e);if(!a||!Zx(a.parsed))return;const r=new URL(`/api/events/${n}`,window.location.origin);r.searchParams.set("clientId",s);const o=a.parsed.searchParams.get("projectId");return o&&r.searchParams.set("projectId",o),Di(`${r.pathname}${r.search}${r.hash}`)}function wT(e){if(typeof window>"u")return;const n=pm(e.url,"disconnect");if(!n)return;const s=window.navigator?.sendBeacon?.bind(window.navigator);s&&s(n)||typeof window.fetch=="function"&&window.fetch(n,{method:"POST",keepalive:!0}).catch(()=>{})}function Cc(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function $p(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=pm(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,a=s?window.setTimeout(()=>s.abort(),vT):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{a!==null&&window.clearTimeout(a)})}function kT(e){Cc(e),pm(e.url,"keepalive")&&($p(e),e.keepaliveTimer=window.setInterval(()=>{$p(e)},xT))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(ca.values()))if(!s.closed){if(Cc(s),wT(s),s.es){try{s.es.close()}catch{}s.es=null}s.closed=!0}},n=s=>{if(s.persisted)for(const a of Array.from(ca.values()))a.subscribers.size!==0&&(a.closed=!1,fm(a))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function po(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{ev(e)},gT)}function ev(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Cc(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=ca.get(e.url);if(!(!n||n!==e)){for(const s of e.subscribers)s.onReconnect?.();e.reconnectTimer=setTimeout(()=>{if(e.reconnectTimer=null,e.closed)return;const s=ca.get(e.url);s&&s===e&&e.subscribers.size>0&&fm(e)},bT)}}function fm(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(Di(yT(e.url)));e.es=n,kT(e),n.addEventListener("open",()=>{po(e);const s=e.hasOpenedOnce;e.hasOpenedOnce=!0;for(const a of e.subscribers)a.onOpen?.(),s&&a.onReconnect?.()}),n.addEventListener("error",s=>{for(const a of e.subscribers)a.onError?.(s);ev(e)}),n.addEventListener("message",()=>po(e)),n.addEventListener("heartbeat",()=>po(e)),tv(e),po(e)}function tv(e){if(!e.es)return;const n=new Set;for(const s of e.subscribers)for(const a of s.events.keys())n.add(a);for(const s of n){if(e.nativeListeners.has(s))continue;const a=r=>{po(e);const o=r;for(const l of e.subscribers){const c=l.events.get(s);if(c)for(const d of c)d(o)}};e.nativeListeners.set(s,a),e.es.addEventListener(s,a)}}function jT(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Cc(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),ca.delete(e.url)}function hi(e,n={}){let s=ca.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},ca.set(e,s));const a={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[l,c]of Object.entries(n.events)){let d=a.events.get(l);d||(d=new Set,a.events.set(l,d)),d.add(c)}s.subscribers.add(a);const r=!!s.es&&s.hasOpenedOnce;fm(s),tv(s),r&&queueMicrotask(()=>{s.subscribers.has(a)&&a.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=ca.get(e);l&&(l.subscribers.delete(a),l.subscribers.size===0&&jT(l))}}const Dp=100;function nv(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[u,m]=i.useState(null),[h,f]=i.useState(!1),p=i.useRef(null),g=i.useRef(!1),x=i.useRef(0),w=i.useRef(e),b=i.useRef(s),y=i.useRef(n),S=i.useRef(0);(w.current!==e||b.current!==s||y.current!==n)&&(w.current=e,b.current=s,y.current=n,x.current++,g.current=!0,r([]),l(!1),d(!1),m(null),f(!1),p.current&&(p.current(),p.current=null)),i.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const N=x.current,I=++S.current;g.current=!1;const F=e,_=s;async function M(){if(!F)return;l(!0),f(!1);try{const U=await Om(F,_,{limit:Dp});if(g.current||x.current!==N||S.current!==I)return;r(U.entries),d(U.hasMore),m(U.total)}catch{if(g.current||x.current!==N||S.current!==I)return;r([]),d(!1),m(null)}finally{!g.current&&x.current===N&&S.current===I&&l(!1)}const z=_?`?projectId=${encodeURIComponent(_)}`:"";p.current=hi(`/api/tasks/${F}/logs/stream${z}`,{events:{"agent:log":U=>{if(!(g.current||x.current!==N))try{const R=JSON.parse(U.data);r(D=>[...D,R]),m(D=>D!==null?D+1:null)}catch{}}}})}return M(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const C=i.useCallback(async()=>{if(!e||h)return;const N=x.current,I=a.length,F=e;f(!0);try{const _=await Om(F,s,{limit:Dp,offset:I});if(g.current||x.current!==N)return;r(M=>[..._.entries,...M]),d(_.hasMore),m(_.total)}catch{}finally{f(!1)}},[e,s,a.length,h]),v=i.useCallback(()=>r([]),[]);return{entries:a,loading:o,clear:v,loadMore:C,hasMore:c,total:u,loadingMore:h}}const Lp="fn-agent-log-markdown",Op="fn-agent-log-tool-output";function Fp(e,n){if(typeof window>"u")return n;try{const s=window.localStorage.getItem(e);return s===null?n:s==="true"}catch{return n}}function zp(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n?"true":"false")}catch{}}function NT(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}const Bp={pre:({children:e,...n})=>t.jsx("pre",{...n,style:{overflowX:"auto",maxWidth:"100%",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:e}),table:({children:e,...n})=>t.jsx("table",{...n,style:{display:"block",overflowX:"auto",maxWidth:"100%"},children:e})},sv=50,ST={triage:"Plan"};function Up(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=sv}function wu(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function CT(e){const n=new Map;return e.map(s=>{const a=wu(s),r=n.get(a)??0;return n.set(a,r+1),`${a}|${r}`})}function iv(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function pd({detail:e}){const[n,s]=i.useState(!1),a=i.useId(),r=e.split(`
680
+ `).length,o=n?"Hide output":`Show output${r>1?` (${r} lines)`:""}`;return t.jsxs("div",{className:"agent-log-tool-detail-wrapper",children:[t.jsxs("button",{type:"button",className:"agent-log-tool-detail-toggle",onClick:()=>s(l=>!l),"aria-expanded":n,"aria-controls":a,"data-testid":"tool-detail-toggle",children:[n?t.jsx(pn,{size:14}):t.jsx(On,{size:14}),t.jsx("span",{children:o})]}),t.jsx("div",{id:a,className:n?"agent-log-tool-detail-content":"agent-log-tool-detail-content agent-log-tool-detail-content--collapsed","data-testid":"tool-detail-content",children:t.jsx("pre",{className:"agent-log-tool-detail",children:e})})]})}function ET(e,n){return e.agent?iv(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function _T(e,n){const s=[];for(let a=0;a<e.length;a+=1){const{entry:r,hiddenToolBoundaryId:o}=e[a],l=n[a]??`${wu(r)}|fallback`,c=a>0?e[a-1]:void 0,d=c?.entry,u=ET(r,d)||c!==void 0&&c.hiddenToolBoundaryId!==o;if(r.type==="text"||r.type==="thinking"){const m=[r];let h=a+1;for(;h<e.length;){const p=e[h],g=p.entry;if(g.type!==r.type||g.agent!==r.agent||p.hiddenToolBoundaryId!==o)break;m.push(g),h+=1}const f=n[h-1]??`${wu(e[h-1].entry)}|fallback`;s.push({kind:r.type,entries:m,key:`${l}->${f}`,showBadge:u}),a=h-1;continue}s.push({kind:"single",entry:r,key:l,showBadge:u})}return s}function MT({entries:e,loading:n,executorModel:s,validatorModel:a,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:d=null}){const u=i.useRef(null),m=i.useRef(0),h=i.useRef(0),f=i.useRef(null),p=i.useRef(null),[g,x]=i.useState(()=>Fp(Lp,!0)),[w,b]=i.useState(()=>Fp(Op,!0)),[y,S]=i.useState(!1),[j,C]=i.useState(!1),[v,N]=i.useState(!0);i.useEffect(()=>{zp(Lp,g)},[g]),i.useEffect(()=>{zp(Op,w)},[w]);const I=i.useMemo(()=>{if(w)return e.map(P=>({entry:P,hiddenToolBoundaryId:0}));const O=[];let A=0;for(const P of e){if(iv(P.type)){A+=1;continue}O.push({entry:P,hiddenToolBoundaryId:A})}return O},[e,w]),F=i.useMemo(()=>I.map(O=>O.entry),[I]),_=i.useMemo(()=>CT(F),[F]),M=i.useMemo(()=>_T(I,_),[I,_]);i.useLayoutEffect(()=>{const O=u.current;if(!O)return;const A=e.length,P=m.current,$=h.current||O.scrollHeight,k=_[0]??null,J=_[_.length-1]??null,ce=f.current!==k,je=p.current!==J;if(A>P)if(P===0)O.scrollTop=O.scrollHeight;else{const He=$-(O.scrollTop+O.clientHeight)<=sv,xe=je&&!ce,Ne=ce&&!je;if(xe&&He&&(O.scrollTop=O.scrollHeight),Ne){const Y=O.scrollHeight-$;Y>0&&(O.scrollTop+=Y)}}m.current=A,h.current=O.scrollHeight,f.current=k,p.current=J,N(Up(O))},[e,_]);const z=i.useCallback(()=>{const O=u.current;O&&N(Up(O))},[]),U=i.useCallback(()=>{const O=u.current;O&&(O.scrollTop=O.scrollHeight,N(!0))},[]),R=i.useCallback(O=>{O.key==="Escape"&&y&&S(!1)},[y]);i.useEffect(()=>{if(y)return document.addEventListener("keydown",R),()=>{document.removeEventListener("keydown",R)}},[y,R]);const D=s?.provider&&s?.modelId,K=a?.provider&&a?.modelId,Z=r?.provider&&r?.modelId,ne=i.useMemo(()=>{const O=[];return D&&O.push({role:"Executor",provider:s.provider,modelId:s.modelId}),K&&O.push({role:"Reviewer",provider:a.provider,modelId:a.modelId}),Z&&O.push({role:"Planning",provider:r.provider,modelId:r.modelId}),O},[D,s,K,a,Z,r]);return n&&e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})}):e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-empty",children:"No agent output yet."})}):t.jsxs("div",{className:`agent-log-viewer agent-log-viewer--streaming${y?" agent-log-viewer--fullscreen":""}`,"data-testid":"agent-log-viewer",children:[t.jsxs("div",{className:"agent-log-model-header","data-testid":"agent-log-model-header",children:[t.jsxs("div",{className:"agent-log-model-icons",children:[ne.map(O=>t.jsx(Fn,{provider:O.provider,size:"sm"},`${O.role}-${O.provider}-${O.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>C(O=>!O),"aria-label":j?"Collapse model details":"Expand model details","aria-expanded":j,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:j?t.jsx(pn,{size:14}):t.jsx(On,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(O=>!O),"aria-label":g?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":g,"data-testid":"agent-log-mode-toggle",title:g?"Show raw text":"Show formatted markdown",children:g?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b(O=>!O),"aria-label":w?"Hide tool output":"Show tool output","aria-pressed":w,"data-testid":"agent-log-tool-output-toggle",title:w?"Hide tool calls and results":"Show tool calls and results",children:w?"Tools: On":"Tools: Off"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>S(O=>!O),"aria-label":y?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:y?"Exit full screen":"Expand agent log to full screen",children:y?t.jsx(Lo,{size:14}):t.jsx(fc,{size:14})})]}),j&&t.jsxs("div",{id:"agent-log-model-details",className:"agent-log-model-details",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),D?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Fn,{provider:s.provider,size:"sm"}),t.jsxs("span",{children:[s.provider,"/",s.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Reviewer:"}),K?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Fn,{provider:a.provider,size:"sm"}),t.jsxs("span",{children:[a.provider,"/",a.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Planning:"}),Z?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Fn,{provider:r.provider,size:"sm"}),t.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]})]})]}),t.jsxs("div",{ref:u,className:"agent-log-viewer-scroll",onScroll:z,children:[d!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",F.length," of ",d," entries",!w&&e.length!==F.length?` (${e.length-F.length} tool entries hidden)`:""]}),o&&l&&t.jsx("div",{className:"agent-log-load-more","data-testid":"agent-log-load-more",children:t.jsx("button",{className:"agent-log-mode-toggle",onClick:l,disabled:c,"data-testid":"agent-log-load-more-button",children:c?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),M.map(O=>{const A=O.kind==="single"?O.entry:O.entries[0],P=O.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:NT(A.timestamp)}):null,$=O.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",ST[A.agent]??A.agent,"]"]}),P]}):null;if(O.kind==="single"){const{entry:J}=O;if(J.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",J.text]}),J.detail?t.jsx(pd,{detail:J.detail,type:"tool"}):null]},O.key);if(J.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",J.text]}),J.detail?t.jsx(pd,{detail:J.detail,type:"tool_result"}):null]},O.key);if(J.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",J.text]}),J.detail?t.jsx(pd,{detail:J.detail,type:"tool_error"}):null]},O.key)}const k=O.kind==="single"?A.text:O.entries.map(J=>J.text).join("");return O.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[$,g?t.jsx("div",{className:"markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],components:Bp,children:k})}):t.jsx("pre",{className:"agent-log-plain-block",children:k})]},O.key):t.jsxs("div",{className:"agent-log-text",children:[$,g?t.jsx("div",{className:"markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],components:Bp,children:k})}):t.jsx("pre",{className:"agent-log-plain-block",children:k})]},O.key)}),!v&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:U,"data-testid":"agent-log-return-to-live",children:[t.jsx(pn,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function Cr(e){return e??void 0}function dl(e){return{provider:Cr(e.modelProvider),modelId:Cr(e.modelId)}}function ul(e){return{provider:Cr(e.validatorModelProvider),modelId:Cr(e.validatorModelId)}}function ml(e){return{provider:Cr(e.planningModelProvider),modelId:Cr(e.planningModelId)}}function AT(e,n){return Eb(e,n)}function RT(e,n){return _b(e,n)}function IT(e,n){return Mb(e,n)}function fd(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return{provider:e.slice(0,n),modelId:e.slice(n+1)}}function gd(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function bd(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function TT(e,n){const a={executor:"Executor",validator:"Reviewer",planning:"Planning"}[e]||e;return!n.provider||!n.modelId?`${a} model set to default`:`${a} model set to ${n.provider}/${n.modelId}`}function PT({task:e,addToast:n,onTaskUpdated:s,settings:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState([]),[m,h]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(()=>dl(e)),[w,b]=i.useState(()=>dl(e)),[y,S]=i.useState(()=>ul(e)),[j,C]=i.useState(()=>ul(e)),[v,N]=i.useState(()=>ml(e)),[I,F]=i.useState(()=>ml(e)),[_,M]=i.useState(()=>e.thinkingLevel??null),[z,U]=i.useState(()=>e.thinkingLevel??null),[R,D]=i.useState(null),K=i.useRef(e.id);i.useEffect(()=>{h(!0),p(null),Ks().then(W=>{o(W.models),c(W.favoriteProviders),u(W.favoriteModels)}).catch(W=>{p(W.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const Z=i.useCallback(async W=>{const L=l,fe=L.includes(W)?L.filter(B=>B!==W):[W,...L];c(fe);try{await Dn({favoriteProviders:fe,favoriteModels:d})}catch{c(L),n("Failed to update favorites","error")}},[l,d,n]),ne=i.useCallback(async W=>{const L=d,fe=L.includes(W)?L.filter(B=>B!==W):[W,...L];u(fe);try{await Dn({favoriteProviders:l,favoriteModels:fe})}catch{u(L),n("Failed to update model favorites","error")}},[d,l,n]);i.useEffect(()=>{K.current=e.id;const W=dl(e),L=ul(e),pe=ml(e);x(W),b(W),S(L),C(L),N(pe),F(pe);const fe=e.thinkingLevel??null;M(fe),U(fe),D(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const O=i.useMemo(()=>gd(g),[g]),A=i.useMemo(()=>gd(y),[y]),P=i.useMemo(()=>gd(v),[v]),$=i.useMemo(()=>AT(e,a),[e,a]),k=i.useMemo(()=>RT(e,a),[e,a]),J=i.useMemo(()=>IT(e,a),[e,a]),ce=R!==null,je=i.useCallback(async(W,L)=>{const pe=e.id,fe=w,B=j,ve=I;D(W);try{const Fe=s?W==="executor"?{modelProvider:L.provider??null,modelId:L.modelId??null}:W==="validator"?{validatorModelProvider:L.provider??null,validatorModelId:L.modelId??null}:{planningModelProvider:L.provider??null,planningModelId:L.modelId??null}:{modelProvider:(W==="executor"?L:w).provider??null,modelId:(W==="executor"?L:w).modelId??null,validatorModelProvider:(W==="validator"?L:j).provider??null,validatorModelId:(W==="validator"?L:j).modelId??null,planningModelProvider:(W==="planning"?L:I).provider??null,planningModelId:(W==="planning"?L:I).modelId??null},ae=await Hs(pe,Fe);if(K.current!==pe)return;const qe=dl(ae),Pe=ul(ae),nt=ml(ae);b(qe),x(qe),C(Pe),S(Pe),F(nt),N(nt),s?.(ae),n(TT(W,{executor:qe,validator:Pe,planning:nt}[W]),"success")}catch(Fe){if(K.current!==pe)return;W==="executor"?x(fe):W==="validator"?S(B):N(ve),n(Ee(Fe)||"Failed to save model settings","error")}finally{K.current===pe&&D(null)}},[e.id,w,j,I,n,s]),He=i.useCallback(W=>{const L=fd(W);x(L),!bd(L,w)&&je("executor",L)},[w,je]),xe=i.useCallback(W=>{const L=fd(W);S(L),!bd(L,j)&&je("validator",L)},[j,je]),Ne=i.useCallback(W=>{const L=fd(W);N(L),!bd(L,I)&&je("planning",L)},[I,je]),Y=i.useCallback(async W=>{const L=e.id,pe=z,fe=W===""?null:W;M(fe),D("thinking");try{const B=await Hs(L,{thinkingLevel:fe});if(K.current!==L)return;const ve=B.thinkingLevel??null;U(ve),M(ve),s?.(B);const Fe=a?.defaultThinkingLevel??"off";n(ve===null?`Thinking level set to default (${Fe})`:`Thinking level set to ${ve}`,"success")}catch(B){if(K.current!==L)return;M(pe),n(Ee(B)||"Failed to save thinking level","error")}finally{K.current===L&&D(null)}},[e.id,z,a,n,s]),ie=!w.provider&&!w.modelId,ee=!j.provider&&!j.modelId,oe=!I.provider&&!I.modelId;return t.jsxs("div",{className:"model-selector-tab",children:[t.jsx("h4",{children:"Model Configuration"}),t.jsx("p",{className:"model-selector-intro",children:"Override the AI models used for this task. When not specified, project or global defaults are used."}),m?t.jsx("div",{className:"model-selector-loading",children:"Loading available models…"}):f?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",f,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),Ks().then(W=>{o(W.models),c(W.favoriteProviders),u(W.favoriteModels)}).catch(W=>p(W.message)).finally(()=>h(!1))},style:{marginLeft:"8px"},children:"Retry"})]}):r.length===0?t.jsx("div",{className:"model-selector-empty",children:"No models available. Configure authentication in Settings to enable model selection."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"executorModel",children:"Executor Model"}),t.jsx("div",{className:"model-selector-current",children:ie?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",$.provider&&$.modelId?` (${$.provider}/${$.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[w.provider&&t.jsx(Fn,{provider:w.provider,size:"sm"}),w.provider,"/",w.modelId]})}),t.jsx(Is,{id:"executorModel",label:"Executor Model",value:O,onChange:He,models:r,disabled:ce,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:Z,favoriteModels:d,onToggleModelFavorite:ne}),t.jsx("small",{children:"The AI model used to implement this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"validatorModel",children:"Reviewer Model"}),t.jsx("div",{className:"model-selector-current",children:ee?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",k.provider&&k.modelId?` (${k.provider}/${k.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[j.provider&&t.jsx(Fn,{provider:j.provider,size:"sm"}),j.provider,"/",j.modelId]})}),t.jsx(Is,{id:"validatorModel",label:"Reviewer Model",value:A,onChange:xe,models:r,disabled:ce,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:Z,favoriteModels:d,onToggleModelFavorite:ne}),t.jsx("small",{children:"The AI model used to review code and plans for this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planningModel",children:"Planning Model"}),t.jsx("div",{className:"model-selector-current",children:oe?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",J.provider&&J.modelId?` (${J.provider}/${J.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[I.provider&&t.jsx(Fn,{provider:I.provider,size:"sm"}),I.provider,"/",I.modelId]})}),t.jsx(Is,{id:"planningModel",label:"Planning Model",value:P,onChange:Ne,models:r,disabled:ce,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:Z,favoriteModels:d,onToggleModelFavorite:ne}),t.jsx("small",{children:"The AI model used for task specification (triage phase)."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"thinkingLevel",children:"Thinking Level"}),t.jsx("div",{className:"model-selector-current",children:z===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",a?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:z})}),t.jsxs("select",{id:"thinkingLevel",value:_??"",onChange:W=>Y(W.target.value),disabled:ce,className:"thinking-level-select",children:[t.jsxs("option",{value:"",children:["Default (",a?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]}),t.jsx("small",{children:"Controls the reasoning effort for the AI agent. Higher levels use more tokens."})]}),t.jsx("div",{className:"model-selector-status",children:ie&&ee&&oe&&z===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const $T={open:t.jsx(cc,{size:16}),closed:t.jsx(Do,{size:16}),merged:t.jsx(Yg,{size:16})};function DT({taskId:e,projectId:n,prInfo:s,automationStatus:a,autoMerge:r=!1,isManualPrFlow:o=!1,prAuthAvailable:l,onPrCreated:c,onPrUpdated:d,addToast:u}){const[m,h]=i.useState(!1),[f,p]=i.useState(""),[g,x]=i.useState(""),[w,b]=i.useState(!1),[y,S]=i.useState(!1),[j,C]=i.useState(null),v=i.useCallback(async()=>{if(f.trim()){b(!0);try{const _=await AN(e,{title:f.trim(),body:g.trim()||void 0},n);c(_),h(!1),p(""),x(""),u(`Created PR #${_.number}`,"success")}catch(_){u(Ee(_)||"Failed to create PR","error")}finally{b(!1)}}},[e,f,g,n,c,u]),N=i.useCallback(async()=>{if(s){S(!0);try{const _=await RN(e,n);C(_),d(_.prInfo),u("PR status refreshed","success")}catch(_){u(Ee(_)||"Failed to refresh PR","error")}finally{S(!1)}}},[e,s,n,d,u]);if(!s)return a==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(si,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"fn is creating a pull request automatically for this task."})]}):r?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(si,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"Auto-merge will handle this task automatically."})]}):m?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(si,{size:16,className:"pr-section-icon"}),"Create Pull Request"]}),t.jsxs("div",{className:"pr-form",children:[t.jsx("input",{type:"text",placeholder:"PR title",value:f,onChange:_=>p(_.target.value),disabled:w,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:g,onChange:_=>x(_.target.value),disabled:w,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>h(!1),disabled:w,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:v,disabled:!f.trim()||w,children:w?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(si,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>h(!0),disabled:!l,title:l?"Create a PR for this task":"PR auth unavailable — run 'gh auth login'",children:[t.jsx(Mn,{size:14,className:"pr-section-icon--sm"}),"Create PR"]}),o&&t.jsx("div",{className:"pr-hint pr-hint--subtle",children:"Use the footer action to run PR-first completion for this task."}),!l&&t.jsxs("div",{className:"pr-hint pr-hint--subtle",children:["Run ",t.jsx("code",{children:"gh auth login"})," to enable PR creation."]})]});const I=$T[s.status]??t.jsx(cc,{size:16}),F=j?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(si,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[t.jsxs("div",{className:"pr-header",children:[t.jsx("span",{className:"pr-status-icon",children:I}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:N,disabled:y,title:"Refresh PR status",children:t.jsx(bs,{size:14,style:{verticalAlign:"middle",opacity:y?.5:1}})})]}),t.jsx("div",{className:"pr-title",children:s.title}),t.jsxs("div",{className:"pr-meta",children:[t.jsx("span",{children:s.headBranch}),t.jsx("span",{className:"pr-meta-arrow",children:"→"}),t.jsx("span",{children:s.baseBranch})]}),a==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),a==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:F.length>0?`Waiting for: ${F.join("; ")}`:"Waiting for required checks or review feedback before auto-merge."}),s.status==="merged"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"This PR is merged. fn will finish local cleanup and move the task to Done."}),t.jsxs("div",{className:"pr-footer",children:[s.commentCount>0&&t.jsxs("span",{className:"pr-comments",children:[t.jsx(Ki,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(Kg,{size:14}),"View on GitHub"]})]})]})]})}const Hp=2e3;function LT(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function OT(e){return e==="agent"||e==="system"}function FT({task:e,onTaskUpdated:n,addToast:s,currentAuthor:a="user",projectId:r}){const[o,l]=i.useState(""),[c,d]=i.useState(null),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState(null),x=i.useMemo(()=>[...e.comments||[]].sort((N,I)=>new Date(I.createdAt).getTime()-new Date(N.createdAt).getTime()),[e.comments]),w=o.length>Hp;async function b(){const N=o.trim();if(N){f(!0);try{const I=await Yj(e.id,N,r);l(""),n?.(I),s("Comment added","success")}catch(I){s(Ee(I)||"Failed to add comment","error")}finally{f(!1)}}}async function y(N){const I=u.trim();if(I){f(!0);try{const F=await Vj(e.id,N,I,r);d(null),m(""),n?.(F),s("Comment updated","success")}catch(F){s(Ee(F)||"Failed to update comment","error")}finally{f(!1)}}}async function S(N){g(N);try{const I=await Wj(e.id,N,r);n?.(I),s("Comment deleted","success")}catch(I){s(Ee(I)||"Failed to delete comment","error")}finally{g(null)}}function j(N){N.key==="Enter"&&(N.ctrlKey||N.metaKey)&&(N.preventDefault(),b())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),x.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:x.map(N=>{const I=N.author===a,F=c===N.id,_=OT(N.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[_?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:N.author}),t.jsx("span",{className:"detail-log-timestamp",children:LT(N)})]}),I&&!F?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(N.id),m(N.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void S(N.id),disabled:p===N.id,children:p===N.id?"Deleting…":"Delete"})]}):null]}),F?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:u,onChange:M=>m(M.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(N.id),disabled:h||!u.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:N.text})]},N.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:N=>l(N.target.value),onKeyDown:j,rows:3,placeholder:"Add a comment",className:"comments-textarea"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${w?" comments-char-count--over":""}`,children:[o.length," / ",Hp]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||w,children:h?"Posting…":"Add Comment"})]})]})]})}const qp="Failed to load review data.",zT="No reviewer feedback yet — this task has not produced reviewer-agent feedback in direct mode.";function Zr(e){return e?new Date(e).toLocaleString():"Never"}function BT(e){return e==="manual"?"Manual":e==="auto"?"Background":"Initial load"}function UT(e){const n=new Map(e.addressing.map(o=>[o.itemId,o])),s=e.items.map(o=>{const l=n.get(o.id);return{id:o.id,summary:o.summary??o.body.slice(0,120),body:o.body,path:o.path,createdAt:o.createdAt,status:l?.status??"queued",addressing:l,item:o}}),a=new Set(s.map(o=>o.id)),r=e.addressing.filter(o=>!a.has(o.itemId)&&o.snapshot).map(o=>({id:o.itemId,summary:o.snapshot?.summary??o.itemId,body:o.snapshot?.body??o.snapshot?.summary??o.itemId,path:o.snapshot?.filePath,createdAt:o.selectedAt,status:o.status,addressing:o}));return[...s,...r]}function HT({task:e,projectId:n,onTaskUpdated:s,addToast:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState(!0),[f,p]=i.useState(null),[g,x]=i.useState(null),[w,b]=i.useState(e.reviewState??null),y=r.length>0&&!d,S=w?.source==="pull-request",j=i.useMemo(()=>w?UT(w):[],[w]);i.useEffect(()=>{let z=!1;return h(!0),p(null),QS(e.id,n).then(U=>{z||(b(U.reviewState),x(U.emptyMessage??null))}).catch(()=>{z||p(qp)}).finally(()=>{z||h(!1)}),()=>{z=!0}},[e.id,n]);const C=i.useMemo(()=>w?w.source==="pull-request"?`${w.summary?.reviewDecision??"REVIEW_REQUIRED"} · ${j.length} review item(s)`:`${w.summary?.summary??"reviewer-agent"} · ${j.length} review item(s)`:"No review feedback captured yet.",[w,j.length]),v=w?w.source==="pull-request"?w.summary?.reviewDecision:w.summary?.verdict:void 0,N=l?"refreshing":w?.refreshStatus??"ready",I=N==="error"?"status-dot status-dot--error":N==="refreshing"?"status-dot status-dot--pending":"status-dot status-dot--online",F=z=>o(U=>U.includes(z)?U.filter(R=>R!==z):[...U,z]),_=async()=>{try{p(null),c(!0);const z=await XS(e.id,n);if(b(z.reviewState),s?.({...e,reviewState:z.reviewState,prInfo:z.prInfo??e.prInfo}),z.reviewState.refreshStatus==="error"){const U=z.reviewState.refreshError??"Failed to refresh review data.";p(U),a(U,"error");return}a("Review refreshed","success")}catch(z){const U=z instanceof Error?z.message:qp;p(U),a(U,"error")}finally{c(!1)}},M=async()=>{try{if(!w)return;p(null),u(!0);const z=j.filter(R=>r.includes(R.id)).map(R=>{if(!R.item)return{id:R.id,source:w.source==="pull-request"?"pr-review":"reviewer-agent",threadId:R.addressing?.snapshot?.threadId,filePath:R.addressing?.snapshot?.filePath,lineNumber:R.addressing?.snapshot?.lineNumber,author:R.addressing?.snapshot?.authorLogin,summary:R.summary,body:R.body,url:R.addressing?.snapshot?.url};const D=R.item;return{id:R.item.id,source:w.source==="pull-request"?"pr-review":"reviewer-agent",threadId:typeof D.threadId=="string"?D.threadId:void 0,filePath:R.item.path,lineNumber:typeof D.line=="number"?D.line:void 0,author:R.item.author?.login,summary:R.item.summary??R.item.body.slice(0,120),body:R.item.body,url:typeof D.url=="string"?D.url:void 0}}),U=await ZS(e.id,z,n);b(U.reviewState),s?.({...U.task,reviewState:U.reviewState}),o([]),a("Same-task AI revision started from selected review feedback","success")}catch(z){const U=z instanceof Error?z.message:"Failed to queue revision";p(U),a(U,"error")}finally{u(!1)}};return t.jsxs("div",{className:"task-review-tab",children:[t.jsxs("div",{className:"task-review-tab__header",children:[t.jsxs("div",{className:"task-review-tab__summary-wrap",children:[t.jsx("p",{className:"task-review-tab__summary",children:C}),v?t.jsx("span",{className:`task-review-tab__decision task-review-tab__decision--${v}`,children:v}):null]}),t.jsxs("div",{className:"task-review-tab__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:_,disabled:l||m,children:l?"Refreshing…":"Refresh"}),t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!y,onClick:M,children:d?"Queueing…":"Request revision"})]})]}),t.jsxs("div",{className:"task-review-tab__meta task-review-tab__refresh-meta","aria-live":"polite",children:[t.jsx("span",{className:I,"aria-hidden":"true"}),t.jsxs("span",{children:[N==="error"?"Refresh failed":N==="refreshing"?"Refreshing":"Up to date"," · Last refreshed: ",Zr(w?.lastRefreshedAt)," · ",BT(w?.refreshSource)]})]}),m?t.jsx("div",{className:"task-review-tab__meta",children:"Loading review data…"}):null,!m&&f?t.jsx("div",{className:"task-review-tab__error",children:f}):null,!m&&!f&&!S&&j.length===0?t.jsx("div",{className:"task-review-tab__empty",children:g??zT}):null,!m&&!f&&j.length>0?t.jsx("ul",{className:"task-review-tab__list",children:j.map(z=>t.jsx("li",{className:"task-review-tab__item card",children:t.jsxs("label",{className:"task-review-tab__direct-item task-review-tab__direct-item--selectable",children:[t.jsxs("div",{className:"task-review-tab__summary-wrap",children:[t.jsx("input",{type:"checkbox",checked:r.includes(z.id),onChange:()=>F(z.id)}),t.jsxs("span",{className:"task-review-tab__item-summary",children:[z.path?`${z.path}: `:"",z.summary]}),t.jsx("span",{className:`task-review-tab__status task-review-tab__status--${z.status}`,children:z.status})]}),t.jsx("div",{className:"task-review-tab__meta",children:Zr(z.createdAt)}),z.addressing?t.jsxs("div",{className:"task-review-tab__meta",children:["Selected: ",Zr(z.addressing.selectedAt),z.addressing.startedAt?` · Started: ${Zr(z.addressing.startedAt)}`:"",z.addressing.completedAt?` · Completed: ${Zr(z.addressing.completedAt)}`:"",z.addressing.error?` · Error: ${z.addressing.error}`:""]}):null,t.jsx("pre",{className:"task-review-tab__body",children:z.body})]})},z.id))}):null,S&&!m&&!f&&j.length===0?t.jsx("div",{className:"task-review-tab__empty",children:"No review items yet."}):null]})}function qT(e){return e?e.slice(0,7):"Unknown"}function VT({task:e}){if(e.column!=="done"||!e.mergeDetails)return null;const n=e.mergeDetails;return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Merge Details"}),t.jsxs("div",{className:"pr-card merge-details-card",children:[t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Status"}),t.jsx("span",{className:"detail-log-outcome",children:n.mergeConfirmed===!1?"Recorded without local merge confirmation":"Merged successfully"})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Commit"}),t.jsx("span",{className:"detail-log-outcome",children:qT(n.commitSha)})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Files changed"}),t.jsx("span",{className:"detail-log-outcome",children:n.filesChanged??0})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Insertions / Deletions"}),t.jsxs("span",{className:"detail-log-outcome",children:["+",n.insertions??0," / -",n.deletions??0]})]})}),n.mergedAt?t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Merged at"}),t.jsx("span",{className:"detail-log-outcome",children:new Date(n.mergedAt).toLocaleString()})]})}):null,n.prNumber?t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"PR"}),e.prInfo?.url?t.jsxs("a",{className:"detail-source-link detail-log-outcome",href:e.prInfo.url,target:"_blank",rel:"noopener noreferrer",children:["#",n.prNumber]}):t.jsxs("span",{className:"detail-log-outcome",children:["#",n.prNumber]})]})}):null,n.mergeCommitMessage?t.jsxs("div",{className:"detail-log-entry",children:[t.jsx("div",{className:"detail-log-header",children:t.jsx("span",{className:"detail-log-action",children:"Message"})}),t.jsx("div",{className:"detail-log-outcome",children:n.mergeCommitMessage})]}):null]})]})}function av(e){return e.split(`
681
+ `).map((s,a)=>{let r="";return s.startsWith("+")&&!s.startsWith("+++")?r="diff-add":s.startsWith("-")&&!s.startsWith("---")?r="diff-del":s.startsWith("@@")&&(r="diff-hunk"),r?t.jsx("span",{className:r,children:`${s}
682
+ `},a):t.jsx(Ol.Fragment,{children:`${s}
683
+ `},a)})}function WT(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function KT({isOpen:e,taskId:n,files:s,stats:a,mergeDetails:r,column:o,onClose:l,onRefresh:c}){const[d,u]=i.useState(null),[m,h]=i.useState(!0),f=i.useRef(null);Li(f,e,"fusion:changes-diff-modal-size");const p=Qi(l);i.useEffect(()=>{s.length>0&&d===null&&u(0)},[s,d]);const g=i.useCallback(()=>{u(y=>y!==null&&y>0?y-1:y)},[]),x=i.useCallback(()=>{u(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(i.useEffect(()=>{if(!e)return;const y=S=>{if(S.key==="Escape"){l();return}S.key==="ArrowUp"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),g()),S.key==="ArrowDown"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),x())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,g,x]),!e)return null;const w=d!==null?s[d]:null,b=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:f,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(xi,{size:18}),t.jsxs("span",{children:["Changes — ",n]}),t.jsxs("span",{className:"changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",a.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",a.deletions]})]})]}),t.jsxs("div",{className:"changes-diff-header-actions",children:[s.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:g,disabled:d===null||d<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(lc,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:d!==null?`${d+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:x,disabled:d===null||d>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(On,{})})]}),t.jsx("button",{className:`btn btn-sm ${m?"btn-primary":""}`,onClick:()=>h(y=>!y),title:m?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(zl,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(bs,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(un,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[b&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(xr,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsx("div",{className:"changes-diff-file-list",children:s.map((y,S)=>t.jsxs("button",{className:`changes-diff-file-item ${d===S?"selected":""}`,onClick:()=>u(S),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:WT(y.status)}),t.jsx("span",{className:"changes-diff-file-path",title:y.path,children:t.jsx("bdo",{dir:"ltr",children:y.path})}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",y.additions," -",y.deletions]})]},y.path))})]}),t.jsx("div",{className:"changes-diff-content",children:w?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"changes-diff-file-header-bar",children:[t.jsx("span",{className:"changes-diff-file-header-name",children:w.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",w.additions," -",w.deletions]})]}),w.patch?t.jsx("div",{className:"changes-diff-viewer",children:t.jsx("pre",{className:`changes-diff-patch ${m?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:av(w.patch)})})}):t.jsx("div",{className:"changes-diff-empty",children:"No diff available for this file."})]}):t.jsxs("div",{className:"changes-diff-empty",children:[t.jsx(xi,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function rv(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function xd(e,n,s){return t.jsxs("div",{className:"detail-section task-changes-tab",children:[n&&s&&t.jsxs("div",{className:"commit-diff-meta",children:[s.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(xr,{size:14}),t.jsx("code",{children:s.commitSha.slice(0,7)})]}),s.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(s.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(xi,{size:24}),t.jsxs("p",{children:[e.length," file",e.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:n?"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable.":"The live worktree diff is empty. Showing the last file paths captured during execution — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:e.map(a=>t.jsx("div",{className:"changes-file-item",children:t.jsxs("div",{className:"changes-file-header changes-file-header--static",children:[t.jsx("span",{className:"changes-file-status changes-file-status--unknown",title:"status unknown",children:rv("unknown")}),t.jsx("span",{className:"changes-file-path",title:a,children:t.jsx("bdo",{dir:"ltr",children:a})})]})},a))})]})}function GT({taskId:e,worktree:n,projectId:s,column:a,mergeDetails:r,modifiedFiles:o}){const[l,c]=i.useState([]),[d,u]=i.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=i.useState(!0),[f,p]=i.useState(null),[g,x]=i.useState([]),[w,b]=i.useState(null),[y,S]=i.useState(new Set),[j,C]=i.useState(null),[v,N]=i.useState(!0),[I,F]=i.useState(!1),_=a==="done",M=_&&!!r?.commitSha,z=a==="in-progress"||a==="in-review"||M,U=i.useCallback(async()=>{if(!z&&!_){h(!1);return}try{h(!0),p(null);const O=await g1(e,s);if(b(O.lineageId),x(O.associations),!z){c([]),u({filesChanged:0,additions:0,deletions:0});return}const A=await pb(e,void 0,s),P=A.files.map($=>({path:$.path,status:$.status,additions:$.additions,deletions:$.deletions,patch:$.patch}));c(P),u(A.stats),P.length>0&&(S(new Set([P[0].path])),C(0))}catch(O){p(Ee(O)||"Failed to load task changes")}finally{h(!1)}},[e,s,z,_]);i.useEffect(()=>{U()},[U]);const R=O=>{S(A=>{const P=new Set(A);if(P.has(O))P.delete(O);else{P.add(O);const $=l.findIndex(k=>k.path===O);$!==-1&&C($)}return P})},D=O=>{if(O<0||O>=l.length)return;const A=l[O].path;S(new Set([A])),C(O)},K=j!==null&&j>0,Z=j!==null&&j<l.length-1;if(m)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--loading",children:[t.jsx("div",{className:"loading-spinner"}),t.jsx("span",{children:"Loading changes..."})]})});if(f)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(Ws,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!_&&!n)return o&&o.length>0?xd(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(xi,{size:24}),t.jsx("p",{children:"No worktree available for this task."}),t.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(_&&!M){if(o&&o.length>0)return xd(o,!0,r);const O=r?.filesChanged,A=r?.insertions,P=r?.deletions,$=O!=null||A!=null||P!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(xi,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:$?`Merge summary: ${O??0} file${(O??0)===1?"":"s"} changed, +${A??0} additions, -${P??0} deletions.`:"No merge commit was recorded for this task."})]})})}const ne=()=>t.jsxs("section",{className:"task-lineage-associations","aria-label":"Task commit associations",children:[t.jsxs("div",{className:"task-lineage-associations-header",children:[t.jsxs("h4",{children:[t.jsx(xr,{size:16}),"Lineage commit associations"]}),w&&t.jsx("code",{className:"task-lineage-id",children:w})]}),g.length===0?t.jsx("p",{className:"task-lineage-associations-empty",children:"No associated commits recorded yet."}):t.jsx("div",{className:"task-lineage-associations-list",children:g.map(O=>{const A=O.matchedBy.replace(/-/g," ");return t.jsxs("article",{className:`task-lineage-association task-lineage-association--${O.confidence}`,children:[t.jsxs("div",{className:"task-lineage-association-main",children:[t.jsx("code",{className:"task-lineage-sha",children:O.commitSha.slice(0,7)}),t.jsx("span",{className:"task-lineage-subject",children:O.commitSubject})]}),t.jsxs("div",{className:"task-lineage-association-meta",children:[t.jsx("span",{children:new Date(O.authoredAt).toLocaleString()}),t.jsxs("span",{children:["Confidence: ",O.confidence]}),t.jsxs("span",{children:["Match: ",A]}),t.jsxs("span",{children:["Task snapshot: ",O.taskIdSnapshot]})]}),O.note&&t.jsx("p",{className:"task-lineage-note",children:O.note})]},`${O.commitSha}-${O.matchedBy}`)})})]});return l.length===0?o&&o.length>0?xd(o,_,r):t.jsxs("div",{className:"detail-section task-changes-tab",children:[ne(),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(xi,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:_?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})]}):t.jsxs("div",{className:"detail-section task-changes-tab",children:[ne(),_&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(xr,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"changes-header",children:[t.jsxs("div",{className:"task-changes-header-title",children:[t.jsxs("h4",{children:[t.jsx(xi,{size:16}),"Files Changed (",d.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",d.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",d.deletions]})]})]}),t.jsxs("div",{className:"changes-header-actions-wrapper",children:[t.jsxs("div",{className:"changes-header-actions",children:[l.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>K&&D(j-1),disabled:!K,title:"Previous file","aria-label":"Previous file",children:t.jsx(lc,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:j!==null?`${j+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>Z&&D(j+1),disabled:!Z,title:"Next file","aria-label":"Next file",children:t.jsx(On,{})})]}),t.jsx("button",{className:`btn btn-sm ${v?"btn-primary":""}`,onClick:()=>N(O=>!O),title:v?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(zl,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:U,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>F(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(fc,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(O=>{const A=y.has(O.path);return t.jsxs("div",{className:`changes-file-item ${A?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>R(O.path),children:[t.jsx("span",{className:"changes-file-toggle",children:A?t.jsx(pn,{size:14}):t.jsx(On,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${O.status}`,title:O.status,children:rv(O.status)}),t.jsx("span",{className:"changes-file-path",title:O.path,children:t.jsx("bdo",{dir:"ltr",children:O.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${O.additions} -${O.deletions}`,children:["+",O.additions," -",O.deletions]})]}),A&&O.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${v?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:av(O.patch)})})})]},O.path)})}),t.jsx(KT,{isOpen:I,taskId:e,files:l,stats:d,mergeDetails:r,column:a,onClose:()=>F(!1),onRefresh:U})]})}function Vp(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function JT(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function s8(e,n){const s=JT(e),a=new Set(n.map(c=>c.id));if(!a.has(s))return s;const r=30;let o=s,l=1;for(;a.has(o)&&l<100;){const c=`-${l}`;o=`${s.slice(0,r-c.length)}${c}`,l++}return o}function Wp(e){const n=e?.trim()??"";return vc.test(n)?n:""}function ov(e,n){const s=Wp(e?.githubTrackingDefaultRepo);return s||Wp(n?.githubTrackingDefaultRepo)}function YT(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const Kp=["image/png","image/jpeg","image/gif","image/webp"];function QT(e,n,s){const a=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${a}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function lv({mode:e,description:n,onDescriptionChange:s,title:a,onTitleChange:r,dependencies:o,onDependenciesChange:l,branch:c,onBranchChange:d,baseBranch:u,onBaseBranchChange:m,nodeId:h,onNodeIdChange:f,nodeOptions:p,nodeOverrideDisabled:g=!1,nodeOverrideDisabledReason:x,priority:w,onPriorityChange:b,executorModel:y,onExecutorModelChange:S,validatorModel:j,onValidatorModelChange:C,planningModel:v,onPlanningModelChange:N,thinkingLevel:I,onThinkingLevelChange:F,presetMode:_,onPresetModeChange:M,selectedPresetId:z,onSelectedPresetIdChange:U,selectedWorkflowSteps:R,onWorkflowStepsChange:D,onDefaultOnApplied:K,pendingImages:Z,onImagesChange:ne,tasks:O,projectId:A,disabled:P=!1,addToast:$,isActive:k=!0,onAutoSaveDescription:J,onPlanningMode:ce,onSubtaskBreakdown:je,onClose:He,renderBelowPrimary:xe,renderBelowModelConfiguration:Ne,hideDependencies:Y,autoExpandMoreOptionsOnSelection:ie=!0,reviewLevel:ee,onReviewLevelChange:oe,executionMode:W,onExecutionModeChange:L,githubTrackingEnabled:pe,onGithubTrackingEnabledChange:fe,githubRepoOverride:B,onGithubRepoOverrideChange:ve}){const Fe=(Y?!1:o.length>0)||Z.length>0||R.length>0||_!=="default"||(w??Ls)!==Ls||y!==""||j!==""||(v||"")!==""||(I||"")!==""||ee!==void 0||W==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!==""||pe===!0||(B||"")!=="",[ae,qe]=i.useState(!1),[Pe,nt]=i.useState(ie?Fe:!1),[Be,de]=i.useState(""),[Ie,$e]=i.useState([]),[st,Ue]=i.useState([]),[me,re]=i.useState([]),[_e,xt]=i.useState(!1),[ut,Qe]=i.useState(null),[vt,Ae]=i.useState(null),[Je,dt]=i.useState([]),[Nt,yt]=i.useState("idle"),[Se,G]=i.useState(!1),[ge,pt]=i.useState(!1),[ke,tt]=i.useState(!1),Rt=i.useRef(null),Re=i.useRef(null),be=i.useRef(null),rt=i.useRef(null),lt=i.useRef(null),gt=i.useRef(null),St=i.useRef(null),Lt=i.useRef(!1),Yt=i.useRef(Fe),tn=i.useRef(n.trim()),mn=i.useRef(n.trim());i.useEffect(()=>{k&&(xt(!0),Ks().then(se=>{$e(se.models),Ue(se.favoriteProviders),re(se.favoriteModels)}).catch(()=>{}).finally(()=>xt(!1)),gc(A).then(se=>Qe(se)).catch(()=>Qe(null)),Uo(A).then(se=>dt(se.filter(te=>te.enabled))).catch(()=>dt([])),Yi().then(se=>Ae(se)).catch(()=>Ae(null)))},[k,A]);const Qt=ut?.modelPresets||[],yn=Qt.find(se=>se.id===z),Gt=ov(ut,vt),on=(B||"").trim(),sn=on.length>0&&!vc.test(on),ln=(Y?!1:o.length>0)||Z.length>0||R.length>0||_!=="default"||(w??Ls)!==Ls||y!==""||j!==""||(v||"")!==""||(I||"")!==""||ee!==void 0||W==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!==""||pe===!0||(B||"")!=="";i.useEffect(()=>{if(e!=="create"||!k||!ut?.autoSelectModelPreset)return;const se=(ut.defaultPresetBySize,void 0);if(se){const te=Vp(se);U(se.id),M("preset"),S(te.executorValue),C(te.validatorValue)}},[k,ut,Qt,e]);const Wt=i.useRef(!1),ye=i.useRef(!1);i.useEffect(()=>{if(e!=="create"||!k||Wt.current||Je.length===0)return;const se=Je.filter(De=>De.defaultOn);if(se.length===0)return;Wt.current=!0;const te=se.map(De=>De.id);D(te),K?.(te)},[e,k,Je]),i.useEffect(()=>{k||(Wt.current=!1)},[k]),i.useEffect(()=>{e!=="create"||!k||fe&&(ye.current||ut&&(fe(ut.githubTrackingEnabledByDefault??!1),ye.current=!0))},[e,k,ut,fe]),i.useEffect(()=>{k||(ye.current=!1)},[k]),i.useEffect(()=>{if(!ie){Yt.current=ln;return}ln&&!Yt.current&&nt(!0),Yt.current=ln},[ln,ie]),i.useEffect(()=>{Pe||(qe(!1),de(""))},[Pe]),i.useEffect(()=>{e!=="edit"||!k||rt.current&&(rt.current.focus(),rt.current.select())},[e,k]),i.useEffect(()=>{if(!ae)return;const se=te=>{Re.current&&!Re.current.contains(te.target)&&qe(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[ae]),i.useEffect(()=>{(e!=="edit"||P)&&tt(!1)},[e,P]),i.useEffect(()=>{if(e!=="edit"){yt("idle");return}const se=n.trim();tn.current=se,mn.current=se,yt("idle")},[e]),i.useEffect(()=>{if(e!=="edit"||!J||!k)return;const se=n.trim(),te=tn.current;if(se===te||se===mn.current){gt.current&&(clearTimeout(gt.current),gt.current=null),Lt.current||yt("idle");return}return gt.current&&clearTimeout(gt.current),gt.current=setTimeout(async()=>{if(!Lt.current){Lt.current=!0,yt("saving");try{await J(se),mn.current=se,yt("saved"),St.current&&clearTimeout(St.current),St.current=setTimeout(()=>{yt("idle"),St.current=null},2e3)}catch{yt("idle")}finally{Lt.current=!1,gt.current=null}}},1500),()=>{gt.current&&(clearTimeout(gt.current),gt.current=null)}},[e,n,J,k]),i.useEffect(()=>()=>{gt.current&&clearTimeout(gt.current),St.current&&clearTimeout(St.current)},[]),i.useEffect(()=>{if(!Se)return;const se=te=>{Rt.current&&!Rt.current.contains(te.target)&&G(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[Se]);const Le=i.useCallback(se=>{const te=se.clipboardData?.items;if(te)for(let De=0;De<te.length;De++){const ft=te[De];if(ft.type.startsWith("image/")){const qt=ft.getAsFile();if(qt&&Kp.includes(qt.type)){se.preventDefault(),ne([...Z,{file:qt,previewUrl:URL.createObjectURL(qt)}]);return}}}},[Z,ne]),Ke=i.useCallback(se=>{se.preventDefault();const te=se.dataTransfer.files;for(let De=0;De<te.length;De++){const ft=te[De];if(Kp.includes(ft.type)){ne([...Z,{file:ft,previewUrl:URL.createObjectURL(ft)}]);return}}},[Z,ne]),mt=i.useCallback(se=>{const te=Z[se];te&&URL.revokeObjectURL(te.previewUrl),ne(Z.filter((De,ft)=>ft!==se))},[Z,ne]),Ve=i.useCallback(se=>{l(o.includes(se)?o.filter(te=>te!==se):[...o,se])},[o,l]),Pt=(se,te)=>se.length>te?se.slice(0,te)+"…":se,Ot=i.useCallback(se=>{s(se.target.value);const te=se.target;te.style.height="auto",te.style.height=te.scrollHeight+"px"},[s]),bt=i.useCallback(()=>{tt(se=>!se)},[]),Dt=i.useCallback(se=>{!ke||se.key!=="Escape"||(se.preventDefault(),se.stopPropagation(),tt(!1))},[ke]),Ft=i.useCallback(async se=>{const te=n.trim();if(!(!te||ge)){pt(!0);try{const De=await cb(te,se,A);s(De),G(!1),$("Description refined with AI","success"),be.current&&(be.current.style.height="auto",be.current.style.height=be.current.scrollHeight+"px")}catch(De){const ft=db(De);$(ft,"error")}finally{pt(!1)}}},[n,ge,$,s,A]),Ht=i.useCallback(async se=>{const te=st,ft=te.includes(se)?te.filter(qt=>qt!==se):[se,...te];Ue(ft);try{await Dn({favoriteProviders:ft,favoriteModels:me})}catch{Ue(te)}},[st,me]),rn=i.useCallback(async se=>{const te=me,ft=te.includes(se)?te.filter(qt=>qt!==se):[se,...te];re(ft);try{await Dn({favoriteProviders:st,favoriteModels:ft})}catch{re(te)}},[me,st]),Xt=i.useCallback(se=>{if(se<=0)return;const te=[...R];[te[se-1],te[se]]=[te[se],te[se-1]],D(te)},[R,D]),an=i.useCallback(se=>{if(se>=R.length-1)return;const te=[...R];[te[se],te[se+1]]=[te[se+1],te[se]],D(te)},[R,D]),Me=i.useCallback(se=>{D(R.filter(te=>te!==se))},[R,D]),it=new Map;for(const se of Je)it.set(se.id,{name:se.name,description:se.description});const kt=O.filter(se=>!o.includes(se.id)).sort((se,te)=>{const De=te.createdAt.localeCompare(se.createdAt);if(De!==0)return De;const ft=parseInt(se.id.slice(se.id.lastIndexOf("-")+1),10)||0;return(parseInt(te.id.slice(te.id.lastIndexOf("-")+1),10)||0)-ft}),$t=Be?kt.filter(se=>se.id.toLowerCase().includes(Be.toLowerCase())||se.title&&se.title.toLowerCase().includes(Be.toLowerCase())||se.description&&se.description.toLowerCase().includes(Be.toLowerCase())):kt;return t.jsxs("div",{className:"task-form",onDrop:Ke,onDragOver:se=>se.preventDefault(),onPaste:Le,children:[t.jsxs("div",{className:"task-form-primary-section",children:[e==="edit"&&r&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-form-title",children:"Title"}),t.jsx("input",{ref:rt,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:a||"",onChange:se=>r(se.target.value),disabled:P})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"task-form-description",className:"description-label-row",children:[t.jsx("span",{children:"Description"}),t.jsx("span",{className:`description-auto-save-status${Nt==="idle"?"":" is-visible"}`,"aria-live":"polite",children:Nt==="saving"?"Saving...":Nt==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${ke?" description--fullscreen":""}`,ref:Rt,onKeyDown:Dt,children:[ke&&t.jsxs("div",{className:"description-fullscreen-header",children:[t.jsx("span",{children:"Editing Description"}),t.jsx("button",{type:"button",className:"btn btn-sm description-expand-btn",onClick:bt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(Lo,{size:14})})]}),t.jsx("textarea",{ref:be,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Ot,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:P||ge}),(()=>{const se=!!n.trim()&&!P;return t.jsxs(t.Fragment,{children:[!ke&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${se?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:bt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(fc,{size:14})}),se&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${ge?"refine-button--loading":""}`,onClick:()=>G(te=>!te),disabled:ge,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(gs,{size:12,style:{verticalAlign:"middle"}}),ge?"Refining...":"Refine"]})]})})(),Se&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:se=>se.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ft("clarify"),"data-testid":"refine-clarify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Clarify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Make the description clearer and more specific"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ft("add-details"),"data-testid":"refine-add-details",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Add details"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Add implementation details and context"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ft("expand"),"data-testid":"refine-expand",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Expand"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Expand into a more comprehensive description"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ft("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]})]})]}),e==="create"&&(ce||je)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[ce&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const se=n.trim();if(!se){$("Enter a description first","error");return}He?.(),ce(se)},disabled:P||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),je&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const se=n.trim();if(!se){$("Enter a description first","error");return}He?.(),je(se)},disabled:P||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),xe,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>nt(se=>!se),"aria-expanded":Pe,"aria-controls":"task-form-more-options",disabled:P,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),Pe?t.jsx(Pi,{size:14}):t.jsx(pn,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${Pe?"":" collapsed"}`,"aria-hidden":!Pe,hidden:!Pe,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),Z.length>0&&t.jsx("div",{className:"inline-create-previews",children:Z.map((se,te)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:se.previewUrl,alt:se.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>mt(te),disabled:P,title:"Remove image",children:"×"})]},se.previewUrl))}),t.jsx("input",{ref:lt,type:"file",accept:"image/*",onChange:se=>{const te=se.target.files?.[0];te&&(ne([...Z,{file:te,previewUrl:URL.createObjectURL(te)}]),se.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>lt.current?.click(),disabled:P,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),f&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-node-select",children:"Execution Node Override"}),t.jsxs("select",{id:"task-node-select",className:"select",value:h??"",onChange:se=>f(se.target.value||void 0),disabled:P||g,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(p??[]).map(se=>t.jsxs("option",{value:se.id,children:[se.name," (",YT(se.status),")"]},se.id))]}),(()=>{const se=(p??[]).find(te=>te.id===h);return se?t.jsx("div",{className:"task-form-node-status",children:t.jsx(Oa,{status:se.status,showLabel:!0})}):null})(),t.jsx("small",{children:x??"Task override takes priority over project default node routing."})]}),!Y&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"dep-trigger-wrap",ref:Re,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>qe(se=>!se),disabled:P,children:o.length>0?`${o.length} selected`:"Add dependencies"}),ae&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Be,onChange:se=>de(se.target.value),onClick:se=>se.stopPropagation()}),$t.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):$t.map(se=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(se.id)?" selected":""}`,onClick:()=>Ve(se.id),onMouseDown:te=>te.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:se.id}),t.jsx("span",{className:"dep-dropdown-title",children:Pt(se.title||se.description||se.id,30)})]},se.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(se=>t.jsxs("span",{className:"dep-chip",children:[se,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>Ve(se),disabled:P,children:"×"})]},se))})]})}),(d||m)&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch Settings"}),d&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-working-branch",className:"model-select-label",children:"Working branch"}),t.jsx("input",{id:"task-working-branch",className:"input",value:c||"",onChange:se=>d(se.target.value),placeholder:"e.g. feature/my-task",disabled:P})]}),m&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-base-branch",className:"model-select-label",children:"Merge target / base branch"}),t.jsx("input",{id:"task-base-branch",className:"input",value:u||"",onChange:se=>m(se.target.value),placeholder:"e.g. main",disabled:P})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),b&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:w??Ls,onChange:se=>b(se.target.value),disabled:P,children:pa.map(se=>t.jsx("option",{value:se,children:se[0].toUpperCase()+se.slice(1)},se))})]}),L&&W!==void 0&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-execution-mode",className:"model-select-label",children:"Execution mode"}),t.jsxs("select",{id:"task-execution-mode","data-testid":"task-form-execution-mode-select",value:W,onChange:se=>L(se.target.value),disabled:P,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),_e?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):Ie.length===0?t.jsx("small",{children:"No models available. Configure authentication in Settings."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"model-preset",className:"model-select-label",children:"Preset"}),t.jsxs("select",{id:"model-preset",value:_==="preset"?z:_,onChange:se=>{const te=se.target.value;if(te==="default"){M("default"),U(""),S(""),C("");return}if(te==="custom"){M("custom"),U("");return}const De=Qt.find(qt=>qt.id===te),ft=Vp(De);M("preset"),U(te),S(ft.executorValue),C(ft.validatorValue)},disabled:P,children:[t.jsx("option",{value:"default",children:"Use default"}),Qt.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,Qt.map(se=>t.jsx("option",{value:se.id,children:se.name},se.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),_==="preset"&&yn?t.jsxs("small",{children:["Using preset: ",yn.name]}):null,_==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>M("custom"),disabled:P,children:"Override"}):null,t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"executor-model",className:"model-select-label",children:"Executor"}),t.jsx(Is,{id:"executor-model",label:"Executor Model",value:y,onChange:se=>{M("custom"),U(""),S(se)},models:Ie,disabled:P||_==="preset",favoriteProviders:st,onToggleFavorite:Ht,favoriteModels:me,onToggleModelFavorite:rn})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(Is,{id:"validator-model",label:"Reviewer Model",value:j,onChange:se=>{M("custom"),U(""),C(se)},models:Ie,disabled:P||_==="preset",favoriteProviders:st,onToggleFavorite:Ht,favoriteModels:me,onToggleModelFavorite:rn})]}),N&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(Is,{id:"planning-model",label:"Planning Model",value:v||"",onChange:se=>{M("custom"),U(""),N(se)},models:Ie,disabled:P||_==="preset",favoriteProviders:st,onToggleFavorite:Ht,favoriteModels:me,onToggleModelFavorite:rn})]}),F&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),t.jsxs("select",{id:"thinking-level",value:I||"",onChange:se=>F(se.target.value),disabled:P||_==="preset",children:[t.jsxs("option",{value:"",children:["Default (",ut?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]})]}),oe&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"review-level",className:"model-select-label",children:"Review"}),t.jsxs("select",{id:"review-level",value:ee??"",onChange:se=>oe(se.target.value===""?void 0:parseInt(se.target.value,10)),disabled:P,children:[t.jsx("option",{value:"",children:"Default (Auto — triage decides)"}),t.jsx("option",{value:"0",children:"0 — None"}),t.jsx("option",{value:"1",children:"1 — Plan Only"}),t.jsx("option",{value:"2",children:"2 — Plan and Code"}),t.jsx("option",{value:"3",children:"3 — Full"})]})]})]})]}),Ne,t.jsxs("div",{className:"form-group","data-testid":"workflow-steps-section",children:[t.jsx("label",{children:"Workflow Steps"}),t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:Je.length>0&&Je.map(se=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${se.id}`,children:[t.jsx("input",{type:"checkbox",checked:R.includes(se.id),onChange:te=>{D(te.target.checked?[...R,se.id]:R.filter(De=>De!==se.id))},disabled:P}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[se.name,QT(se.phase||"pre-merge",se.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:se.description})]})]},se.id))})]}),R.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),R.map((se,te)=>{const De=it.get(se);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${se}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:te+1}),t.jsx("span",{className:"workflow-step-order-name",children:De?.name||se}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Xt(te),disabled:P||te===0,"data-testid":`workflow-step-move-up-${se}`,title:"Move up",children:t.jsx(Pi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>an(te),disabled:P||te===R.length-1,"data-testid":`workflow-step-move-down-${se}`,title:"Move down",children:t.jsx(pn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Me(se),disabled:P,"data-testid":`workflow-step-remove-${se}`,title:"Remove",children:t.jsx(un,{})})]})]},se)})]})]}),(fe||ve)&&t.jsxs("div",{className:"form-group","data-testid":"task-form-github-tracking",children:[t.jsx("label",{children:"GitHub Tracking"}),fe&&t.jsxs("label",{className:"checkbox-label",htmlFor:"task-github-tracking-enabled",children:[t.jsx("input",{id:"task-github-tracking-enabled",type:"checkbox",checked:pe===!0,onChange:se=>{ye.current=!0,fe(se.target.checked)},disabled:P}),"Enable GitHub issue tracking for this task"]}),ve&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-github-repo-override",className:"model-select-label",children:"Repository (owner/repo)"}),t.jsx("input",{id:"task-github-repo-override",className:"input",value:B||"",onChange:se=>ve(se.target.value),placeholder:Gt||"owner/repo",disabled:P}),sn?t.jsx("div",{className:"form-error",children:"Repository must be in owner/repo format."}):null]})]})]})]})}const Gp={pre:({children:e,className:n,...s})=>t.jsx("pre",{...s,className:["workflow-markdown-pre",n].filter(Boolean).join(" "),children:e}),table:({children:e,className:n,...s})=>t.jsx("table",{...s,className:["workflow-markdown-table",n].filter(Boolean).join(" "),children:e})};function XT(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function ZT(e,n){if(!e||!n)return null;const s=new Date(e).getTime(),r=new Date(n).getTime()-s;if(r<1e3)return`${r}ms`;const o=Math.round(r/1e3);if(o<60)return`${o}s`;const l=Math.floor(o/60),c=o%60;return`${l}m ${c}s`}function eP(e){return e?new Date(e).toLocaleString():null}function tP(e){const n=e.split(`
684
+ `);return n.length<=1?e:`${n.length} lines`}function hl(e,n,s){const a=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${a}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function nP({entries:e,startedAt:n,stepId:s}){const a=i.useRef(null),r=new Date(n).getTime(),o=e.filter(l=>new Date(l.timestamp).getTime()>=r);return i.useEffect(()=>{const l=a.current;l&&(l.scrollTop=l.scrollHeight)},[o.length]),e.length===0?t.jsx("div",{className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:t.jsx("div",{className:"workflow-live-log-empty",children:"Waiting for agent output…"})}):t.jsx("div",{ref:a,className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:o.map((l,c)=>l.type==="tool"?t.jsxs("div",{className:"workflow-live-log-tool",children:["⚡ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_result"?t.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_error"?t.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="thinking"?t.jsx("div",{className:"workflow-live-log-thinking",children:l.text},c):t.jsx("span",{className:"workflow-live-log-text",children:l.text},c))})}function sP({taskId:e,results:n,loading:s,enabledWorkflowSteps:a,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[d,u]=i.useState({}),[m,h]=i.useState({}),[f,p]=i.useState(null),[g,x]=i.useState([]),[w,b]=i.useState(!1),y=n.some(k=>k.status==="pending"),{entries:S}=nv(e,!!l&&y,o);i.useEffect(()=>{let k=!1;return Uo(o).then(J=>{k||x(J.filter(ce=>ce.enabled))}).catch(()=>{k||x([])}),()=>{k=!0}},[o]);const j=a??[],C=i.useMemo(()=>g.map(k=>({id:k.id,name:k.name,description:k.description,phase:k.phase||"pre-merge"})),[g]),v=i.useMemo(()=>new Map(C.map(k=>[k.id,k])),[C]),N=k=>{u(J=>({...J,[k]:!J[k]}))},I=k=>{h(J=>{const ce=J[k]??"markdown";return{...J,[k]:ce==="markdown"?"plain":"markdown"}})},F=k=>{p(k)},_=()=>{p(null)};i.useEffect(()=>{if(!f)return;const k=J=>{J.key==="Escape"&&_()};return document.addEventListener("keydown",k),()=>{document.removeEventListener("keydown",k)}},[f]);const M=i.useCallback((k,J)=>{if(c){if(J){if(j.includes(k)){c(j);return}c([...j,k]);return}c(j.filter(ce=>ce!==k))}},[c,j]),z=i.useCallback(k=>{if(!c||k<=0)return;const J=[...j];[J[k-1],J[k]]=[J[k],J[k-1]],c(J)},[c,j]),U=i.useCallback(k=>{if(!c||k>=j.length-1)return;const J=[...j];[J[k],J[k+1]]=[J[k+1],J[k]],c(J)},[c,j]),R=i.useCallback(k=>{c&&c(j.filter(J=>J!==k))},[c,j]),D=n.length>0,K=j.length>0;i.useEffect(()=>{r||b(!1)},[r]);const Z=i.useMemo(()=>j.map(k=>{const J=v.get(k);return{id:k,name:J?.name||k,description:J?.description||"Step definition not found.",phase:J?.phase||"pre-merge"}}),[j,v]),ne=()=>!r||!w||s?null:t.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:C.map(k=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${k.id}`,children:[t.jsx("input",{type:"checkbox",checked:j.includes(k.id),onChange:J=>M(k.id,J.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[k.name,hl(k.phase,k.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:k.description})]})]},k.id))})]}),j.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),j.map((k,J)=>{const ce=v.get(k);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${k}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:J+1}),t.jsx("span",{className:"workflow-step-order-name",children:ce?.name||k}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>z(J),disabled:J===0,"data-testid":`workflow-step-move-up-${k}`,title:"Move up",children:t.jsx(Pi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>U(J),disabled:J===j.length-1,"data-testid":`workflow-step-move-down-${k}`,title:"Move down",children:t.jsx(pn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>R(k),"data-testid":`workflow-step-remove-${k}`,title:"Remove",children:t.jsx(un,{})})]})]},k)})]})]}),O=()=>{if(s)return t.jsxs("div",{className:"workflow-results-loading","data-testid":"workflow-results-loading",children:[t.jsx("div",{className:"workflow-results-spinner"}),t.jsx("span",{children:"Loading workflow results…"})]});if(!D)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const k=n.filter(xe=>xe.status==="passed").length,J=n.filter(xe=>xe.status==="failed").length,ce=n.filter(xe=>xe.status==="skipped").length,je=n.filter(xe=>xe.status==="pending").length,He=[`${n.length} step${n.length!==1?"s":""}`];return k>0&&He.push(`${k} passed`),J>0&&He.push(`${J} failed`),ce>0&&He.push(`${ce} skipped`),je>0&&He.push(`${je} running`),t.jsxs("div",{className:"workflow-results-list","data-testid":"workflow-results-list",children:[t.jsx("div",{className:"workflow-results-summary-bar","data-testid":"workflow-results-summary",children:He.join(" · ")}),n.map((xe,Ne)=>{const Y=xe.phase||"pre-merge",ie=d[xe.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${xe.status}`,"data-testid":`workflow-result-item-${xe.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[xe.workflowStepName,hl(Y,xe.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${xe.status}`,"data-testid":`workflow-result-badge-${xe.workflowStepId}`,children:XT(xe.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[xe.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",eP(xe.startedAt)]}),xe.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:ZT(xe.startedAt,xe.completedAt)})]}),xe.status==="pending"&&xe.startedAt?t.jsx(nP,{entries:S,startedAt:xe.startedAt,stepId:xe.workflowStepId}):xe.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-toggle",onClick:()=>N(xe.workflowStepId),"data-testid":`workflow-result-toggle-${xe.workflowStepId}`,children:ie?"Hide output":"Show output"}),!ie&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${xe.workflowStepId}`,children:tP(xe.output)}),ie&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>I(xe.workflowStepId),"data-testid":`workflow-result-mode-toggle-${xe.workflowStepId}`,title:(m[xe.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[xe.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-result-expand-toggle",onClick:()=>F(xe.workflowStepId),"data-testid":`workflow-result-expand-${xe.workflowStepId}`,title:"Expand output",children:t.jsx(fc,{size:12})})]})]}),ie&&t.jsx("div",{className:`workflow-result-output${(m[xe.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${xe.workflowStepId}`,children:(m[xe.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],components:Gp,children:xe.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:xe.output})})]}):null]},`${xe.workflowStepId}-${Ne}`)})]})},A=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>b(k=>!k),"data-testid":"workflow-steps-edit-toggle","aria-label":w?"Done editing workflow steps":"Edit workflow steps",title:w?"Done":"Edit",children:w?t.jsxs(t.Fragment,{children:[t.jsx(js,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(qs,{size:14}),"Edit"]})}):null,P=!s&&!D&&K,$=r&&D;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[P?t.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[t.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[t.jsxs("div",{className:"workflow-configured-title-row",children:[t.jsx("h4",{children:"Configured Workflow Steps"}),t.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[Z.length," step",Z.length===1?"":"s"]})]}),A]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:Z.map(k=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${k.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[k.name,hl(k.phase,k.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:k.description})]},k.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),ne()]}):t.jsxs(t.Fragment,{children:[$&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),A]}),O(),ne()]}),f&&(()=>{const k=n.find(je=>je.workflowStepId===f);if(!k)return null;const J=m[k.workflowStepId]??"markdown",ce=k.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:je=>{je.target===je.currentTarget&&_()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:k.workflowStepName}),hl(ce,k.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>I(k.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:J==="markdown"?"Switch to plain text":"Switch to markdown",children:J==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-output-modal-close",onClick:_,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(un,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${J==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:J==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],components:Gp,children:k.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:k.output})})})]})})})()]})}function iP(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const aP=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function rP(e){return e!==void 0&&e!=="online"}function oP({task:e,settings:n,addToast:s,onTaskUpdated:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(null),[m,h]=i.useState(e.nodeId??""),[f,p]=i.useState(!1),g=i.useRef(e.id);i.useEffect(()=>{g.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),i.useEffect(()=>{c(!0),u(null),ql().then(_=>{o(_)}).catch(_=>{u(Ee(_)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const x=i.useMemo(()=>new Map(r.map(_=>[_.id,_])),[r]),w=i.useMemo(()=>[...r].sort((_,M)=>_.name.localeCompare(M.name)),[r]),b=n,y=e.nodeId??b?.defaultNodeId??null,S=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",j=y?x.get(y):void 0,C=j?`${j.name} (${j.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",v=e.column==="in-progress"||aP.has(e.status),N=v||f||l,I=i.useCallback(async _=>{if(_===m)return;const M=e.id,z=m;h(_),p(!0);try{const U=await Hs(M,{nodeId:_||null});if(g.current!==M)return;h(U.nodeId??""),a?.(U),s(_?"Node override updated":"Node override cleared","success")}catch(U){if(g.current!==M)return;h(z),s(Ee(U)||"Failed to update node override","error")}finally{g.current===M&&p(!1)}},[s,a,m,e.id]),F=i.useCallback(()=>{I("")},[I]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:"Task Routing"}),t.jsx("p",{className:"routing-tab__intro",children:"View the effective execution node and control per-task node override."}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Routing Summary"}),t.jsxs("div",{className:"routing-summary-grid",role:"list",children:[t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Effective node"}),t.jsxs("span",{className:"routing-summary-value",children:[j?t.jsx(Oa,{status:j.status,compact:!0}):null,C,rP(j?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children:S})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Unavailable-node policy"}),t.jsx("span",{className:"routing-summary-value",children:iP(b?.unavailableNodePolicy)})]})]}),v&&y?t.jsx("div",{className:"routing-tab__info-banner",children:"Routing is locked while this task is active. Node override cannot be changed until the task is no longer active."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),v?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:m,disabled:N,onChange:_=>{I(_.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),w.map(_=>t.jsxs("option",{value:_.id,title:`Status: ${_.status}`,children:[_.name," (",_.type,") — ",_.status]},_.id))]}),d?t.jsx("div",{className:"routing-tab__error",children:d}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:["Override set to: ",x.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:v||f,onClick:F,children:"Clear override"})]}):null]})]})}const lP=/^[a-zA-Z0-9_-]{1,64}$/,cP=200;function Jp(e){return e?new Date(e).toLocaleString():""}function dP(e,n=cP){return e.length<=n?e:e.substring(0,n)+"…"}function uP({taskId:e,addToast:n,onTaskUpdated:s,projectId:a,canEdit:r=!1}){const[o,l]=i.useState([]),[c,d]=i.useState(!0),[u,m]=i.useState(null),[h,f]=i.useState(""),[p,g]=i.useState(null),[x,w]=i.useState(""),[b,y]=i.useState(null),[S,j]=i.useState([]),[C,v]=i.useState(!1),[N,I]=i.useState(!1),[F,_]=i.useState(""),[M,z]=i.useState(""),[U,R]=i.useState(!1),[D,K]=i.useState(null),[Z,ne]=i.useState(null),[O,A]=i.useState(!1),P=i.useCallback(async()=>{try{const Y=await Kj(e,a);l(Y)}catch(Y){n(Ee(Y)||"Failed to load documents","error")}finally{d(!1)}},[e,a,n]);i.useEffect(()=>{P()},[P]);async function $(Y){u===Y.key?(m(null),f(""),g(null),w(""),y(null),j([]),A(!1)):(m(Y.key),f(Y.content),g(null),w(""),y(null),j([]),A(!1))}async function k(Y){if(b===Y)y(null),j([]);else{y(Y),v(!0);try{const ie=await Gj(e,Y,a);j(ie)}catch(ie){n(Ee(ie)||"Failed to load revisions","error")}finally{v(!1)}}}function J(){u&&(g(u),w(h))}function ce(){g(null),w("")}async function je(){if(!(!p||!x.trim())){R(!0);try{await Fm(e,p,x,{},a),g(null),w(""),await P();const Y=o.find(ie=>ie.key===p);Y&&f(Y.content),n("Document saved","success")}catch(Y){n(Ee(Y)||"Failed to save document","error")}finally{R(!1)}}}async function He(){const Y=F.trim(),ie=M.trim();if(!Y){n("Document key is required","error");return}if(!lP.test(Y)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!ie){n("Content is required","error");return}R(!0);try{await Fm(e,Y,ie,{},a),I(!1),_(""),z(""),await P(),n("Document created","success")}catch(ee){n(Ee(ee)||"Failed to create document","error")}finally{R(!1)}}async function xe(Y){K(Y);try{await Jj(e,Y,a),ne(null),K(null),u===Y&&(m(null),f("")),b===Y&&(y(null),j([])),await P(),n("Document deleted","success")}catch(ie){n(Ee(ie)||"Failed to delete document","error")}finally{K(null)}}function Ne(Y){f(Y.content),g(null),w("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),N&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:"New Document"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:"Key"}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:F,onChange:Y=>_(Y.target.value),placeholder:"e.g., plan, notes, research",disabled:U}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:M,onChange:Y=>z(Y.target.value),rows:6,placeholder:"Enter document content…",disabled:U})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{I(!1),_(""),z("")},disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void He(),disabled:U||!F.trim()||!M.trim(),children:U?"Creating…":"Create"})]})]}),o.length===0&&!N?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(Y=>t.jsxs("div",{className:"task-document-card",children:[t.jsxs("div",{className:"task-document-card-header",children:[t.jsxs("div",{className:"task-document-card-title",children:[t.jsx(ua,{size:14}),t.jsx("span",{className:"task-document-key",children:Y.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",Y.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:Y.author}),t.jsx("span",{className:"task-document-timestamp",children:Jp(Y.updatedAt||Y.createdAt)})]})]}),u===Y.key&&p!==Y.key&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"task-document-content-header",children:t.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>A(ie=>!ie),"aria-label":O?"Switch to plain text":"Switch to markdown","aria-pressed":O,title:O?"Switch to plain text":"Switch to markdown",children:O?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:O?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===Y.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),C?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):S.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:S.filter(ie=>ie.revision<Y.revision).sort((ie,ee)=>ee.revision-ie.revision).map(ie=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>Ne(ie),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",ie.revision]}),t.jsx("span",{className:"revision-author",children:ie.author}),t.jsx("span",{className:"revision-timestamp",children:Jp(ie.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:dP(ie.content,100)})]},ie.id))})]})]}),p===Y.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:x,onChange:ie=>w(ie.target.value),rows:10,disabled:U}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:ce,disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void je(),disabled:U||!x.trim(),children:U?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void $(Y),children:u===Y.key?t.jsxs(t.Fragment,{children:[t.jsx(Pi,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(pn,{size:14})," Expand"]})}),u===Y.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void k(Y.key),children:[t.jsx(Pa,{size:14})," History"]}),r&&p!==Y.key&&t.jsx("button",{className:"btn btn-sm",onClick:J,children:"Edit"}),r&&(Z===Y.key?t.jsxs("div",{className:"confirm-delete-actions",children:[t.jsx("span",{children:"Delete?"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void xe(Y.key),disabled:D===Y.key,children:D===Y.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>ne(null),disabled:D===Y.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>ne(Y.key),children:t.jsx(_n,{size:14})}))]})]})]},Y.key))}),r&&!N&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>I(!0),children:[t.jsx(Mn,{size:14})," New Document"]})]})}function pl(e){return e.toLocaleString()}function vd(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function eo(e){if(e<1e3)return`${Math.round(e)} ms`;const n=e/1e3;if(n<60)return`${n.toFixed(1)} s`;const s=Math.floor(n/60),a=Math.round(n%60);return`${s}m ${a}s`}function mP(e){const n=Date.now(),s=e.map(o=>{if(!o.startedAt)return null;const l=new Date(o.startedAt).getTime();if(Number.isNaN(l))return null;let c;if(o.completedAt){const d=new Date(o.completedAt).getTime();if(Number.isNaN(d)||d<l)return null;c=d}else c=Math.max(l,n);return{name:o.workflowStepName||o.workflowStepId,durationMs:c-l}}).filter(o=>o!==null),a=zb(e,n)??0,r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:a,longestStep:r}}function hP({tokenUsage:e,loading:n,task:s}){const a=Date.now(),r=Ob(s?.log??[]),o=r.filter(g=>typeof g.durationMs=="number"),l=o.reduce((g,x)=>g+(x.durationMs??0),0),c=Fb(s?.log)??0,d=typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:Math.max(l,c),u=o.reduce((g,x)=>!g||(x.durationMs??0)>(g.durationMs??0)?x:g,void 0),m=mP(s?.workflowStepResults??[]),f=Bb(s?.executionStartedAt,s?.executionCompletedAt,a)??(typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:d+m.totalDurationMs),p=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task execution statistics",children:[t.jsx("h4",{children:"Execution & Token Stats"}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Timing"}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Execution timing metrics",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timing events"}),t.jsx("span",{className:"task-token-stats-panel__value",children:r.length.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timed duration"}),t.jsx("span",{className:"task-token-stats-panel__value",children:eo(d)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow timed steps"}),t.jsx("span",{className:"task-token-stats-panel__value",children:m.timedStepCount.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow runtime"}),t.jsx("span",{className:"task-token-stats-panel__value",children:eo(m.totalDurationMs)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total execution time"}),t.jsx("span",{className:"task-token-stats-panel__value",children:eo(f)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest timing event"}),t.jsx("dd",{children:u?.durationMs?`${u.summary} (${eo(u.durationMs)})`:"No timed events recorded yet."})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest workflow step"}),t.jsx("dd",{children:m.longestStep?`${m.longestStep.name} (${eo(m.longestStep.durationMs)})`:"No completed workflow step timings yet."})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Details"}),t.jsxs("dl",{className:"task-token-stats-panel__details",children:[t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Execution mode"}),t.jsx("dd",{children:s?.executionMode==="fast"?"Fast":"Standard"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime status"}),t.jsx("dd",{children:s?.status??"Not set"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Paused"}),t.jsx("dd",{children:s?.paused?"Yes":"No"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Step progress"}),t.jsx("dd",{children:p>0?`${Math.min((s?.currentStep??0)+1,p)} / ${p}`:"No steps"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Retries (recovery / workflow / merge / task_done)"}),t.jsx("dd",{children:`${s?.recoveryRetryCount??0} / ${s?.workflowStepRetries??0} / ${s?.mergeRetries??0} / ${s?.taskDoneRetryCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Recovery state"}),t.jsx("dd",{children:s?.nextRecoveryAt?`Next recovery at ${vd(s.nextRecoveryAt)}`:"No scheduled recovery"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Self-heal counters"}),t.jsx("dd",{children:`stuck kills: ${s?.stuckKillCount??0}, post-review fixes: ${s?.postReviewFixCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime links"}),t.jsx("dd",{children:[s?.assignedAgentId?`agent ${s.assignedAgentId}`:null,s?.checkedOutBy?`checkout ${s.checkedOutBy}`:null,s?.blockedBy?`blocked by ${s.blockedBy}`:null,s?.sessionFile?"has session":null].filter(Boolean).join(", ")||"No runtime links"})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Token Usage"}),!e&&n?t.jsx("div",{className:"task-token-stats-panel__loading",role:"status","aria-live":"polite",children:"Loading token statistics…"}):e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Task token totals",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Input"}),t.jsx("span",{className:"task-token-stats-panel__value",children:pl(e.inputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Output"}),t.jsx("span",{className:"task-token-stats-panel__value",children:pl(e.outputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Cached"}),t.jsx("span",{className:"task-token-stats-panel__value",children:pl(e.cachedTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total"}),t.jsx("span",{className:"task-token-stats-panel__value",children:pl(e.totalTokens)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"First used"}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.firstUsedAt,children:vd(e.firstUsedAt)})})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Last used"}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.lastUsedAt,children:vd(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const gm=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function pP(e){let n=null;for(const s of e){if(s.agent!=="executor"||s.type!=="text")continue;const a=s.text.match(/^Executor using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function fP(e){let n=null;for(const s of e){if(s.agent!=="reviewer"||s.type!=="text")continue;const a=s.text.match(/^Reviewer using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function cv(e){const n=e?.runtimeConfig??void 0,s=typeof n?.model=="string"?n.model.trim():"";if(s){const o=s.indexOf("/");if(o>0&&o<s.length-1)return{provider:s.slice(0,o),modelId:s.slice(o+1)}}const a=typeof n?.modelProvider=="string"?n.modelProvider.trim():"",r=typeof n?.modelId=="string"?n.modelId.trim():"";return{provider:a||void 0,modelId:r||void 0}}function gP(e,n,s,a){const r=pP(n);if(r)return r;if(gm.has(e.status??"")||e.column==="in-progress"){const o=cv(s);if(o.provider&&o.modelId)return o}return Eb(e,a)}function bP(e,n,s,a){const r=fP(n);if(r)return r;if(gm.has(e.status??"")||e.column==="in-progress"){const o=cv(s);if(o.provider&&o.modelId)return o}return _b(e,a)}function xP(e){let n=null;for(const s of e){if(s.agent!=="triage"||s.type!=="text")continue;const a=s.text.match(/^Triage using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function vP(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const a=xP(n);return a||Mb(e,s)}function yP(e){switch(e){case"done":return"var(--color-success)";case"in-progress":return"var(--todo)";case"skipped":return"var(--text-dim)";case"pending":default:return"var(--border)"}}function yd(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function wP(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function wd(e,n){return e.length>n?e.slice(0,n)+"…":e}function Yp(e=[],n=[]){return e.length===n.length&&e.every((s,a)=>s===n[a])}function kd(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function jd(e){return e.trim()}function kP(e){const n=e.trim();return n.length>0?n:void 0}function Ui(e){return typeof e=="string"&&pa.includes(e)?e:Ls}function Hi(e){return e==="fast"?"fast":"standard"}function jP(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function NP(e){const n=e?.findingLabel;if(typeof n=="string"&&n.length>0)return n;const s=e?.runId;return typeof s=="string"&&s.length>0?s:void 0}const SP=i.lazy(()=>Sn(()=>import("./AgentDetailView-shgiiUb4.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.AgentDetailView})));function CP(e,n={}){switch(e.sourceType){case"dashboard_ui":return{label:"Dashboard"};case"quick_chat":return{label:"Quick Chat"};case"chat_session":return{label:"Chat Session"};case"agent_heartbeat":return{label:n.sourceAgentName??e.sourceAgentId??"agent",sourceAgentId:e.sourceAgentId};case"automation":return{label:"Automation"};case"cron":return{label:"Scheduled Task"};case"workflow_step":return{label:"Workflow Step"};case"github_import":return{label:"GitHub Import",contextInfo:jP(e.sourceMetadata)};case"research":return{label:"Research",contextInfo:NP(e.sourceMetadata)};case"task_refine":return{label:"Refinement",parentTaskId:e.sourceParentTaskId};case"task_duplicate":return{label:"Duplicate",parentTaskId:e.sourceParentTaskId};case"cli":return{label:"CLI"};case"api":return{label:"API"};case"recovery":return{label:"Recovery"};case"unknown":default:return null}}const Nd=200,EP=new Set(["triage","todo"]),_P=new Set(["triage","todo","in-progress","in-review"]);function dv({task:e,projectId:n,tasks:s=[],onOpenDetail:a,onMoveTask:r,onDeleteTask:o,onMergeTask:l,onRetryTask:c,onResetTask:d,onDuplicateTask:u,onTaskUpdated:m,addToast:h,prAuthAvailable:f,initialTab:p="definition",mobileHeaderMode:g="close",embedded:x=!1,onRequestClose:w}){const[b,y]=i.useState(p),[S,j]=i.useState(()=>"prompt"in e?e:null),[C,v]=i.useState(()=>!("prompt"in e));i.useEffect(()=>{if("prompt"in e){j(e),v(!1);return}let Q=!1;return v(!0),j(null),La(e.id,n).then(Te=>{Q||(j(Te),v(!1))}).catch(()=>{Q||v(!1)}),()=>{Q=!0}},[e.id,n]);const N=S?{...S,...e,prompt:S.prompt,log:S.log}:{...e,prompt:""},I=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,[F,_]=i.useState(null),[M,z]=i.useState(null),U=CP(N,{sourceAgentName:F?.name});i.useEffect(()=>{y(p)},[p]),i.useEffect(()=>{Z(!1)},[e.id]);const[R,D]=i.useState("activity"),[K,Z]=i.useState(!1),[ne,O]=i.useState(e.attachments||[]),[A,P]=i.useState(!1),[$,k]=i.useState(e.dependencies||[]),[J,ce]=i.useState(!1),[je,He]=i.useState(""),[xe,Ne]=i.useState(null),[Y,ie]=i.useState([]),[ee,oe]=i.useState(!1),[W,L]=i.useState(!1),[pe,fe]=i.useState(!1),[B,ve]=i.useState(!1),[Fe,ae]=i.useState(!1),[qe,Pe]=i.useState(N.prompt||""),[nt,Be]=i.useState(""),[de,Ie]=i.useState(!1),[$e,st]=i.useState(""),[Ue,me]=i.useState(!1),[re,_e]=i.useState(!1),[xt,ut]=i.useState(e.title||""),[Qe,vt]=i.useState(e.description||""),[Ae,Je]=i.useState(e.dependencies||[]),[dt,Nt]=i.useState(e.branch??""),[yt,Se]=i.useState(e.baseBranch??""),[G,ge]=i.useState(""),[pt,ke]=i.useState(""),[tt,Rt]=i.useState(""),[Re,be]=i.useState(""),[rt,lt]=i.useState("default"),[gt,St]=i.useState(void 0),[Lt,Yt]=i.useState(Ls),[tn,mn]=i.useState(e.nodeId),[Qt,yn]=i.useState(Hi(e.executionMode)),[Gt,on]=i.useState(""),[sn,ln]=i.useState(e.enabledWorkflowSteps||[]),[Wt,ye]=i.useState(e.sourceIssue?.provider??""),[Le,Ke]=i.useState(e.sourceIssue?.repository??""),[mt,Ve]=i.useState(e.sourceIssue?.externalIssueId??""),[Pt,Ot]=i.useState(e.sourceIssue?.url??""),[bt,Dt]=i.useState([]),[Ft,Ht]=i.useState(!1),[rn,Xt]=i.useState(Ui(e.priority)),[an,Me]=i.useState(!1),[it,kt]=i.useState(Hi(e.executionMode)),[$t,se]=i.useState(!1),te=i.useRef(!1),[De,ft]=i.useState(!1),[qt,zt]=i.useState(!1),[Pn,he]=i.useState(!1),[ht,at]=i.useState(!1),[wt,Xe]=i.useState(e.githubTracking?.repoOverride??""),[Et,Zt]=i.useState(null),[le,ct]=i.useState(null),[nn,Rn]=i.useState(!1),Un=i.useRef(null),wn=i.useRef(null),rs=i.useRef(null),{getSlotsForId:_s}=wb(n),Ut=_s("task-detail-tab").map((Q,Te)=>({entry:Q,tabId:`plugin-${Q.pluginId}-${Te}`})),xs=typeof b=="string"&&b.startsWith("plugin-")?Ut.find(Q=>Q.tabId===b)??null:null;i.useEffect(()=>(te.current=!0,()=>{te.current=!1}),[]);const[xn,Xn]=i.useState(void 0),[$n,vs]=i.useState(null),[ms,hs]=i.useState([]),[Jn,ps]=i.useState(!1),[Ns,Yn]=i.useState(e.enabledWorkflowSteps||[]),ys=e.column==="in-progress"||gm.has(e.status);i.useEffect(()=>{ut(e.title||""),vt(e.description||""),Nt(e.branch??""),Se(e.baseBranch??""),ye(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),Ve(e.sourceIssue?.externalIssueId??""),Ot(e.sourceIssue?.url??""),yn(Hi(e.executionMode)),he(!1),at(!1),Xe(e.githubTracking?.repoOverride??""),Zt(null),ct(null),_e(!1)},[e.id,e.title,e.description,e.branch,e.baseBranch,e.sourceIssue,e.executionMode,e.githubTracking]),i.useEffect(()=>{Yn(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),i.useEffect(()=>{Xt(Ui(e.priority))},[e.id,e.priority]),i.useEffect(()=>{kt(Hi(e.executionMode))},[e.id,e.executionMode]),i.useEffect(()=>{Et!==null&&e.githubTracking?.enabled===!0===Et&&Zt(null)},[Et,e.githubTracking?.enabled]),i.useEffect(()=>{let Q=!1;return gc(n).then(Te=>{Q||Xn(Te)}).catch(()=>{}),Yi().then(Te=>{Q||vs(Te)}).catch(()=>{Q||vs(null)}),()=>{Q=!0}},[n]),i.useEffect(()=>{if(b!=="workflow")return;let Q=!1;return ps(!0),PS(e.id,n).then(Te=>{Q||hs(Te)}).catch(Te=>{Q||h(`Failed to load workflow results: ${Ee(Te)}`,"error")}).finally(()=>{Q||ps(!1)}),()=>{Q=!0}},[b,e.id,n,h]),i.useEffect(()=>{if(b!=="workflow")return;const Q=n?`?projectId=${encodeURIComponent(n)}`:"",Te=_t=>{try{const Jt=JSON.parse(_t.data);Jt.id===e.id&&Array.isArray(Jt.workflowStepResults)&&hs(Jt.workflowStepResults)}catch{}};return hi(`/api/events${Q}`,{events:{"task:updated":Te}})},[b,e.id,n]),i.useEffect(()=>{J||He("")},[J]),i.useEffect(()=>{if(!e.assignedAgentId){Ne(null);return}const Q=Y.find(_t=>_t.id===e.assignedAgentId);if(Q){Ne(Q);return}let Te=!1;return au(e.assignedAgentId,n).then(_t=>{Te||Ne(_t)}).catch(()=>{Te||Ne(null)}),()=>{Te=!0}},[e.assignedAgentId,n,Y]),i.useEffect(()=>{if(!e.sourceAgentId){_(null);return}const Q=Y.find(_t=>_t.id===e.sourceAgentId);if(Q){_(Q);return}let Te=!1;return Promise.resolve(au(e.sourceAgentId,n)).then(_t=>{Te||_(_t??null)}).catch(()=>{Te||_(null)}),()=>{Te=!0}},[e.sourceAgentId,n,Y]),i.useEffect(()=>{oe(!1)},[e.id]),i.useEffect(()=>{if(!(De||qt))return;const Te=_t=>{const Jt=_t.target,Qn=Un.current?.contains(Jt),Bi=rs.current?.contains(Jt);!Qn&&De&&ft(!1),!Bi&&qt&&zt(!1)};return document.addEventListener("mousedown",Te),()=>document.removeEventListener("mousedown",Te)},[De,qt]),i.useEffect(()=>{if(!(De||qt))return;const Te=_t=>{_t.key==="Escape"&&(_t.stopPropagation(),De&&ft(!1),qt&&zt(!1))};return document.addEventListener("keydown",Te),()=>document.removeEventListener("keydown",Te)},[De,qt]),i.useEffect(()=>{ae(!1),Pe(N.prompt||""),Be("")},[e.id,N.prompt]);const ws=EP.has(e.column)&&!Ft,Ms=_P.has(e.column)&&!Ft,X=Et??e.githubTracking?.enabled===!0,E=e.githubTracking?.issue,ue=Ms||X||!!E,Ce=E?"Linked":X?"Enabled":"Disabled",We=ov(xn??null,$n),At=wt.trim(),q=i.useCallback(async()=>{if(!Ms||nn)return;const Q=!X;Zt(Q),Rn(!0);try{const Te=await Hs(e.id,{githubTracking:{enabled:Q}},n);m?.(Te)}catch(Te){Zt(e.githubTracking?.enabled===!0),h(`Failed to update ${e.id}: ${Ee(Te)}`,"error")}finally{te.current&&Rn(!1)}},[h,Ms,X,nn,m,n,e.githubTracking?.enabled,e.id]),we=i.useCallback(async()=>{if(!(!Ms||nn)){if(At.length>0&&!vc.test(At)){ct("Repository override must be in owner/repo format");return}ct(null),Rn(!0);try{const Q=await Hs(e.id,{githubTracking:{repoOverride:At.length>0?At:null}},n);m?.(Q)}catch(Q){h(`Failed to update ${e.id}: ${Ee(Q)}`,"error")}finally{te.current&&Rn(!1)}}},[h,Ms,At,nn,m,n,e.id]),Oe=i.useCallback(async()=>{if(!(!X||E||nn)){Rn(!0);try{const Q=await Hs(e.id,{githubTracking:{enabled:!0}},n);m?.(Q),h("Requested GitHub tracking issue creation","info")}catch(Q){h(`Failed to update ${e.id}: ${Ee(Q)}`,"error")}finally{te.current&&Rn(!1)}}},[h,E,X,nn,m,n,e.id]),It=i.useCallback(()=>{if(!ws)return;_e(!0),ut(e.title||""),vt(e.description||""),Je(e.dependencies||[]),Nt(e.branch??""),Se(e.baseBranch??"");const Q=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Te=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",_t=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";ge(Q),ke(Te),Rt(_t),be(e.thinkingLevel??""),mn(e.nodeId),lt(Q||Te||_t?"custom":"default"),on(""),ln(e.enabledWorkflowSteps||[]),yn(Hi(e.executionMode)),ye(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),Ve(e.sourceIssue?.externalIssueId??""),Ot(e.sourceIssue?.url??""),Dt([]),St(e.reviewLevel),Yt(Ui(e.priority))},[ws,e]),Kt=i.useCallback(()=>{_e(!1),ut(e.title||""),vt(e.description||""),Je(e.dependencies||[]),Nt(e.branch??""),Se(e.baseBranch??""),mn(e.nodeId),ye(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),Ve(e.sourceIssue?.externalIssueId??""),Ot(e.sourceIssue?.url??""),Yt(Ui(e.priority)),yn(Hi(e.executionMode)),bt.forEach(Q=>URL.revokeObjectURL(Q.previewUrl)),Dt([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,bt]),[fn,An]=i.useState("idle"),jn=i.useRef(null),En=i.useRef(0),ts=i.useCallback(Q=>{const Te={},_t=xt.trim(),Jt=Qe.trim();_t&&_t!==(e.title??"")&&(Te.title=_t),Q&&Jt&&Jt!==(e.description??"")&&(Te.description=Jt),Yp(Ae,e.dependencies??[])||(Te.dependencies=Ae),Yp(sn,e.enabledWorkflowSteps??[])||(Te.enabledWorkflowSteps=sn);const Qn=dt.trim()||null,Bi=e.branch??null;Qn!==Bi&&(Te.branch=Qn);const km=yt.trim()||null,iy=e.baseBranch??null;km!==iy&&(Te.baseBranch=km);const jm=kd(G),ay=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";G!==ay&&(Te.modelProvider=jm?.provider??null,Te.modelId=jm?.modelId??null);const Nm=kd(pt),ry=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";pt!==ry&&(Te.validatorModelProvider=Nm?.provider??null,Te.validatorModelId=Nm?.modelId??null);const Sm=kd(tt),oy=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";tt!==oy&&(Te.planningModelProvider=Sm?.provider??null,Te.planningModelId=Sm?.modelId??null);const ly=e.thinkingLevel??"";Re!==ly&&(Te.thinkingLevel=Re!==""?Re:null),(e.nodeId??void 0)!==tn&&(Te.nodeId=tn??null),gt!==e.reviewLevel&&(Te.reviewLevel=gt),Lt!==Ui(e.priority)&&(Te.priority=Lt),Qt!==Hi(e.executionMode)&&(Te.executionMode=Qt==="fast"?"fast":null);const _c=jd(Wt),Mc=jd(Le),Qo=jd(mt),Ac=kP(Pt);if(_c.length===0&&Mc.length===0&&Qo.length===0&&!Ac)e.sourceIssue&&(Te.sourceIssue=null);else{if(!_c||!Mc||!Qo)return{updates:null,error:"Source issue provider, repository, and issue identifier are required"};const cy=Number.parseInt(Qo,10),Rc=e.sourceIssue?.issueNumber??cy;if(!Number.isFinite(Rc)||Rc<=0)return{updates:null,error:"Source issue identifier must be numeric for new metadata"};const tr={provider:_c,repository:Mc,externalIssueId:Qo,issueNumber:Rc,...Ac?{url:Ac}:{}},nr=e.sourceIssue;(!nr||nr.provider!==tr.provider||nr.repository!==tr.repository||nr.externalIssueId!==tr.externalIssueId||nr.issueNumber!==tr.issueNumber||(nr.url??void 0)!==tr.url)&&(Te.sourceIssue=tr)}return{updates:Te,error:null}},[yt,dt,Ae,Qe,Qt,G,tn,tt,Lt,gt,sn,mt,Wt,Le,Pt,Re,xt,pt,e]),Ln=i.useCallback(async Q=>{const{updates:Te,error:_t}=ts(Q);if(!Te)return An("error"),_t&&h(`Failed to update ${e.id}: ${_t}`,"error"),!1;if(Object.keys(Te).length===0)return!0;const Jt=++En.current;Ht(!0),An("saving");try{const Qn=await Hs(e.id,Te,n);return Jt!==En.current?void 0:(m?.(Qn),An("saved"),!0)}catch(Qn){return Jt===En.current&&(An("error"),h(`Failed to update ${e.id}: ${Ee(Qn)}`,"error")),!1}finally{te.current&&Jt===En.current&&Ht(!1)}},[h,ts,m,n,e.id]),os=i.useCallback(async Q=>{await Ln(!0)},[Ln]),fs=i.useCallback(async()=>{await Ln(!0)&&(h(`Updated ${e.id}`,"success"),te.current&&_e(!1))},[h,Ln,e.id]);i.useEffect(()=>{if(re)return jn.current&&clearTimeout(jn.current),jn.current=setTimeout(()=>{Ln(!1)},700),()=>{jn.current&&(clearTimeout(jn.current),jn.current=null)}},[re,xt,Ae,dt,yt,G,pt,tt,Re,tn,gt,Lt,Qt,sn,Wt,Le,mt,Pt,Ln]);const ns=i.useCallback(async Q=>{const Te=Ui(Q),_t=Ui(e.priority);if(Te===_t){Xt(_t);return}const Jt=rn;Xt(Te),Me(!0);try{const Qn=await Hs(e.id,{priority:Te},n);Xt(Ui(Qn.priority)),m?.(Qn),h(`Priority updated to ${Ui(Qn.priority)}`,"success")}catch(Qn){Xt(Jt),h(`Failed to update ${e.id}: ${Ee(Qn)}`,"error")}finally{te.current&&Me(!1)}},[e.id,e.priority,n,rn,m,h]),Zn=i.useCallback(async()=>{const Te=Hi(e.executionMode)==="fast"?"standard":"fast",_t=it;kt(Te),se(!0);try{const Jt=await Hs(e.id,{executionMode:Te==="fast"?"fast":null},n),Qn=Hi(Jt.executionMode);kt(Qn),m?.(Jt),h(`Execution mode updated to ${Qn}`,"success")}catch(Jt){kt(_t),h(`Failed to update ${e.id}: ${Ee(Jt)}`,"error")}finally{te.current&&se(!1)}},[e.id,e.executionMode,n,it,m,h]),es=i.useCallback(Q=>{re&&(Q.key==="Escape"?(Q.preventDefault(),Kt()):Q.key==="Enter"&&(Q.ctrlKey||Q.metaKey)&&(Q.preventDefault(),fs()))},[re,Kt,fs]);i.useEffect(()=>{if(re)return document.addEventListener("keydown",es),()=>document.removeEventListener("keydown",es)},[re,es]);const Ss=i.useRef(null),{nodes:ls}=yc(),{confirm:ss}=pi(),Zs=i.useCallback(async()=>{if(!(!ws||!E||nn||!await ss({title:"Unlink GitHub issue?",message:"This stops Fusion from syncing with the linked GitHub issue. The issue itself will not be modified.",confirmLabel:"Unlink",danger:!0}))){Rn(!0);try{const Te=await Hs(e.id,{githubTracking:{issue:null}},n);m?.(Te),h("GitHub issue unlinked","success")}catch(Te){h(`Failed to update ${e.id}: ${Ee(Te)}`,"error")}finally{te.current&&Rn(!1)}}},[h,ws,ss,E,nn,m,n,e.id]),{entries:Si,loading:ga,loadMore:Wa,hasMore:Ka,total:Ga,loadingMore:oi}=nv(e.id,b==="logs"&&R==="agent-log",n),gn=i.useCallback(()=>{w?.()},[w]);i.useEffect(()=>{if(x)return;const Q=Te=>{Te.key==="Escape"&&!re&&gn()};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[x,gn,re]);const Fi=i.useCallback(async Q=>{try{const Te=e.steps.some(Qn=>Qn.status!=="pending"),_t=(Q==="todo"||Q==="triage")&&Te;let Jt;if(_t){if(await ss({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Jt={preserveProgress:!0};else if(!await ss({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(e.id,Q,Jt),gn(),h(`Moved to ${ds[Q]}`,"success")}catch(Te){h(Ee(Te),"error")}},[e.id,e.steps,r,gn,h,ss]),ea=i.useCallback(async()=>{if(await ss({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await o(e.id),gn(),h(`Deleted ${e.id}`,"info")}catch(Te){const _t=Ku(Te);if(!_t||_t.dependentIds.length===0){h(Ee(Te),"error");return}const Jt=_t.dependentIds.join(", ");if(!await ss({title:"Force Delete Task",message:`${e.id} is a dependency of ${Jt}.
685
+
686
+ Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await o(e.id,{removeDependencyReferences:!0}),gn(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(Bi){h(Ee(Bi),"error")}}},[e.id,o,gn,h,ss]),ba=i.useCallback(async()=>{await ss({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(gn(),h(`Merging ${e.id}...`,"info"),l(e.id).then(Te=>{const _t=Te.merged?`Merged ${e.id} (branch: ${Te.branch})`:`Closed ${e.id} (${Te.error||"no branch to merge"})`;h(_t,"success")}).catch(Te=>{h(Ee(Te),"error")}))},[e.id,l,gn,h,ss]),Ja=i.useCallback(()=>{c&&(gn(),c(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(Q=>{h(Ee(Q),"error")}))},[e.id,c,gn,h]),xa=i.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(gn(),d(e.id).then(()=>{h(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(Q=>{h(Ee(Q),"error")}))},[e.id,d,gn,h]),va=i.useCallback(async()=>{if(!(!u||!await ss({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const Te=await u(e.id);gn(),h(`Duplicated ${e.id} → ${Te.id}`,"success")}catch(Te){h(Ee(Te),"error")}},[e.id,u,gn,h,ss]),ya=i.useCallback(async()=>{try{e.paused?(await Dj(e.id,n),h(`Unpaused ${e.id}`,"success")):(await ab(e.id,n),h(`Paused ${e.id}`,"success")),gn()}catch(Q){h(Ee(Q),"error")}},[e.id,e.paused,gn,h]),Ya=i.useCallback(async()=>{try{await zj(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),gn()}catch(Q){h(Ee(Q),"error")}},[e.id,gn,h]),wa=i.useCallback(async()=>{if(await ss({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await Bj(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),gn()}catch(Te){h(Ee(Te),"error")}},[e.id,gn,h,ss]),zr=i.useCallback(async()=>{if(await ss({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await Xj(e.id,n),gn(),h(`Replanning ${e.id}...`,"info")}catch(Te){h(Ee(Te),"error")}},[e.id,n,gn,h,ss]),ka=i.useCallback(()=>{Ie(!0),st("")},[]),Us=i.useCallback(()=>{ft(!1),zt(!1)},[]),Ci=i.useCallback(Q=>{Us(),Fi(Q)},[Us]),ei=i.useCallback(Q=>{Us(),Q()},[Us]),ta=i.useCallback(()=>{Us(),ba()},[Us,ba]),ja=i.useCallback(()=>{Ie(!1),st(""),me(!1)},[]),Br=i.useCallback(async()=>{if(!$e.trim()){h("Please enter feedback describing what needs refinement","error");return}if($e.length>2e3){h("Feedback must be 2000 characters or less","error");return}me(!0);try{const Q=await Zj(e.id,$e.trim(),n);h(`Refinement task created: ${Q.id}`,"success"),gn()}catch(Q){h(Ee(Q),"error")}finally{me(!1)}},[e.id,$e,h,gn]),Ei=i.useCallback(async Q=>{P(!0);try{const Te=await bc(e.id,Q,n);O(_t=>[..._t,Te]),h("Screenshot attached","success")}catch(Te){h(Ee(Te),"error")}finally{P(!1)}},[e.id,h]),Na=i.useCallback(async Q=>{const Te=Q.target.files?.[0];Te&&(await Ei(Te),Ss.current&&(Ss.current.value=""))},[Ei]);i.useEffect(()=>{const Q=Te=>{const _t=Te.clipboardData?.items;if(_t)for(let Jt=0;Jt<_t.length;Jt++){const Qn=_t[Jt];if(Qn.type.startsWith("image/")){const Bi=Qn.getAsFile();if(Bi){Te.preventDefault(),Ei(Bi);return}}}};return document.addEventListener("paste",Q),()=>document.removeEventListener("paste",Q)},[Ei]);const Sa=i.useCallback(Q=>{Q.preventDefault()},[]),zi=i.useCallback(Q=>{Q.preventDefault();const Te=Q.dataTransfer.files;for(let _t=0;_t<Te.length;_t++){const Jt=Te[_t];if(Jt.type.startsWith("image/")){Ei(Jt);return}}},[Ei]),Qa=i.useCallback(async Q=>{try{await qj(e.id,Q,n),O(Te=>Te.filter(_t=>_t.filename!==Q)),h("Attachment deleted","info")}catch(Te){h(Ee(Te),"error")}},[e.id,h]),Ur=i.useCallback(async Q=>{const Te=Ns;Yn(Q);try{const _t=await Hs(e.id,{enabledWorkflowSteps:Q},n);h("Workflow steps updated","success"),m?.(_t)}catch(_t){Yn(Te),h(`Failed to update workflow steps: ${Ee(_t)}`,"error")}},[e.id,n,Ns,m,h]),Xa=i.useCallback(async()=>{L(!0);try{const Q=await $r(void 0,n);ie(Q),oe(!0)}catch(Q){h(`Failed to load agents: ${Ee(Q)}`,"error"),oe(!1)}finally{L(!1)}},[n,h]),Za=i.useCallback(async Q=>{try{const Te=await Qm(e.id,Q,n),_t=Y.find(Jt=>Jt.id===Q)??null;Ne(_t||(Jt=>Jt?.id===Q?Jt:null)),oe(!1),m?.(Te),h("Assigned agent updated","success")}catch(Te){h(`Failed to assign agent: ${Ee(Te)}`,"error")}},[e.id,n,Y,m,h]),er=i.useCallback(async()=>{try{const Q=await Qm(e.id,null,n);Ne(null),oe(!1),m?.(Q),h("Agent unassigned","success")}catch(Q){h(`Failed to unassign agent: ${Ee(Q)}`,"error")}},[e.id,n,m,h]),Hr=i.useCallback(async Q=>{const Te=[...$,Q];k(Te);try{await Hs(e.id,{dependencies:Te},n)}catch(_t){k($),h(Ee(_t),"error")}},[e.id,$,h]),Ye=i.useCallback(async(Q,Te)=>{Q.stopPropagation();const _t=$.filter(Jt=>Jt!==Te);k(_t);try{await Hs(e.id,{dependencies:_t},n)}catch(Jt){k($),h(Ee(Jt),"error")}},[e.id,$,h]),Tt=i.useCallback(async Q=>{try{const Te=await La(Q,n);a(Te)}catch{h(`Failed to load dependency ${Q}`,"error")}},[a,h]),cn=i.useCallback(async Q=>{fe(!0);try{await Hs(N.id,{prompt:Q},n),h("Spec updated","success"),S&&(S.prompt=Q)}catch(Te){throw h(Ee(Te),"error"),Te}finally{fe(!1)}},[N,S,h]),cs=i.useCallback(async Q=>{ve(!0);try{await Qj(e.id,Q,n),h("AI revision requested. Task moved to planning.","success"),gn()}catch(Te){const _t=Ee(Te);_t.includes("done")||_t.includes("archived")?h("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):h(_t,"error")}finally{ve(!1)}},[e.id,h,gn]),Hn=i.useCallback(()=>{ae(!0),Pe(N.prompt||""),Be("")},[N.prompt]),Cs=i.useCallback(()=>{ae(!1),Pe(N.prompt||""),Be("")},[N.prompt]),na=i.useCallback(async()=>{if(qe===(N.prompt||"")){Cs();return}ae(!1);try{await cn(qe)}catch(Q){throw ae(!0),Q}},[qe,N.prompt,cn,Cs]),H=i.useCallback(async()=>{nt.trim()&&await cs(nt.trim())},[nt,cs]),ze=i.useCallback(Q=>{Q.key==="Escape"?(Q.preventDefault(),Cs()):Q.key==="Enter"&&(Q.ctrlKey||Q.metaKey)&&(Q.preventDefault(),na())},[Cs,na]),Ge=s.filter(Q=>Q.id!==e.id&&!$.includes(Q.id)).sort((Q,Te)=>{const _t=Te.createdAt.localeCompare(Q.createdAt);if(_t!==0)return _t;const Jt=parseInt(Q.id.slice(Q.id.lastIndexOf("-")+1),10)||0;return(parseInt(Te.id.slice(Te.id.lastIndexOf("-")+1),10)||0)-Jt}),Nn=i.useMemo(()=>Ju(s),[s]).get(e.id),Vt=i.useMemo(()=>{if(!Nn)return[];const Q=new Set(Nn.staleBlockedByDependentIds);return Nn.dependentIds.map(Te=>{const _t=s.find(Jt=>Jt.id===Te);return{id:Te,label:_t?.title||_t?.description||Te,stale:Q.has(Te)}})},[Nn,s]),kn=xe?.name??e.assignedAgentId??null,Ze=i.useMemo(()=>{const Q=[];return N.modelProvider&&Q.push(N.modelProvider),N.validatorModelProvider&&!Q.includes(N.validatorModelProvider)&&Q.push(N.validatorModelProvider),N.planningModelProvider&&!Q.includes(N.planningModelProvider)&&Q.push(N.planningModelProvider),Q},[N.modelProvider,N.validatorModelProvider,N.planningModelProvider]),ot=ru[e.column]||[],Bt=["todo","in-progress"],In=e.column==="in-review"?Bt:ot,qn=In[0],ti=In.slice(1),Tn=ti.length>0,Vn=i.useCallback(()=>{ft(!1),wn.current?.focus()},[]),dn=i.useCallback(Q=>{if(!Tn){qn&&Ci(qn);return}const Te=Q.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(Q.target instanceof Element&&Q.target.closest(".detail-move-btn__arrow")||Te&&Q.clientX>0&&Q.clientX>=Te.getBoundingClientRect().left)){ft(Jt=>!Jt),zt(!1);return}qn&&Ci(qn)},[Tn,qn,Ci]),Gs=i.useCallback(Q=>{!Tn||!(Q.key==="ArrowDown"||Q.altKey&&Q.key==="ArrowDown")||(Q.preventDefault(),ft(!0),zt(!1))},[Tn]),Ps=i.useCallback(Q=>{Q.key==="Escape"&&(Q.preventDefault(),Q.stopPropagation(),Vn())},[Vn]);i.useEffect(()=>{if(!De)return;Un.current?.querySelector(".detail-move-menu-item")?.focus()},[De]);const fi={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…","merging-fix":"Merging fixes…"},Ca=e.status?fi[e.status]:void 0,qr=xn?.mergeStrategy??"direct",sy=xn?.autoMerge??!1,wm=qr==="pull-request"&&!sy;let Yo="Merge & Close";return wm&&!Ca&&(e.prInfo?e.prInfo.status==="open"?Yo="Check PR Status":e.prInfo.status==="merged"&&(Yo="Finish & Close"):Yo="Start PR Review"),t.jsxs("div",{className:x?"task-detail-content task-detail-content--embedded":"task-detail-content",onDragOver:Sa,onDrop:zi,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx("span",{className:"detail-id",children:e.id}),t.jsx("span",{className:`detail-column-badge badge-${e.column}`,children:ds[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!re&&ws&&t.jsx("button",{className:"modal-edit-btn",onClick:It,title:"Edit task","aria-label":"Edit task",children:t.jsx(qs,{size:14})}),!x&&g==="back"&&t.jsxs("button",{className:"modal-close task-detail-mobile-back",onClick:gn,"aria-label":"Back to task list",type:"button",children:[t.jsx(Ha,{"aria-hidden":"true"}),t.jsx("span",{children:"Back"})]}),!x&&g!=="back"&&t.jsx("button",{className:"modal-close",onClick:gn,"aria-label":"Close",type:"button",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&R==="agent-log"&&!re?" detail-body--agent-log":""}`,children:[re?t.jsx("div",{className:"modal-edit-form",children:t.jsx(lv,{mode:"edit",title:xt,onTitleChange:ut,description:Qe,onDescriptionChange:vt,dependencies:Ae,onDependenciesChange:Je,branch:dt,onBranchChange:Nt,baseBranch:yt,onBaseBranchChange:Se,executorModel:G,onExecutorModelChange:ge,validatorModel:pt,onValidatorModelChange:ke,planningModel:tt,onPlanningModelChange:Rt,thinkingLevel:Re,onThinkingLevelChange:be,presetMode:rt,onPresetModeChange:lt,selectedPresetId:Gt,onSelectedPresetIdChange:on,selectedWorkflowSteps:sn,onWorkflowStepsChange:ln,pendingImages:bt,onImagesChange:Dt,tasks:s.filter(Q=>Q.id!==e.id),projectId:n,disabled:Ft,addToast:h,isActive:re,onAutoSaveDescription:os,reviewLevel:gt,onReviewLevelChange:St,priority:Lt,onPriorityChange:Yt,nodeId:tn,onNodeIdChange:mn,nodeOptions:ls,nodeOverrideDisabled:ys,nodeOverrideDisabledReason:ys?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Qt,onExecutionModeChange:yn,renderBelowModelConfiguration:t.jsxs("div",{className:"form-group detail-source-edit-group",children:[t.jsx("label",{children:"Source Issue"}),t.jsxs("div",{className:"detail-source-edit-grid",children:[t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Provider (e.g. github)",value:Wt,onChange:Q=>ye(Q.target.value),disabled:Ft,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Le,onChange:Q=>Ke(Q.target.value),disabled:Ft,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:mt,onChange:Q=>Ve(Q.target.value),disabled:Ft,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:Pt,onChange:Q=>Ot(Q.target.value),disabled:Ft,"data-testid":"task-source-url-input"})]}),t.jsx("small",{children:"Leave all fields empty to clear source issue metadata."})]})})}):t.jsxs(t.Fragment,{children:[(()=>{const Q=e.title||e.description||e.id,Te=!K&&Q.length>Nd;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Te?Q.slice(0,Nd)+"…":Q}),Q.length>Nd&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>Z(!K),children:K?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:[t.jsxs("div",{className:"detail-meta-inline-controls","data-testid":"detail-meta-inline-controls",children:[t.jsxs("label",{className:`card-priority-badge card-priority-badge--${rn} detail-priority-chip ${an?"detail-priority-chip--saving":""}`,children:[t.jsx("span",{children:"Priority:"}),t.jsx("select",{className:"detail-priority-select",value:rn,onChange:Q=>{ns(Q.target.value)},disabled:an,"aria-label":"Task priority",children:pa.map(Q=>t.jsx("option",{value:Q,children:Q},Q))})]}),t.jsxs("button",{type:"button",className:`btn btn-sm detail-execution-mode-toggle ${it==="fast"?"detail-execution-mode-toggle--fast":""} ${$t?"detail-execution-mode-toggle--saving":""}`,onClick:()=>{Zn()},disabled:$t,"aria-label":`Execution mode: ${it}`,"aria-pressed":it==="fast",children:[t.jsx(as,{"aria-hidden":"true"}),t.jsx("span",{children:it==="fast"?"Fast":"Standard"})]})]}),U&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Fs,{"aria-hidden":"true"}),t.jsxs("span",{children:[N.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",U.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>z(U.sourceAgentId),children:U.label}):U.label]}):t.jsxs(t.Fragment,{children:["Created via ",U.label]}),U.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>Tt(U.parentTaskId),children:U.parentTaskId})]}),U.contextInfo?` (${U.contextInfo})`:""]})]}),(e.prInfo?.number||e.mergeDetails?.prNumber)&&t.jsxs("div",{className:"detail-provenance detail-pr-link-row",children:[t.jsx(Fs,{"aria-hidden":"true"}),t.jsxs("span",{children:["PR"," ",e.prInfo?.url?t.jsxs("a",{className:"detail-provenance-link",href:e.prInfo.url,target:"_blank",rel:"noopener noreferrer",children:["#",e.prInfo.number]}):t.jsxs("span",{children:["#",e.prInfo?.number??e.mergeDetails?.prNumber]})]})]}),t.jsxs("div",{className:"detail-timestamps","aria-label":"Task timestamps",children:[t.jsxs("span",{className:"detail-timestamp-item",children:[t.jsx("span",{className:"detail-timestamp-label",children:"Created"})," ",t.jsx("time",{dateTime:e.createdAt,title:new Date(e.createdAt).toLocaleString(),children:yd(e.createdAt)})]}),t.jsx("span",{className:"detail-timestamp-separator","aria-hidden":"true",children:"·"}),t.jsxs("span",{className:"detail-timestamp-item",children:[t.jsx("span",{className:"detail-timestamp-label",children:"Updated"})," ",t.jsx("time",{dateTime:e.updatedAt,title:new Date(e.updatedAt).toLocaleString(),children:yd(e.updatedAt)})]})]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!re&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>y("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${b==="logs"?" detail-tab-active":""}`,onClick:()=>y("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${b==="changes"?" detail-tab-active":""}`,onClick:()=>y("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${b==="review"?" detail-tab-active":""}`,onClick:()=>y("review"),children:"Review"}),t.jsx("button",{className:`detail-tab${b==="comments"?" detail-tab-active":""}`,onClick:()=>y("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${b==="documents"?" detail-tab-active":""}`,onClick:()=>y("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${b==="model"?" detail-tab-active":""}`,onClick:()=>y("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${b==="workflow"?" detail-tab-active":""}`,onClick:()=>y("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${b==="stats"?" detail-tab-active":""}`,onClick:()=>y("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${b==="routing"?" detail-tab-active":""}`,onClick:()=>y("routing"),children:"Routing"}),Ut.map(({entry:Q,tabId:Te})=>t.jsx("button",{className:`detail-tab${b===Te?" detail-tab-active":""}`,onClick:()=>y(Te),children:Q.slot.label},`plugin-tab-${Q.pluginId}-${Te}`))]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(sP,{taskId:e.id,results:ms,loading:Jn,enabledWorkflowSteps:Ns,canEdit:ws,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Ur})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(PT,{task:e,addToast:h,onTaskUpdated:m,settings:xn})}):b==="logs"?t.jsxs("div",{className:`detail-section${R==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${R==="activity"?" log-subview-btn-active":""}`,onClick:()=>D("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${R==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>D("agent-log"),children:"Agent Log"})]}),R==="agent-log"?t.jsx(MT,{entries:Si,loading:ga,executorModel:gP(e,Si,xe,xn),validatorModel:bP(e,Si,xe,xn),planningModel:vP(e,Si,xn),hasMore:Ka,onLoadMore:Wa,loadingMore:oi,totalCount:Ga}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),N.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",N.log.length," activity entries."]}):null,N.log&&N.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...N.log].reverse().map((Q,Te)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:yd(Q.timestamp)}),t.jsx("span",{className:"detail-log-action",children:Q.action})]}),Q.outcome&&t.jsx("div",{className:"detail-log-outcome",children:Q.outcome})]},Te))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(GT,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="review"?t.jsx(HT,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="comments"?t.jsx(FT,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="documents"?t.jsx(uP,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:ws}):xs?t.jsx("div",{className:"detail-section",children:t.jsx(la,{slotId:"task-detail-tab",projectId:n,pluginIds:[xs.entry.pluginId]})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(hP,{tokenUsage:N.tokenUsage,loading:C,task:N})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(oP,{task:e,settings:xn,addToast:h,onTaskUpdated:m})}):t.jsxs(t.Fragment,{children:[e.column==="done"&&e.summary&&t.jsxs("div",{className:"detail-section detail-summary",children:[t.jsx("h4",{children:"Summary"}),t.jsx("div",{className:"markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],children:e.summary})})]}),t.jsx(VT,{task:e}),e.sourceIssue&&t.jsxs("div",{className:"detail-section detail-source-section",children:[t.jsxs("div",{className:"detail-source-header",children:[t.jsxs("div",{className:"detail-source-summary",children:[t.jsx("span",{className:"detail-source-label",children:"Source issue"}),e.sourceIssue.provider.toLowerCase()==="github"&&t.jsxs("span",{className:"detail-source-provider-badge","aria-label":"GitHub source issue",children:[t.jsx(Fs,{"aria-hidden":"true"}),t.jsx("span",{children:"GitHub"})]}),e.sourceIssue.url?t.jsx("a",{className:"detail-source-link detail-source-link--summary detail-source-number",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:`(#${e.sourceIssue.issueNumber})`}):t.jsx("span",{className:"detail-source-number",children:`(#${e.sourceIssue.issueNumber})`})]}),t.jsx("button",{type:"button",className:"detail-source-toggle","aria-expanded":Pn,"aria-label":Pn?"Collapse source issue details":"Expand source issue details",onClick:()=>he(Q=>!Q),children:t.jsx(On,{size:16,className:Pn?"detail-source-chevron--expanded":void 0})})]}),Pn&&t.jsxs("dl",{className:"detail-source-grid",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Provider"}),t.jsx("dd",{children:e.sourceIssue.provider})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Repository"}),t.jsx("dd",{children:e.sourceIssue.repository})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Issue Identifier"}),t.jsx("dd",{children:e.sourceIssue.externalIssueId})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"URL"}),t.jsx("dd",{children:e.sourceIssue.url?t.jsx("a",{className:"detail-source-link",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:e.sourceIssue.url}):t.jsx("span",{className:"detail-source-empty",children:"(none)"})})]})]})]}),ue&&t.jsxs("div",{className:"detail-section detail-github-tracking-section",children:[t.jsxs("div",{className:"detail-source-header",children:[t.jsxs("div",{className:"detail-source-summary",children:[t.jsx("span",{className:"detail-source-label",children:"GitHub tracking"}),t.jsxs("span",{className:"detail-source-provider-badge","aria-label":"GitHub tracking status",children:[t.jsx(Fs,{"aria-hidden":"true"}),t.jsx("span",{children:Ce})]}),!E&&t.jsx("span",{className:"detail-source-empty",children:X?"Issue not yet created":"Tracking is currently disabled"})]}),t.jsx("button",{type:"button",className:"detail-source-toggle","aria-expanded":ht,"aria-label":ht?"Collapse GitHub tracking details":"Expand GitHub tracking details",onClick:()=>at(Q=>!Q),children:t.jsx(On,{size:16,className:ht?"detail-source-chevron--expanded":void 0})})]}),ht&&t.jsxs("div",{className:"detail-github-tracking-content",children:[E&&t.jsxs("dl",{className:"detail-source-grid detail-github-tracking-grid",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Issue"}),t.jsx("dd",{children:E.url?t.jsx("a",{className:"detail-source-link",href:E.url,target:"_blank",rel:"noopener noreferrer",children:`${E.owner}/${E.repo}#${E.number}`}):t.jsx("span",{children:`${E.owner}/${E.repo}#${E.number}`})})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"State"}),t.jsx("dd",{children:t.jsx("span",{className:`detail-github-issue-state ${e.issueInfo?.state==="closed"?"detail-github-issue-state--closed":"detail-github-issue-state--open"}`,children:e.issueInfo?.state??"open"})})]})]}),t.jsxs("div",{className:"detail-github-tracking-controls",children:[!E&&X&&t.jsx("button",{className:"btn btn-sm touch-target",onClick:()=>void Oe(),disabled:nn,children:"Create tracking issue"}),Ms&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"checkbox-label",htmlFor:"detail-github-tracking-toggle",children:[t.jsx("input",{id:"detail-github-tracking-toggle",type:"checkbox",checked:X,disabled:nn,onChange:()=>void q()}),"Enable GitHub tracking"]}),t.jsxs("div",{className:"detail-github-tracking-repo-row",children:[t.jsx("input",{className:"input",value:wt,onChange:Q=>{Xe(Q.target.value),ct(null)},placeholder:We||"owner/repo"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void we(),disabled:nn,children:"Save"})]}),le&&t.jsx("small",{className:"detail-github-tracking-error",children:le}),E&&t.jsx("button",{className:"btn btn-sm touch-target",onClick:()=>void Zs(),disabled:nn,children:"Unlink GitHub issue"})]})]})]})]}),t.jsx("div",{className:"detail-section detail-agent-section",children:t.jsxs("div",{className:"detail-meta-row",children:[t.jsxs("div",{className:"detail-meta-left",children:[Ze.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:Ze.map(Q=>t.jsx(Fn,{provider:Q,size:"sm"},Q))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(Kn,{size:14,className:"detail-meta-label-icon"}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[kn?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(Kn,{size:14}),kn,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void er(),title:"Unassign agent",children:t.jsx(un,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{ee?oe(!1):Xa()},children:"Assign Agent"}),ee&&t.jsxs("div",{className:"agent-picker-dropdown",children:[W&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!W&&Y.map(Q=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===Q.id?" selected":""}`,onClick:()=>void Za(Q.id),children:[t.jsx(Kn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:Q.name}),t.jsx("span",{className:"agent-picker-role",children:Q.role})]},Q.id)),!W&&Y.length===0&&t.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),t.jsxs("div",{className:"detail-section detail-step-progress",children:[t.jsx("h4",{children:"Progress"}),N.steps&&N.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:N.steps.map((Q,Te)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${Q.status}`,"data-tooltip":`${Q.name} (${Q.status})`,style:{backgroundColor:yP(Q.status)}},Te))}),t.jsxs("span",{className:"step-progress-label",children:[N.steps.filter(Q=>Q.status==="done").length,"/",N.steps.length," step",N.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!Fe&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:Hn,children:"Edit"})}),Fe?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:qe,onChange:Q=>Pe(Q.target.value),onKeyDown:ze,disabled:pe,placeholder:"Enter task specification in Markdown...",rows:12}),t.jsxs("div",{className:"spec-editor-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:Cs,disabled:pe,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void na(),disabled:qe===(N.prompt||"")||pe,children:pe?"Saving…":"Save"})]}),t.jsxs("div",{className:"spec-editor-hint",children:[t.jsx("kbd",{children:"Ctrl"}),"+",t.jsx("kbd",{children:"Enter"})," to save · ",t.jsx("kbd",{children:"Escape"})," to cancel"]}),t.jsxs("div",{className:"spec-editor-revision",children:[t.jsx("h4",{children:"Ask AI to Revise"}),t.jsx("p",{className:"spec-editor-revision-help",children:"Provide feedback for the AI to improve this specification. The task will move to planning for replanning."}),t.jsx("textarea",{className:"spec-editor-feedback",value:nt,onChange:Q=>Be(Q.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:B,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[nt.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void H(),disabled:!nt.trim()||B,children:B?"Requesting…":"Request AI Revision"})]})]})]}):C?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):N.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],children:N.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),ne.length>0?t.jsx("div",{className:"detail-attachments-grid",children:ne.map(Q=>{const Te=Di(`/api/tasks/${e.id}/attachments/${Q.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:Te,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:Te,alt:Q.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[Q.originalName," (",wP(Q.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>Qa(Q.filename),title:"Delete attachment",children:"×"})]},Q.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:Ss,type:"file",accept:"image/*",onChange:Na}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Ss.current?.click(),disabled:A,children:A?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),$.length>0?t.jsx("ul",{className:"detail-dep-list",children:$.map(Q=>{const Te=s.find(Jt=>Jt.id===Q),_t=Te?.title||Te?.description||Q;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Tt(Q),onKeyDown:Jt=>{(Jt.key==="Enter"||Jt.key===" ")&&(Jt.preventDefault(),Tt(Q))},role:"link",tabIndex:0,title:`Click to view ${Q}`,children:[t.jsx("span",{className:"detail-dep-id",children:Q}),t.jsx("span",{className:"detail-dep-label",children:wd(_t,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Jt=>Ye(Jt,Q),title:`Remove dependency ${Q}`,children:"×"})]},Q)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no dependencies)"}),t.jsxs("div",{className:"dep-trigger-wrap",children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{J&&He(""),ce(Q=>!Q)},children:"Add Dependency"}),J&&(()=>{const Q=je.toLowerCase(),Te=Q?Ge.filter(_t=>_t.id.toLowerCase().includes(Q)||_t.title&&_t.title.toLowerCase().includes(Q)||_t.description&&_t.description.toLowerCase().includes(Q)):Ge;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:je,onChange:_t=>He(_t.target.value),onClick:_t=>_t.stopPropagation()}),Te.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Te.map(_t=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{Hr(_t.id),ce(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:_t.id}),t.jsx("span",{className:"dep-dropdown-title",children:wd(_t.title||_t.description||_t.id,30)})]},_t.id))]})})()]})]}),t.jsxs("div",{className:"detail-deps detail-blocking",children:[t.jsx("h4",{children:"Blocking"}),Vt.length>0?t.jsx("ul",{className:"detail-dep-list",children:Vt.map(Q=>t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Tt(Q.id),onKeyDown:Te=>{(Te.key==="Enter"||Te.key===" ")&&(Te.preventDefault(),Tt(Q.id))},role:"link",tabIndex:0,title:`Click to view ${Q.id}`,children:[t.jsx("span",{className:"detail-dep-id",children:Q.id}),t.jsx("span",{className:"detail-dep-label",children:wd(Q.label,40)})]}),Q.stale&&t.jsx("span",{className:"detail-blocking-item--stale",title:"Stale blockedBy edge: self-healing clearStaleBlockedBy should clear this automatically",children:"(stale)"})]},Q.id))}):t.jsx("div",{className:"detail-empty-inline",children:"(no downstream tasks blocked)"})]}),e.column==="in-review"&&t.jsx("div",{className:"detail-section detail-pr-section",children:t.jsx(DT,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:xn?.autoMerge??!1,isManualPrFlow:wm,prAuthAvailable:f??!1,onPrCreated:Q=>{e.prInfo=Q},onPrUpdated:Q=>{e.prInfo=Q},addToast:h})})]})]})]}),t.jsx("div",{className:"modal-actions",children:re?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"modal-edit-hint",children:fn==="saving"?"Autosaving…":fn==="saved"?"Saved":fn==="error"?"Save failed":"Changes autosave as you edit"}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:Kt,disabled:Ft,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void fs(),disabled:Ft,children:Ft?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&N.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ya,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:wa,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!I&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:ea,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||I||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:rs,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{zt(Q=>!Q),ft(!1)},"aria-haspopup":"menu","aria-expanded":qt,children:["Actions",t.jsx(pn,{size:12})]}),qt&&t.jsxs("div",{className:"detail-actions-menu",role:"menu",children:[t.jsx("button",{className:"detail-actions-menu-item detail-actions-menu-item-danger",role:"menuitem",onClick:()=>ei(ea),children:"Delete"}),u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ei(va),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ei(ka),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ei(zr),children:"Respecify"}),I&&c&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ei(Ja),children:"Retry"}),d&&e.column!=="done"&&e.column!=="archived"&&t.jsx("button",{className:"detail-actions-menu-item detail-actions-menu-item-danger",role:"menuitem",onClick:()=>ei(xa),children:"Reset"}),e.column!=="done"&&!e.assignedAgentId&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ei(ya),children:e.paused?"Unpause":"Pause"}),e.column!=="done"&&e.paused&&e.pausedByAgentId&&t.jsx("span",{className:"detail-actions-menu-item detail-actions-menu-note",role:"note",children:"Paused by agent"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:Un,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:wn,className:"btn btn-primary btn-sm detail-move-btn",onClick:dn,onKeyDown:Gs,disabled:!qn,"aria-label":qn?`Move to ${ds[qn]}`:void 0,"aria-haspopup":Tn?"menu":void 0,"aria-expanded":Tn?De:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",qn?ds[qn]:""]}),Tn&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(pn,{size:12})})]}),De&&Tn&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Ps,children:ti.map(Q=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Ci(Q),onKeyDown:Ps,children:Q==="in-progress"?"Back to In Progress":`Move to ${ds[Q]}`},Q))})]}),Ca?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:Ca}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:ta,children:Yo})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:wn,className:"btn btn-primary btn-sm detail-move-btn",onClick:dn,onKeyDown:Gs,disabled:!qn,"aria-label":qn?`Move to ${ds[qn]}`:void 0,"aria-haspopup":Tn?"menu":void 0,"aria-expanded":Tn?De:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",qn?ds[qn]:""]}),Tn&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(pn,{size:12})})]}),De&&Tn&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Ps,children:ti.map(Q=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Ci(Q),onKeyDown:Ps,children:["Move to ",ds[Q]]},Q))})]})})]})}),de&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:ja,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:Q=>Q.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{className:"detail-refine-title",children:"Refine"}),t.jsx("button",{className:"modal-close",onClick:ja,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"detail-body",children:[t.jsx("p",{className:"detail-refine-help",children:"Describe what needs to be refined or improved..."}),t.jsx("textarea",{className:"detail-refine-textarea",value:$e,onChange:Q=>st(Q.target.value),placeholder:"Enter your feedback here...",rows:6,maxLength:2e3,autoFocus:!0}),t.jsxs("div",{className:"detail-refine-input-group",children:[t.jsxs("div",{className:"detail-refine-char-count",children:[$e.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Br,disabled:!$e.trim()||Ue,children:Ue?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:ja,disabled:Ue,children:"Cancel"})})]})}),M&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(SP,{agentId:M,projectId:n,onClose:()=>z(null),addToast:h})})]})}function MP({onClose:e,...n}){const s=i.useRef(null);Li(s,!0,"task-detail-modal-size"),Ni(!0);const a=Qi(e);return t.jsx("div",{className:"modal-overlay open",...a,role:"dialog","aria-modal":"true",children:t.jsx("div",{className:"modal modal-lg task-detail-modal",ref:s,children:t.jsx(dv,{...n,onRequestClose:e})})})}const fl={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Qp=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function Xp(e){return e==="merging-fix"?"Merging fixes…":e}const uv=["title","status","column","dependencies","progress"],AP=["title","status","column"];function RP(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function IP(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function Zp(e){try{const n=zn("kb-dashboard-list-columns",e);if(n){const a=JSON.parse(n).filter(r=>uv.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set(AP)}function ef(e){try{const n=zn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function tf(e){try{const n=zn("kb-dashboard-list-collapsed",e);if(n){const a=JSON.parse(n).filter(r=>oa.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set}function nf(e){try{const n=zn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function sf(e){try{const n=zn("kb-dashboard-list-selected-task",e);if(typeof n=="string"&&n.trim().length>0)return n}catch{}return null}function af(e){try{const s=zn("kb-dashboard-list-sidebar-width",e);if(!s)return 400;const a=Number(s);if(Number.isFinite(a)&&a>0)return a}catch{}return 400}const Zl=280,ku=.65,gl=16;function ju(e){return Math.max(Zl,e*ku)}function bl(e,n){const s=ju(n);return Math.min(Math.max(e,Zl),s)}function TP(e){return e.status==="executing"||e.column==="in-progress"}function rf(e){const n=Lb(e);return n.total===0||!TP(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function PP({tasks:e,onMoveTask:n,onRetryTask:s,onDeleteTask:a,onMergeTask:r,onResetTask:o,onDuplicateTask:l,onOpenDetail:c,addToast:d,globalPaused:u,onNewTask:m,onQuickCreate:h,availableModels:f,favoriteProviders:p=[],favoriteModels:g=[],onToggleFavorite:x,onToggleModelFavorite:w,onPlanningMode:b,onSubtaskBreakdown:y,onTasksUpdated:S,projectId:j,projectName:C,taskStuckTimeoutMs:v,searchQuery:N="",lastFetchTimeMs:I,prAuthAvailable:F}){const[_,M]=i.useState(null),[z,U]=i.useState("asc"),[R,D]=i.useState(null),[K,Z]=i.useState(null),[ne,O]=i.useState(null),P=ri()==="mobile",{confirm:$}=pi(),[k,J]=i.useState(()=>Zp(j)),[ce,je]=i.useState(()=>ef(j)),[He,xe]=i.useState(()=>tf(j));i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-list-columns",JSON.stringify([...k]),j)},[j,k]),i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-hide-done",ce.toString(),j)},[ce,j]),i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-list-collapsed",JSON.stringify([...He]),j)},[He,j]);const[Ne,Y]=i.useState(!1),[ie,ee]=i.useState(!1),[oe,W]=i.useState(()=>nf(j)),[L,pe]=i.useState(()=>sf(j)),[fe,B]=i.useState(null),[ve,Fe]=i.useState(()=>af(j)),ae=i.useRef(null),qe=i.useRef(null);i.useEffect(()=>{J(Zp(j)),je(ef(j)),xe(tf(j)),W(nf(j));const ye=sf(j);pe(ye),B(ye?e.find(Le=>Le.id===ye)??null:null),Fe(af(j))},[j,e]),i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-selected-tasks",JSON.stringify([...oe]),j)},[j,oe]),i.useEffect(()=>{if(!(typeof window>"u")){if(L){us("kb-dashboard-list-selected-task",L,j);return}Nr("kb-dashboard-list-selected-task",j)}},[j,L]),i.useEffect(()=>{if(!L){B(null);return}const ye=e.find(Le=>Le.id===L);ye&&B(Le=>!Le||Le.id!==L?ye:{...Le,...ye})},[L,e]),i.useEffect(()=>{if(P||typeof ResizeObserver>"u")return;const ye=ae.current;if(!ye)return;const Le=()=>{const mt=bl(ve,ye.clientWidth);mt!==ve&&Fe(mt)};Le();const Ke=new ResizeObserver(Le);return Ke.observe(ye),()=>Ke.disconnect()},[P,ve]),i.useEffect(()=>{if(P||typeof ResizeObserver>"u")return;const ye=qe.current,Le=ae.current;if(!ye||!Le)return;let Ke=null,mt=ye.offsetWidth;const Ve=new ResizeObserver(()=>{const Pt=bl(ye.offsetWidth,Le.clientWidth);Pt!==mt&&(mt=Pt,Ke&&clearTimeout(Ke),Ke=setTimeout(()=>{try{us("kb-dashboard-list-sidebar-width",String(Pt),j)}catch{}},200))});return Ve.observe(ye),()=>{Ve.disconnect(),Ke&&clearTimeout(Ke)}},[P,j]);const Pe=i.useCallback(()=>{ee(ye=>(ye&&W(new Set),!ye))},[]),nt=i.useCallback(ye=>{W(Le=>{const Ke=new Set(Le);return Ke.has(ye)?Ke.delete(ye):Ke.add(ye),Ke})},[]),Be=i.useCallback(()=>{W(new Set)},[]),de=i.useCallback(ye=>{J(Le=>{const Ke=new Set(Le);return Ke.has(ye)?Ke.size>1&&Ke.delete(ye):Ke.add(ye),Ke})},[]),Ie={title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},$e=i.useCallback(ye=>{if(_===ye){U(Le=>Le==="asc"?"desc":"asc");return}M(ye),U("asc")},[_]),st=i.useCallback(ye=>{O(Le=>Le===ye?null:ye)},[]),Ue=i.useCallback(ye=>{xe(Le=>{const Ke=new Set(Le);return Ke.has(ye)?Ke.delete(ye):Ke.add(ye),Ke})},[]),me=i.useCallback(()=>{O(null)},[]),re=i.useMemo(()=>{let ye=N?e.filter(mt=>mt.id.toLowerCase().includes(N.toLowerCase())||mt.title&&mt.title.toLowerCase().includes(N.toLowerCase())||mt.description.toLowerCase().includes(N.toLowerCase())):[...e];ce&&!ne&&(ye=ye.filter(mt=>mt.column!=="done"&&mt.column!=="archived"));const Le=ne?ye.filter(mt=>mt.column===ne):ye,Ke={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};Le.forEach(mt=>{const Ve=Vu(mt.column)?mt.column:Wl;Ke[Ve].push(mt)});for(const mt of oa){if(!_){Ke[mt]=Ib(Ke[mt],mt);continue}Ke[mt]=[...Ke[mt]].sort((Ve,Pt)=>{let Ot=0;switch(_){case"title":Ot=(Ve.title||Ve.description).localeCompare(Pt.title||Pt.description);break;case"status":Ot=(Ve.status||"").localeCompare(Pt.status||"");break;case"column":Ot=Ve.column.localeCompare(Pt.column);break}return z==="asc"?Ot:-Ot})}return Ke},[e,N,_,z,ce,ne]),_e=i.useMemo(()=>Object.values(re).reduce((ye,Le)=>ye+Le.length,0),[re]),xt=i.useMemo(()=>e.filter(ye=>ye.column==="done"||ye.column==="archived").length,[e]),ut=i.useMemo(()=>ce?xt:0,[ce,xt]),Qe=i.useCallback(()=>{const ye=Object.values(re).flat().filter(Le=>Le.column!=="archived").map(Le=>Le.id);W(Le=>{if(ye.every(mt=>Le.has(mt))){const mt=new Set(Le);return ye.forEach(Ve=>mt.delete(Ve)),mt}else return new Set([...Le,...ye])})},[re]),vt=i.useMemo(()=>{const ye=Object.values(re).flat().filter(Le=>Le.column!=="archived");return ye.length===0?!1:ye.every(Le=>oe.has(Le.id))},[re,oe]),Ae=i.useMemo(()=>{const ye=Object.values(re).flat().filter(Ke=>Ke.column!=="archived");if(ye.length===0)return!1;const Le=ye.filter(Ke=>oe.has(Ke.id)).length;return Le>0&&Le<ye.length},[re,oe]),[Je,dt]=i.useState("__no_change__"),[Nt,yt]=i.useState("__no_change__"),[Se,G]=i.useState("__no_change__"),[ge,pt]=i.useState([]),[ke,tt]=i.useState(!1),Rt=i.useMemo(()=>Se&&Se!=="__no_change__"?ge.find(ye=>ye.id===Se):void 0,[ge,Se]),[Re,be]=i.useState(!1);i.useEffect(()=>{if(oe.size===0)return;let ye=!1;return(async()=>{tt(!0);try{const Ke=await ql();ye||pt(Ke)}catch(Ke){console.error("Failed to fetch nodes for bulk edit",Ke),ye||pt([])}finally{ye||tt(!1)}})(),()=>{ye=!0}},[oe.size]);const rt=i.useCallback(async()=>{if(oe.size===0)return;const ye=Array.from(oe).map(bt=>e.find(Dt=>Dt.id===bt)).filter(bt=>!!bt),Le=ye.filter(bt=>bt.column==="archived"),Ke=ye.filter(bt=>bt.column!=="archived");if(Ke.length===0){d("No selected tasks can be deleted (archived tasks are excluded)","error");return}if(!await $({title:"Delete Selected Tasks",message:`Delete ${Ke.length} selected task${Ke.length===1?"":"s"}?`,confirmLabel:"Delete",cancelLabel:"Cancel",danger:!0}))return;be(!0);const Ve=[],Pt=[],Ot=Le.map(bt=>bt.id);try{for(const bt of Ke)try{await a(bt.id),Ve.push(bt.id)}catch(Dt){const Ft=Ku(Dt);if(!Ft){Pt.push(bt.id);continue}if(!await $({title:"Force Delete Task",message:`Task ${bt.id} has dependents: ${Ft.dependentIds.join(", ")}. Remove dependency references and force delete?`,confirmLabel:"Force Delete",cancelLabel:"Skip",danger:!0})){Pt.push(bt.id);continue}try{await a(bt.id,{removeDependencyReferences:!0}),Ve.push(bt.id)}catch{Pt.push(bt.id)}}}finally{be(!1)}Ve.length>0&&W(bt=>{const Dt=new Set(bt);for(const Ft of Ve)Dt.delete(Ft);return Dt}),d(`Deleted ${Ve.length} task${Ve.length===1?"":"s"} · ${Ot.length} archived skipped · ${Pt.length} failed`,Pt.length>0?"error":"success")},[d,$,a,oe,e]),lt=i.useCallback(async()=>{if(oe.size===0)return;const ye=Array.from(oe).filter(Ke=>{const mt=e.find(Ve=>Ve.id===Ke);return mt&&mt.column!=="archived"});if(ye.length===0){d("No valid tasks to update (archived tasks cannot be modified)","error");return}const Le={taskIds:ye};if(Je!=="__no_change__")if(Je==="")Le.modelProvider=null,Le.modelId=null;else{const Ke=Je.indexOf("/");Ke!==-1&&(Le.modelProvider=Je.slice(0,Ke),Le.modelId=Je.slice(Ke+1))}if(Nt!=="__no_change__")if(Nt==="")Le.validatorModelProvider=null,Le.validatorModelId=null;else{const Ke=Nt.indexOf("/");Ke!==-1&&(Le.validatorModelProvider=Nt.slice(0,Ke),Le.validatorModelId=Nt.slice(Ke+1))}if(Se!=="__no_change__"&&(Se===""?Le.nodeId=null:Le.nodeId=Se),Object.keys(Le).length===1){d("No changes to apply","info");return}be(!0);try{const Ke=await Mj(Le.taskIds,Le.modelProvider,Le.modelId,Le.validatorModelProvider,Le.validatorModelId,void 0,void 0,Le.nodeId,j);S&&S(Ke.updated),d(`Updated ${ye.length} task${ye.length===1?"":"s"}`,"success"),Be(),dt("__no_change__"),yt("__no_change__"),G("__no_change__")}catch(Ke){d(Ee(Ke)||"Failed to update models","error")}finally{be(!1)}},[oe,e,Je,Nt,Se,j,d,Be,S]),gt=i.useCallback(ye=>{if(P){c(ye,{origin:"list-mobile"});return}pe(ye.id),B(ye)},[P,c]),St=i.useRef(null),Lt=i.useRef(null);i.useEffect(()=>()=>{St.current&&clearTimeout(St.current)},[]);const Yt=i.useCallback(ye=>{if(pe(ye.id),B(ye),"prompt"in ye){Lt.current=null,St.current&&(clearTimeout(St.current),St.current=null);return}Lt.current=ye.id,St.current&&clearTimeout(St.current),St.current=setTimeout(()=>{St.current=null,Lt.current===ye.id&&La(ye.id,j).then(Ke=>{Lt.current===Ke.id&&B(mt=>!mt||mt.id!==Ke.id?mt:{...mt,...Ke})}).catch(()=>{})},200)},[j]),tn=i.useCallback((ye,Le)=>{if(Le.paused){ye.preventDefault();return}ye.dataTransfer.setData("text/plain",Le.id),ye.dataTransfer.effectAllowed="move",D(Le.id)},[]),mn=i.useCallback(()=>{D(null),Z(null)},[]),Qt=i.useCallback(ye=>{if(P)return;ye.preventDefault();const Le=ae.current;if(!Le)return;const Ke=Le.getBoundingClientRect(),mt=Pt=>{const Ot=Pt.clientX-Ke.left;Fe(bl(Ot,Ke.width))},Ve=()=>{window.removeEventListener("mousemove",mt),window.removeEventListener("mouseup",Ve)};window.addEventListener("mousemove",mt),window.addEventListener("mouseup",Ve)},[P]),yn=i.useCallback(ye=>{if(P)return;const Le=ae.current?.clientWidth??0,Ke=ve/ku+gl,mt=Math.max(Le,Ke),Ve=ju(mt);if(ye.key==="ArrowLeft"||ye.key==="ArrowRight"){ye.preventDefault();const Pt=ye.key==="ArrowLeft"?-gl:gl;Fe(Ot=>bl(Ot+Pt,mt));return}if(ye.key==="Home"){ye.preventDefault(),Fe(Zl);return}ye.key==="End"&&(ye.preventDefault(),Fe(Ve))},[P,ve]),Gt=i.useCallback((ye,Le)=>{ye.preventDefault(),ye.dataTransfer.dropEffect="move",Z(Le)},[]),on=i.useCallback(()=>{Z(null)},[]),sn=i.useCallback(async(ye,Le)=>{ye.preventDefault(),Z(null);const Ke=ye.dataTransfer.getData("text/plain");if(Ke){if(Le==="archived"){d("Tasks can only be archived via the archive button","error");return}try{const Ve=e.find(bt=>bt.id===Ke)?.steps.some(bt=>bt.status!=="pending")??!1,Pt=(Le==="todo"||Le==="triage")&&Ve;let Ot;if(Pt){if(await $({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Ot={preserveProgress:!0};else if(!await $({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await n(Ke,Le,Ot)}catch(mt){d(Ee(mt),"error")}}},[n,d,e,$]),ln=ye=>!_||_!==ye?t.jsx(Hg,{size:14,className:"sort-icon"}):z==="asc"?t.jsx(Ta,{size:14,className:"sort-icon active"}):t.jsx(Po,{size:14,className:"sort-icon active"}),Wt=ye=>t.jsxs("div",{id:ye,className:"list-view-options-panel",children:[t.jsx("div",{className:"list-view-options-columns",children:uv.map(Le=>{const Ke=k.has(Le),mt=Ke&&k.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${mt?" disabled":""}`,title:mt?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:Ke,onChange:()=>de(Le),disabled:mt}),t.jsx("span",{children:Ie[Le]})]},Le)})}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>je(Le=>!Le),"aria-pressed":ce,title:ce?"Show done tasks":"Hide done tasks",children:[ce?t.jsx(Tr,{size:14}):t.jsx(Pu,{size:14}),ce?"Show Done":"Hide Done"]}),t.jsx("div",{className:"list-drop-zones list-drop-zones--sidebar",children:oa.map(Le=>{const Ke=e.filter(Ot=>Ot.column===Le).length,mt=Le==="done"||Le==="archived",Ve=ce&&mt?0:Ke,Pt=ce&&mt&&Ke>0;return t.jsxs("div",{className:`list-drop-zone${K===Le?" drag-over":""}${ne===Le?" active":""}`,onClick:()=>st(Le),onDragOver:Ot=>Gt(Ot,Le),onDragLeave:on,onDrop:Ot=>sn(Ot,Le),"data-column":Le,children:[t.jsx("span",{className:`list-section-dot dot-${Le}`}),t.jsx("span",{className:"drop-zone-label",children:ds[Le]}),t.jsx("span",{className:"drop-zone-count",children:Pt?`${Ve} of ${Ke}`:Ke})]},Le)})})]});return t.jsxs("div",{className:"list-view",children:[P&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsx("button",{className:"btn btn-sm",onClick:Pe,"aria-pressed":ie,children:ie?"Done Editing":"Bulk Edit"}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>Y(ye=>!ye),"aria-expanded":Ne,"aria-controls":"list-view-options-panel-mobile",children:[t.jsx(_m,{size:14}),"View options"]}),m?t.jsx("button",{className:"btn btn-task-create btn-sm list-new-task-action",onClick:m,children:"+ New Task"}):null,t.jsx("div",{className:"list-stats",children:ne?`${_e} of ${e.length} tasks in ${ds[ne]}`:`${_e} of ${e.length} tasks`})]}),Ne?t.jsx("div",{className:"list-toolbar-mobile-options",children:Wt("list-view-options-panel-mobile")}):null]}),t.jsx("div",{className:"list-table-container",children:t.jsxs("div",{className:P?"":"list-split-layout","data-testid":P?void 0:"list-split-layout",ref:ae,children:[t.jsxs("div",{className:P?"":"list-split-sidebar","data-testid":P?void 0:"list-split-sidebar",ref:qe,style:P?void 0:{width:`${ve}px`},children:[!P&&t.jsxs("aside",{className:"list-sidebar-controls","aria-label":"List controls",children:[t.jsxs("div",{className:"list-sidebar-controls__header",children:[t.jsxs("p",{className:"list-stats",children:[ne?`${_e} of ${e.length} tasks in ${ds[ne]}`:`${_e} of ${e.length} tasks`,ut>0&&!ne&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",ut," hidden)"]})]}),t.jsxs("div",{className:"list-sidebar-controls__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Pe,"aria-pressed":ie,children:ie?"Done Editing":"Bulk Edit"}),m?t.jsx("button",{className:"btn btn-task-create btn-sm list-new-task-action",onClick:m,children:"+ New Task"}):null]}),t.jsxs("div",{className:"list-sidebar-summary-chips",children:[ne?t.jsx("button",{className:"btn btn-sm",onClick:me,"aria-label":"Clear column filter",children:`Filter: ${ds[ne]}`}):null,ce?t.jsx("span",{className:"list-sidebar-chip",children:"Done hidden"}):null,ie?t.jsx("span",{className:"list-sidebar-chip",children:"Bulk edit"}):null,ie&&oe.size>0?t.jsx("button",{className:"btn btn-sm",onClick:Be,children:`${oe.size} selected`}):null]})]}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>Y(ye=>!ye),"aria-expanded":Ne,"aria-controls":"list-view-options-panel",children:[t.jsx(_m,{size:14}),"View options"]}),Ne&&Wt("list-view-options-panel"),ie&&oe.size>0?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"bulk-edit-toolbar",children:t.jsxs("button",{className:"btn btn-danger btn-sm",onClick:rt,disabled:Re,children:[t.jsx(_n,{size:14}),"Delete selected"]})}),f&&f.length>0?t.jsxs("div",{className:"bulk-edit-toolbar",children:[t.jsx("span",{className:"bulk-edit-label",children:"Bulk Edit Models & Node:"}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(Is,{models:f,value:Je,onChange:dt,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:w})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(Is,{models:f,value:Nt,onChange:yt,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:w})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:Se,onChange:ye=>G(ye.target.value),"aria-label":"Node Override",disabled:ke,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),ge.map(ye=>t.jsx("option",{value:ye.id,children:`${IP(ye.status)} ${ye.name||ye.id} (${RP(ye.status)})`},ye.id))]}),Rt?t.jsx(Oa,{status:Rt.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:lt,disabled:Re||Je==="__no_change__"&&Nt==="__no_change__"&&Se==="__no_change__",children:Re?"Applying...":"Apply"})]}):null]}):null]}),t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Vb,{onCreate:h??(async()=>d("Task creation not available","error")),addToast:d,tasks:e,availableModels:f,onPlanningMode:b,onSubtaskBreakdown:y,projectId:j,autoExpand:!1,favoriteProviders:p,favoriteModels:g,onToggleFavorite:x,onToggleModelFavorite:w})}),_e===0?t.jsx("div",{className:"list-empty",children:N?"No tasks match your filter":"No tasks yet"}):P?t.jsx("div",{className:"list-cards",children:oa.map(ye=>{if(ne&&ye!==ne||ce&&(ye==="done"||ye==="archived")&&!ne)return null;const Le=re[ye],Ke=Le.length===0;if(N&&Ke)return null;const mt=He.has(ye);return t.jsxs(i.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${mt?" list-section-header--collapsed":""}`,onClick:()=>Ue(ye),"aria-expanded":!mt,role:"button",tabIndex:0,onKeyDown:Ve=>{(Ve.key==="Enter"||Ve.key===" ")&&(Ve.preventDefault(),Ue(ye))},children:[t.jsx(On,{size:14,className:`list-section-chevron${mt?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ye}`}),t.jsx("span",{className:"list-section-title",children:ds[ye]}),t.jsx("span",{className:"list-section-count",children:Le.length})]}),!mt&&t.jsx(t.Fragment,{children:Ke?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):Le.map(Ve=>{const Pt=Ve.status==="failed",Ot=Ve.paused===!0,bt=Gl(Ve,v,I),Dt=!u&&!Pt&&!Ot&&!bt&&(Ve.column==="in-progress"||Qp.has(Ve.status)),Ft=typeof Ve.status=="string"&&Ve.status.trim().length>0,Ht=!!(Ve.dependencies&&Ve.dependencies.length>0),rn=rf(Ve),Xt=rn.hasProgress,an=ie;return t.jsxs("div",{className:`list-card${Dt?" agent-active":""}${an?" list-card--selectable":""}`,onClick:()=>gt(Ve),"data-id":Ve.id,children:[an&&t.jsx("label",{className:"list-card-checkbox",onClick:Me=>Me.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:oe.has(Ve.id),onChange:Me=>{Me.stopPropagation(),nt(Ve.id)},onClick:Me=>Me.stopPropagation(),disabled:Ve.column==="archived","aria-label":`Select ${Ve.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:Ve.id}),Ve.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(as,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-card-spacer"}),Ot&&Ve.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):bt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Ft?t.jsx("span",{className:`list-status-badge list-status-badge--${Ve.column}${Pt?" failed":""}${Dt?" pulsing":""}`,children:Xp(Ve.status??"")}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:Ve.title||Ve.description})}),(Ht||Xt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[Ht&&t.jsxs("span",{className:"list-dep-badge",title:Ve.dependencies.join(", "),children:[t.jsx(vr,{size:12})," ",Ve.dependencies.length]}),Xt&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${rn.percent}%`,backgroundColor:fl[Ve.column]}})}),t.jsx("span",{className:"list-progress-label",children:rn.label})]})]})]},Ve.id)})})]},ye)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[ie&&t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:vt,ref:ye=>{ye&&(ye.indeterminate=Ae)},onChange:Qe,"aria-label":"Select all visible tasks"})}),k.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>$e("title"),children:["Title ",ln("title")]}),k.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>$e("status"),children:["Status ",ln("status")]}),k.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>$e("column"),children:["Column ",ln("column")]}),k.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),k.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:oa.map(ye=>{if(ne&&ye!==ne||ce&&(ye==="done"||ye==="archived")&&!ne)return null;const Le=re[ye],Ke=Le.length===0;if(N&&Ke)return null;const mt=He.has(ye);return t.jsxs(i.Fragment,{children:[t.jsx("tr",{className:`list-section-header${mt?" list-section-header--collapsed":""}`,onClick:()=>Ue(ye),"aria-expanded":!mt,children:t.jsxs("th",{colSpan:k.size+(ie?1:0),className:"list-section-cell",children:[t.jsx(On,{size:14,className:`list-section-chevron${mt?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ye}`}),t.jsx("span",{className:"list-section-title",children:ds[ye]}),t.jsx("span",{className:"list-section-count",children:Le.length})]})}),!mt&&t.jsx(t.Fragment,{children:Ke?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:k.size+(ie?1:0),className:"list-empty-cell",children:"No tasks"})}):Le.map(Ve=>{const Pt=Ve.status==="failed",Ot=Ve.paused===!0,bt=Gl(Ve,v,I),Dt=!u&&!Pt&&!Ot&&!bt&&(Ve.column==="in-progress"||Qp.has(Ve.status)),Ft=R===Ve.id;return t.jsxs("tr",{className:`list-row${Pt?" failed":""}${Ot?" paused":""}${bt?" stuck":""}${Dt?" agent-active":""}${Ft?" dragging":""}${L===Ve.id?" list-row--selected":""}`,onClick:()=>gt(Ve),draggable:!Ot,onDragStart:Ht=>tn(Ht,Ve),onDragEnd:mn,"data-id":Ve.id,children:[ie&&t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:oe.has(Ve.id),onChange:Ht=>{Ht.stopPropagation(),nt(Ve.id)},onClick:Ht=>Ht.stopPropagation(),disabled:Ve.column==="archived","aria-label":`Select ${Ve.id}`})}),k.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[t.jsx("span",{className:"list-title-id",children:Ve.id}),t.jsxs("div",{className:"list-title-row",children:[Ve.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(as,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-title-text",children:Ve.title||Ve.description})]})]})}),k.has("status")&&t.jsx("td",{className:"list-cell",children:Ot&&Ve.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):bt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Ve.status?t.jsx("span",{className:`list-status-badge list-status-badge--${Ve.column}${Pt?" failed":""}${Dt?" pulsing":""}`,children:Xp(Ve.status??"")}):t.jsx("span",{className:"list-status-badge",children:"-"})}),k.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${fl[Ve.column]}20`,color:fl[Ve.column]},children:ds[Ve.column]})}),k.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:Ve.dependencies&&Ve.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:Ve.dependencies.join(", "),children:[t.jsx(vr,{size:12})," ",Ve.dependencies.length]}):"-"}),k.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const Ht=rf(Ve);return Ht.hasProgress?t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${Ht.percent}%`,backgroundColor:fl[Ve.column]}})}),t.jsx("span",{className:"list-progress-label",children:Ht.label})]}):"-"})()})]},Ve.id)})})]},ye)})})]})]}),!P&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"list-split-resize-handle","data-testid":"list-split-resize-handle",onMouseDown:Qt,onKeyDown:yn,role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-label":"Resize task list sidebar","aria-valuemin":Zl,"aria-valuemax":Math.round(ju(ae.current?.clientWidth??ve/ku+gl)),"aria-valuenow":Math.round(ve)}),t.jsx("div",{className:"list-split-detail","data-testid":"list-split-detail",children:fe?t.jsx("div",{className:"list-split-detail-content","data-testid":"list-split-detail-content",children:t.jsx(dv,{task:fe,projectId:j,tasks:e,embedded:!0,onOpenDetail:Yt,onMoveTask:n,onDeleteTask:a,onMergeTask:r,onRetryTask:s,onResetTask:o,onDuplicateTask:l,onTaskUpdated:ye=>{B(Le=>!Le||Le.id!==ye.id?Le:{...Le,...ye})},addToast:d,prAuthAvailable:F})}):t.jsx("div",{className:"list-split-detail-empty",children:t.jsx("p",{children:"Select a task to view details"})})})]})]})})]})}const $P={active:{label:"Active",color:"var(--color-success)",icon:is},paused:{label:"Paused",color:"var(--color-warning)",icon:vi},errored:{label:"Error",color:"var(--color-error)",icon:Ws},initializing:{label:"Initializing",color:"var(--color-warning)",icon:jt}};function DP(e){if(!e)return"Never";const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function of(e,n=40){if(e.length<=n)return e;const s=e.slice(0,Math.floor(n/2)-2),a=e.slice(-Math.floor(n/2)+2);return`${s}...${a}`}function LP(e,n){if(e.project.id!==n.project.id||e.project.status!==n.project.status||e.project.name!==n.project.name||e.project.path!==n.project.path||e.project.lastActivityAt!==n.project.lastActivityAt||e.isLoading!==n.isLoading)return!1;const s=e.health,a=n.health;if(!s&&!a)return!0;if(!s||!a||s.activeTaskCount!==a.activeTaskCount||s.inFlightAgentCount!==a.inFlightAgentCount||s.totalTasksCompleted!==a.totalTasksCompleted||s.totalTasksFailed!==a.totalTasksFailed||s.status!==a.status)return!1;const r=e.availabilityMappings??[],o=n.availabilityMappings??[];return r.length!==o.length?!1:r.every((l,c)=>{const d=o[c];return!!d&&l.nodeId===d.nodeId&&l.path===d.path&&l.displayName===d.displayName&&l.available===d.available})}function OP({project:e,health:n,onSelect:s,onPause:a,onResume:r,onRemove:o,availabilityMappings:l=[],isLoading:c=!1}){const[d,u]=i.useState(!1),m=$P[e.status],h=m.icon,f=i.useCallback(()=>{s(e)},[s,e]),p=i.useCallback(S=>{S.stopPropagation(),a(e)},[a,e]),g=i.useCallback(S=>{S.stopPropagation(),r(e)},[r,e]),x=i.useCallback(S=>{if(S.stopPropagation(),!d){u(!0);return}o(e),u(!1)},[d,o,e]),w=e.status==="paused",b=e.status==="errored",y=e.status==="initializing";return t.jsxs("div",{className:`project-card ${c?"project-card-loading":""} ${b?"project-card-errored":""}`,onClick:f,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),f())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(Es,{size:20})}),t.jsxs("div",{className:"project-card-title-section",children:[t.jsx("h3",{className:"project-card-name",title:e.name,children:e.name}),l.length>0&&t.jsxs("div",{className:"project-card-availability","aria-label":"Project node availability",children:[l.slice(0,3).map(S=>t.jsxs("div",{className:"project-card-availability__row",title:`${S.displayName} → ${S.path}`,children:[t.jsx("span",{className:"project-card-availability__node",children:S.displayName}),t.jsx("span",{className:"project-card-availability__arrow",children:"→"}),t.jsx("code",{className:"project-card-availability__path",children:of(S.path,28)})]},`${S.nodeId}-${S.path}`)),l.length>3&&t.jsxs("span",{className:"project-card-availability__more",children:["+",l.length-3," more"]})]}),t.jsx("span",{className:"project-card-path",title:e.path,children:of(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:m.color,borderColor:m.color},children:[t.jsx(h,{size:12,className:y?"animate-spin":""}),t.jsx("span",{children:m.label})]})]}),t.jsxs("div",{className:"project-card-health",children:[n&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.activeTaskCount}),t.jsx("span",{className:"project-card-metric-label",children:"Active Tasks"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.inFlightAgentCount}),t.jsx("span",{className:"project-card-metric-label",children:"Agents"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.totalTasksCompleted}),t.jsx("span",{className:"project-card-metric-label",children:"Completed"})]})]}),!n&&t.jsx("div",{className:"project-card-metric project-card-metric-empty",children:t.jsx("span",{className:"project-card-metric-label",children:"No health data available"})})]}),t.jsxs("div",{className:"project-card-footer",children:[t.jsxs("div",{className:"project-card-activity",children:[t.jsx("span",{className:"project-card-activity-label",children:"Last activity:"}),t.jsx("span",{className:"project-card-activity-time",children:DP(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[w?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:g,disabled:c,title:"Resume project","aria-label":"Resume project",children:[t.jsx(is,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:p,disabled:c||y,title:y?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(vi,{size:14}),t.jsx("span",{children:"Pause"})]}),t.jsxs("button",{className:"project-card-action project-card-action-open",onClick:f,disabled:c,title:"Open project","aria-label":"Open project",children:[t.jsx($o,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${d?"is-armed":""}`,onClick:x,disabled:c,title:d?"Confirm remove":"Remove project","aria-label":d?"Confirm remove project":"Remove project",children:[t.jsx(_n,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const FP=i.memo(OP,LP);function lf(e){return typeof e=="string"&&e.trim().length>0}function fo(e){return(e.nodeMappings??[]).filter(s=>lf(s.nodeId)&&lf(s.path)).map(s=>({nodeId:s.nodeId,nodeName:s.nodeName,path:s.path,available:s.available!==!1}))}function zP(e,n){return fo(e).filter(s=>s.nodeId===n.id&&s.available)}function BP(e,n){return zP(e,n).length>0}function UP(e,n){return e.filter(s=>BP(s,n))}function i8(e,n){return UP(e,n).length}function cf(e,n,s,a){const r=s.find(o=>o.id===e);return r?.name?r.name:n?.nodeName?n.nodeName:a._sourceNodeName?a._sourceNodeName:e}function HP(){return t.jsxs("div",{className:"project-overview project-overview--loading",children:[t.jsx("div",{className:"project-overview__header-skeleton",children:t.jsxs("div",{className:"project-overview__stats-row",children:[t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Es,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Ys,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Gn,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Ws,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]})]})}),t.jsxs("div",{className:"project-overview__filters-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"})]}),t.jsx("div",{className:"project-grid project-grid--skeleton",children:Array.from({length:6}).map((e,n)=>t.jsxs("div",{className:"project-card project-card--skeleton",children:[t.jsxs("div",{className:"project-card-skeleton__header",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon-circle"}),t.jsxs("div",{className:"project-skeleton__text-group",children:[t.jsx("div",{className:"project-skeleton project-skeleton--title"}),t.jsx("div",{className:"project-skeleton project-skeleton--path"})]}),t.jsx("div",{className:"project-skeleton project-skeleton--badge"})]}),t.jsxs("div",{className:"project-card-skeleton__health",children:[t.jsx("div",{className:"project-skeleton project-skeleton--metric"}),t.jsx("div",{className:"project-skeleton project-skeleton--metric"}),t.jsx("div",{className:"project-skeleton project-skeleton--metric"})]}),t.jsxs("div",{className:"project-card-skeleton__footer",children:[t.jsx("div",{className:"project-skeleton project-skeleton--activity"}),t.jsx("div",{className:"project-skeleton project-skeleton--actions"})]})]},n))})]})}const qP=1e4,df=5;function VP(e){const[n,s]=i.useState({}),[a,r]=i.useState(!0),[o,l]=i.useState(null),c=i.useRef(null),d=i.useRef(null),u=i.useRef(!1),m=i.useCallback(async()=>{if(e.length===0){s({}),u.current||(u.current=!0),r(!1);return}d.current&&d.current.abort(),d.current=new AbortController,!u.current&&r(!0),l(null);try{const p={};for(let g=0;g<e.length;g+=df){const x=e.slice(g,g+df),w=await Promise.allSettled(x.map(async b=>{try{return await eh(b)}catch{return null}}));if(x.forEach((b,y)=>{const S=w[y];p[b]=S.status==="fulfilled"?S.value:null}),d.current?.signal.aborted)return}s(p),u.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),u.current=!0}finally{r(!1)}},[e]),h=i.useCallback(async f=>{try{const p=await eh(f);s(g=>({...g,[f]:p}))}catch(p){console.error(`Failed to fetch health for project ${f}:`,p)}},[]);return i.useEffect(()=>(u.current=!1,m(),()=>{d.current&&d.current.abort()}),[m]),i.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},qP),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:a,error:o,refresh:m,refreshProject:h}}function WP({projects:e,loading:n=!1,onSelectProject:s,onAddProject:a,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[d,u]=i.useState("all"),[m,h]=i.useState(null),[f,p]=i.useState("activity"),[g,x]=i.useState("desc");i.useEffect(()=>{if(typeof window>"u")return;const U=localStorage.getItem("kb-dashboard-recent-projects");if(U)try{const R=JSON.parse(U);b(R)}catch{}},[]);const[w,b]=i.useState([]),y=i.useMemo(()=>e.map(U=>U.id),[e]),{healthMap:S,loading:j}=VP(y),C=i.useMemo(()=>e.map(U=>({project:U,health:S[U.id]||null})),[e,S]),v=i.useMemo(()=>{let U=[...C];return d!=="all"&&(U=U.filter(({project:R})=>R.status===d)),m!==null&&(U=U.filter(({project:R})=>fo(R).some(D=>D.available&&D.nodeId===m))),U},[C,d,m]),N=i.useMemo(()=>{const U=[...v];return U.sort((R,D)=>{let K=0;switch(f){case"name":K=R.project.name.localeCompare(D.project.name);break;case"activity":{const Z=R.project.lastActivityAt||R.health?.lastActivityAt||R.project.updatedAt,ne=D.project.lastActivityAt||D.health?.lastActivityAt||D.project.updatedAt;K=new Date(ne).getTime()-new Date(Z).getTime();break}case"status":{const Z={errored:0,initializing:1,paused:2,active:3};K=Z[R.project.status]-Z[D.project.status];break}}return g==="asc"?K:-K}),U},[v,f,g]),I=i.useMemo(()=>{const U=e.length,R=e.filter(P=>P.status==="active").length,D=e.filter(P=>P.status==="errored").length,K=new Set;e.forEach(P=>{fo(P).forEach($=>{$.available&&K.add($.nodeId)})});const Z=K.size;let ne=0,O=0,A=0;return Object.values(S).forEach(P=>{P&&(ne+=P.activeTaskCount,O+=P.totalTasksCompleted,A+=P.inFlightAgentCount)}),{totalProjects:U,activeProjects:R,erroredProjects:D,totalNodes:Z,totalActiveTasks:ne,totalCompletedTasks:O,totalInFlightAgents:A}},[e,S]),F=i.useMemo(()=>({all:e.length,active:e.filter(U=>U.status==="active").length,paused:e.filter(U=>U.status==="paused").length,errored:e.filter(U=>U.status==="errored").length}),[e]),_=i.useMemo(()=>{const U=new Map;return e.forEach(R=>{fo(R).filter(D=>D.available).forEach(D=>{const K=D.nodeId,Z=U.get(K),ne=cf(K,D,c,R);Z?Z.count+=1:U.set(K,{name:ne,count:1})})}),Array.from(U.entries()).map(([R,{name:D,count:K}])=>({nodeId:R,name:D,count:K}))},[e,c]),M=i.useCallback(U=>{const R=[U.id,...w.filter(D=>D!==U.id)].slice(0,3);b(R),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(R)),s(U)},[s,w]);return n||j&&e.length>0&&Object.keys(S).length===0?t.jsx(HP,{}):e.length===0?t.jsx("div",{className:"project-overview project-overview--empty",children:t.jsxs("div",{className:"project-empty-state",children:[t.jsx("div",{className:"project-empty-state__icon",children:t.jsx(ra,{size:48})}),t.jsx("h2",{className:"project-empty-state__title",children:"No Projects Found"}),t.jsx("p",{className:"project-empty-state__description",children:"Get started by adding your first project. Projects allow you to organize and track tasks across multiple repositories."}),t.jsxs("button",{className:"btn btn-primary project-empty-state__cta",onClick:a,children:[t.jsx(Mn,{size:16}),"Add Your First Project"]})]})}):t.jsxs("div",{className:"project-overview",children:[t.jsxs("div",{className:"project-overview__header",children:[t.jsxs("h2",{className:"project-overview__title",children:[t.jsx(ma,{size:20}),"Projects"]}),t.jsxs("div",{className:"project-overview__stats",children:[t.jsxs("div",{className:"project-stat",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Es,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:I.totalProjects}),t.jsx("span",{className:"project-stat__label",children:"Total"})]})]}),t.jsxs("div",{className:"project-stat project-stat--active",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ys,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:I.totalActiveTasks}),t.jsx("span",{className:"project-stat__label",children:"Active Tasks"})]})]}),t.jsxs("div",{className:"project-stat project-stat--completed",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Gn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:I.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),I.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ws,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:I.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),I.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Co,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:I.totalNodes}),t.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),t.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:a,children:[t.jsx(Mn,{size:16}),"Add Project"]})]}),t.jsxs("div",{className:"project-overview__filters",children:[t.jsxs("div",{className:"project-filter-tabs",children:[t.jsxs("button",{className:`project-filter-tab ${d==="all"?"active":""}`,onClick:()=>u("all"),children:["All",t.jsx("span",{className:"project-filter-count",children:F.all})]}),t.jsxs("button",{className:`project-filter-tab ${d==="active"?"active":""}`,onClick:()=>u("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:F.active})]}),t.jsxs("button",{className:`project-filter-tab ${d==="paused"?"active":""}`,onClick:()=>u("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:F.paused})]}),t.jsxs("button",{className:`project-filter-tab ${d==="errored"?"active":""} ${F.errored>0?"has-errors":""}`,onClick:()=>u("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:F.errored})]})]}),_.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(Co,{size:14}),t.jsxs("select",{value:m??"",onChange:U=>{h(U.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),_.map(({nodeId:U,name:R,count:D})=>t.jsxs("option",{value:U??"",children:[R," (",D,")"]},U??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(Fl,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:U=>{const[R,D]=U.target.value.split("-");p(R),x(D)},className:"project-sort-select","aria-label":"Sort projects",children:[t.jsx("option",{value:"activity-desc",children:"Last Activity (Newest)"}),t.jsx("option",{value:"activity-asc",children:"Last Activity (Oldest)"}),t.jsx("option",{value:"name-asc",children:"Name (A-Z)"}),t.jsx("option",{value:"name-desc",children:"Name (Z-A)"}),t.jsx("option",{value:"status-asc",children:"Status (Error → Active)"}),t.jsx("option",{value:"status-desc",children:"Status (Active → Error)"})]}),t.jsx(Hg,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:N.map(({project:U,health:R})=>{const D=fo(U).filter(K=>K.available).map(K=>({...K,displayName:cf(K.nodeId,K,c,U)}));return t.jsx(FP,{project:U,health:R,availabilityMappings:D,onSelect:M,onPause:r,onResume:o,onRemove:l},U.id)})}),N.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(Fl,{size:32}),t.jsx("p",{children:"No projects match the current filter"}),t.jsx("button",{className:"btn btn-secondary",onClick:()=>u("all"),children:"Show All Projects"})]})]})}const bm="kb-planning-last-description",xm="kb-subtask-last-description",vm="kb-mission-last-goal";function KP(e,n){us(bm,e,n)}function GP(e){return zn(bm,e)||""}function or(e){Nr(bm,e)}function JP(e,n){us(xm,e,n)}function YP(e){return zn(xm,e)||""}function Sd(e){Nr(xm,e)}function QP(e,n){us(vm,e,n)}function XP(e){return zn(vm,e)||""}function ia(e){Nr(vm,e)}function ZP(e){const{question:n,response:s}=e;if(!n)return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const a=s;if(n.id in a)return a[n.id]}return s}function e$(e,n){switch(e.type){case"text":return typeof n=="string"?n:n==null?"":String(n);case"single_select":return typeof n=="string"?e.options?.find(a=>a.id===n)?.label??n:n==null?"":String(n);case"multi_select":return Array.isArray(n)?n.map(s=>typeof s!="string"?String(s):e.options?.find(r=>r.id===s)?.label??s).join(", "):n==null?"":String(n);case"confirm":return n===!0?"Yes":n===!1?"No":n==null?"":String(n);default:return n==null?"":JSON.stringify(n)}}function t$(e){let n=0;const s=[];for(const a of e){if(a.question){n+=1,s.push({...a,questionNumber:n});continue}a.thinkingOutput&&s.push({...a,questionNumber:null})}return s}function mi({entries:e,defaultShowThinking:n=!1}){const[s,a]=i.useState({}),r=t$(e);return r.length===0?null:t.jsx("div",{className:"conversation-history","data-testid":"conversation-history",children:r.map((o,l)=>{const c=!!o.question,d=!!o.thinkingOutput,u=s[l]??n,m=c?ZP(o):void 0,h=o.question&&m!==void 0?e$(o.question,m):"",f=o.response&&typeof o.response=="object"&&!Array.isArray(o.response)?o.response:void 0,p=typeof f?._comment=="string"?f._comment.trim():"";return t.jsxs("div",{className:"conversation-entry",children:[c?t.jsxs("div",{className:"conversation-entry-question",children:[t.jsxs("span",{className:"conversation-entry-question-label",children:["Q",o.questionNumber]}),t.jsx("p",{children:o.question?.question})]}):t.jsx("div",{className:"conversation-entry-question",children:t.jsx("span",{className:"conversation-entry-question-label",children:"AI Reasoning"})}),c&&t.jsxs("div",{className:"conversation-entry-response",children:[t.jsx("strong",{children:"Your response"}),t.jsx("p",{children:h||"—"}),p&&t.jsxs("p",{className:"conversation-comment",children:["💬 ",p]})]}),d&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{a(g=>({...g,[l]:!u}))},"aria-expanded":u,children:[t.jsx("span",{"aria-hidden":"true",children:u?"▾":"▸"}),u?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),u&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const uf="fusion-tab-id";function n$(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Va(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(uf);if(e)return e;const n=n$();return window.sessionStorage.setItem(uf,n),n}function Ec(e){const n=i.useMemo(()=>Va(),[]),[s,a]=i.useState(!1),[r,o]=i.useState(null),[l,c]=i.useState(!1);i.useEffect(()=>{if(!e){a(!1),o(null),c(!1);return}let u=!0;return c(!0),Promise.resolve(h0(e,n)).then(m=>{if(u){if(m.acquired){a(!1),o(null);return}a(!0),o(m.currentHolder)}}).catch(()=>{u&&(a(!1),o(null))}).finally(()=>{u&&c(!1)}),()=>{u=!1;try{const m=p0(e,n);m&&typeof m.catch=="function"&&m.catch(()=>{})}catch{}}},[e,n]),i.useEffect(()=>{if(!e||typeof window>"u")return;const u=()=>{if(typeof navigator.sendBeacon!="function")return;const m=Di(`/api/ai-sessions/${encodeURIComponent(e)}/lock/beacon?tabId=${encodeURIComponent(n)}`);navigator.sendBeacon(m)};return window.addEventListener("beforeunload",u),()=>{window.removeEventListener("beforeunload",u)}},[e,n]),i.useEffect(()=>!e||typeof EventSource>"u"?void 0:hi("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const f=h.lockedByTab??null;o(f),a(!!(f&&f!==n))}catch{}}}}),[e,n]);const d=i.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(f0(e,n)),a(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:d,isLoading:l}}const s$="fusion:ai-session-sync",mf="fusion:ai-session-sync",i$=3e4,a$=6e4;function Mi(){return Date.now()}function r$(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function hf(e){if(!e||typeof e!="object")return null;const n=e;return typeof n.type!="string"||typeof n.timestamp!="number"||!Number.isFinite(n.timestamp)?null:e}class o${tabId;listeners=new Set;sessionStates=new Map;ownershipBySession=new Map;heartbeatByTab=new Map;ownedSessions=new Map;snapshot;channel=null;usingStorageFallback=!1;cleanupStorageListener=null;cleanupBeforeUnload=null;heartbeatInterval=null;staleSweepInterval=null;constructor(){this.tabId=r$(),this.snapshot={tabId:this.tabId,sessions:new Map,activeTabMap:new Map},this.isBrowser()&&(this.initializeTransport(),this.startHeartbeat(),this.startStaleSweep(),this.setupBeforeUnloadCleanup())}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}requestSync(){this.publish({type:"sync:request",tabId:this.tabId,timestamp:Mi()})}broadcastUpdate(n){const s=n.timestamp??Mi();this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",owningTabId:n.owningTabId,type:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},s),this.publish({type:"session:updated",sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,sessionType:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt,timestamp:s})}broadcastCompleted(n){const s=n.status??"complete",a=n.timestamp??Mi();this.applySessionUpdate({sessionId:n.sessionId,status:s,needsInput:!1,owningTabId:null},a),this.ownershipBySession.delete(n.sessionId),this.ownedSessions.delete(n.sessionId),this.emit(),this.publish({type:"session:completed",sessionId:n.sessionId,status:s,timestamp:a})}broadcastLock(n,s){const a=Mi();this.applyTabOwnership(n,s,a),this.ownedSessions.set(n,s),this.publish({type:"tab:active",tabId:s,sessionId:n,timestamp:a})}broadcastUnlock(n,s){const a=Mi();this.releaseTabOwnership(n,s,a),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:a})}broadcastHeartbeat(n){const s=Mi();this.updateHeartbeat(n,s),this.publish({type:"tab:heartbeat",tabId:n,timestamp:s})}destroy(){this.cleanupStorageListener?.(),this.cleanupStorageListener=null,this.cleanupBeforeUnload?.(),this.cleanupBeforeUnload=null,this.channel&&(this.channel.close(),this.channel=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.staleSweepInterval&&(clearInterval(this.staleSweepInterval),this.staleSweepInterval=null)}reset(){this.sessionStates.clear(),this.ownershipBySession.clear(),this.heartbeatByTab.clear(),this.ownedSessions.clear(),this.snapshot={tabId:this.tabId,sessions:new Map,activeTabMap:new Map},this.emit()}isBrowser(){return typeof window<"u"}initializeTransport(){if(typeof BroadcastChannel<"u")try{this.channel=new BroadcastChannel(s$),this.channel.onmessage=s=>{const a=hf(s.data);a&&this.handleIncomingMessage(a)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==mf||!s.newValue))try{const a=JSON.parse(s.newValue),r=hf(a.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Mi();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},i$)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,a]of this.ownedSessions.entries()){const r=Mi();this.publish({type:"tab:inactive",tabId:a,sessionId:s,timestamp:r})}};window.addEventListener("beforeunload",n),this.cleanupBeforeUnload=()=>{window.removeEventListener("beforeunload",n)}}publish(n){const s={...n,senderTabId:this.tabId};if(this.channel){this.channel.postMessage(s);return}if(this.usingStorageFallback)try{const a={id:`${s.type}-${s.timestamp}-${Math.random().toString(36).slice(2,8)}`,message:s};window.localStorage.setItem(mf,JSON.stringify(a))}catch{}}handleIncomingMessage(n){switch(n.type){case"session:updated":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,type:n.sessionType,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},n.timestamp);return}case"session:completed":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status??"complete",needsInput:!1,owningTabId:null},n.timestamp),this.ownershipBySession.delete(n.sessionId),this.emit();return}case"tab:active":{this.applyTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:inactive":{this.releaseTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:heartbeat":{this.updateHeartbeat(n.tabId,n.timestamp);return}case"sync:request":{if(n.tabId===this.tabId)return;const s=[...this.sessionStates.values()].map(o=>{const l=this.ownershipBySession.get(o.sessionId);return{...o,owningTabId:l?.tabId??o.owningTabId??null}}),a=[...this.ownershipBySession.entries()].map(([o,l])=>({sessionId:o,tabId:l.tabId,timestamp:l.timestamp})),r=[...this.heartbeatByTab.entries()].map(([o,l])=>({tabId:o,timestamp:l}));this.publish({type:"sync:response",tabId:n.tabId,sessions:s,locks:a,heartbeats:r,timestamp:Mi()});return}case"sync:response":{if(n.tabId!==this.tabId)return;for(const s of n.sessions)this.applySessionUpdate({sessionId:s.sessionId,status:s.status,needsInput:s.needsInput,owningTabId:s.owningTabId,type:s.type,title:s.title,projectId:s.projectId,updatedAt:s.updatedAt},s.lastEventTimestamp,!1);for(const s of n.locks??[])this.applyTabOwnership(s.sessionId,s.tabId,s.timestamp,!1);for(const s of n.heartbeats??[])this.updateHeartbeat(s.tabId,s.timestamp,!1);this.emit();return}default:return}}applySessionUpdate(n,s,a=!0){const r=this.sessionStates.get(n.sessionId);if(r&&s<r.lastEventTimestamp)return;const o=this.ownershipBySession.get(n.sessionId),l={sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",lastEventTimestamp:s,owningTabId:n.owningTabId??o?.tabId??r?.owningTabId??null,type:n.type??r?.type,title:n.title??r?.title,projectId:n.projectId??r?.projectId,updatedAt:n.updatedAt??new Date(s).toISOString()};this.sessionStates.set(n.sessionId,l),n.owningTabId!==void 0&&(n.owningTabId?this.applyTabOwnership(n.sessionId,n.owningTabId,s,!1):this.ownershipBySession.delete(n.sessionId)),a&&this.emit()}applyTabOwnership(n,s,a,r=!0){const o=this.ownershipBySession.get(n);if(o&&a<o.timestamp)return;this.ownershipBySession.set(n,{tabId:s,timestamp:a}),this.updateHeartbeat(s,a,!1);const l=this.sessionStates.get(n);l&&a>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:s,lastEventTimestamp:a}),r&&this.emit()}releaseTabOwnership(n,s,a,r=!0){const o=this.ownershipBySession.get(n);if(!o||o.tabId!==s||a<o.timestamp)return;this.ownershipBySession.delete(n);const l=this.sessionStates.get(n);l&&a>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:null,lastEventTimestamp:a}),r&&this.emit()}updateHeartbeat(n,s,a=!0){const r=this.heartbeatByTab.get(n);r!==void 0&&s<r||(this.heartbeatByTab.set(n,s),a&&this.emit())}emit(){const n=Mi(),s=new Map;for(const[r,o]of this.sessionStates.entries()){const l=this.ownershipBySession.get(r);s.set(r,{...o,owningTabId:l?.tabId??o.owningTabId??null})}const a=new Map;for(const[r,o]of this.ownershipBySession.entries()){const l=this.heartbeatByTab.get(o.tabId)??o.timestamp,c=n-l>a$;a.set(r,{sessionId:r,tabId:o.tabId,lastHeartbeatTimestamp:l,lastLockTimestamp:o.timestamp,stale:c})}this.snapshot={tabId:this.tabId,sessions:s,activeTabMap:a};for(const r of this.listeners)r()}}const Ai=new o$;function Fr(){const e=i.useSyncExternalStore(c=>Ai.subscribe(c),()=>Ai.getSnapshot(),()=>Ai.getSnapshot());i.useEffect(()=>{Ai.requestSync()},[]);const n=i.useCallback(c=>{Ai.broadcastUpdate(c)},[]),s=i.useCallback(c=>{Ai.broadcastCompleted(c)},[]),a=i.useCallback((c,d)=>{Ai.broadcastLock(c,d)},[]),r=i.useCallback((c,d)=>{Ai.broadcastUnlock(c,d)},[]),o=i.useCallback(c=>{Ai.broadcastHeartbeat(c)},[]),l=i.useCallback(()=>{Ai.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:a,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function l$(e,n){return e&&n?`${e}/${n}`:""}function c$(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}const d$=["Build a real-time collaborative document editor","Create a customer onboarding flow with email verification","Add a reporting dashboard with charts and CSV export","Implement a plugin system with marketplace"];function u$({isOpen:e,onClose:n,onMissionCreated:s,projectId:a,initialGoal:r,resumeSessionId:o}){Ni(e);const[l,c]=i.useState(""),[d,u]=i.useState({type:"initial"}),[m,h]=i.useState(null),[f,p]=i.useState([]),[g,x]=i.useState([]),[w,b]=i.useState(null),[y,S]=i.useState(!1),j=i.useRef(!1),[C,v]=i.useState(""),[N,I]=i.useState(!0),[F,_]=i.useState(!1),[M,z]=i.useState(!1),[U,R]=i.useState(!1),D=i.useRef(null),K=i.useRef(null),Z=i.useRef(null),ne=i.useRef(null),[O,A]=i.useState(o??null),P=i.useMemo(()=>Va(),[]),{isLockedByOther:$,takeControl:k,isLoading:J}=Ec(e?O:null),{activeTabMap:ce,broadcastUpdate:je,broadcastCompleted:He,broadcastLock:xe,broadcastUnlock:Ne,broadcastHeartbeat:Y}=Fr(),{confirm:ie}=pi(),[ee,oe]=i.useState(void 0),[W,L]=i.useState(void 0),[pe,fe]=i.useState([]),[B,ve]=i.useState(!0),[Fe,ae]=i.useState(null),[qe,Pe]=i.useState([]),[nt,Be]=i.useState([]),de=l$(ee,W);i.useEffect(()=>{(async()=>{try{ve(!0);const G=await Ks();fe(G.models),Pe(G.favoriteProviders),Be(G.favoriteModels)}catch(G){ae(Ee(G)||"Failed to load models")}finally{ve(!1)}})()},[]);const Ie=i.useCallback(Se=>{Pe(G=>{const ge=G,ke=ge.includes(Se)?ge.filter(tt=>tt!==Se):[Se,...ge];return Dn({favoriteProviders:ke,favoriteModels:nt}).catch(()=>{Pe(ge)}),ke})},[nt]),$e=i.useCallback(Se=>{Be(G=>{const ge=G,ke=ge.includes(Se)?ge.filter(tt=>tt!==Se):[Se,...ge];return Dn({favoriteProviders:qe,favoriteModels:ke}).catch(()=>{Be(ge)}),ke})},[qe]),st=i.useCallback((Se,G)=>{if(!Se||!G)return"Using default";const ge=pe.find(pt=>pt.provider===Se&&pt.id===G);return ge?`${ge.provider}/${ge.id}`:`${Se}/${G}`},[pe]),Ue=i.useCallback(Se=>{K.current?.close();const G=Z1(Se,a,{onThinking:ge=>{v(pt=>pt+ge),je({sessionId:Se,status:"generating",needsInput:!1,owningTabId:P,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onQuestion:ge=>{_(!1),z(!1),ia(a),u({type:"question",sessionId:Se,question:ge}),v(""),S(!0),je({sessionId:Se,status:"awaiting_input",needsInput:!0,owningTabId:P,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onSummary:ge=>{_(!1),z(!1),ia(a),u({type:"summary",sessionId:Se,summary:ge}),b(ge),v(""),S(!0),je({sessionId:Se,status:"complete",needsInput:!1,owningTabId:P,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onError:ge=>{const pt=ge||"Session failed while contacting the AI.";_(!1),z(!1),h(null),u({type:"error",sessionId:Se,errorMessage:pt}),v(""),S(!0),Z.current=Se,je({sessionId:Se,status:"error",needsInput:!1,owningTabId:P,type:"mission_interview",title:l.trim()||void 0,projectId:a??null}),He({sessionId:Se,status:"error"})},onComplete:()=>{_(!1),z(!1),Z.current=null,He({sessionId:Se,status:"complete"})},onConnectionStateChange:ge=>{_(ge==="reconnecting")}});K.current=G},[He,je,l,a,P]),me=i.useCallback(async Se=>{const G=Se??l;if(G.trim()){h(null),v(""),p([]),x([]),_(!1),u({type:"loading"});try{const{sessionId:ge}=await J1(G.trim(),a,ee&&W?{modelProvider:ee,modelId:W}:void 0);Z.current=ge,A(ge),ia(a),Ue(ge),p([])}catch(ge){_(!1),h(Ee(ge)||"Failed to start interview session"),u({type:"initial"}),Z.current=null,A(null)}}},[Ue,l,ee,W,a]);i.useEffect(()=>{e&&d.type==="initial"&&D.current?.focus()},[e,d.type]),i.useEffect(()=>{if(e&&!r&&!o&&!j.current&&d.type==="initial"){const Se=XP(a);Se&&c(Se)}},[e]),i.useEffect(()=>{if(e&&r&&!j.current&&d.type==="initial"){c(r);const Se=setTimeout(()=>{j.current=!0,me(r)},0);return()=>clearTimeout(Se)}},[e,r,d.type,me]),i.useEffect(()=>{e||(j.current=!1,_(!1),z(!1),A(null))},[e]),i.useEffect(()=>{if(!e||!o||d.type!=="initial")return;let Se=!1;return Ti(o).then(G=>{if(Se||!G)return;const ge=jr(G.conversationHistory);if(x(ge),A(G.id),p(ge.map(pt=>pt.response).filter(pt=>!!(pt&&typeof pt=="object"&&!Array.isArray(pt)))),G.status==="awaiting_input"&&G.currentQuestion)try{ia(a);const pt=JSON.parse(G.currentQuestion);Z.current=G.id,S(!0),u({type:"question",sessionId:G.id,question:pt})}catch{h("Failed to restore session question.")}else if(G.status==="complete"&&G.result)try{ia(a);const pt=JSON.parse(G.result);Z.current=G.id,S(!0),b(pt),u({type:"summary",sessionId:G.id,summary:pt})}catch{h("Failed to restore session result.")}else G.status==="generating"?(Z.current=G.id,S(!0),G.thinkingOutput&&v(G.thinkingOutput),u({type:"loading"}),Ue(G.id)):G.status==="error"&&(Z.current=G.id,S(!0),h(null),u({type:"error",sessionId:G.id,errorMessage:G.error??"The session encountered an error."}))}).catch(()=>{Se||h("Failed to resume session.")}),()=>{Se=!0}},[Ue,e,o,d.type,a]),i.useEffect(()=>{if(!e){ne.current&&(Ne(ne.current,P),ne.current=null);return}if(O&&ne.current!==O){ne.current&&Ne(ne.current,P),xe(O,P),ne.current=O;return}!O&&ne.current&&(Ne(ne.current,P),ne.current=null)},[xe,Ne,e,O,P]),i.useEffect(()=>{if(!e||!O||ne.current!==O)return;Y(P);const Se=setInterval(()=>{Y(P)},3e4);return()=>{clearInterval(Se)}},[Y,e,O,P]),i.useEffect(()=>()=>{K.current?.close(),K.current=null,ne.current&&(Ne(ne.current,P),ne.current=null)},[Ne,P]),i.useEffect(()=>{if(!e)return;const Se=G=>{(d.type==="question"||d.type==="summary")&&(G.preventDefault(),G.returnValue=""),K.current?.close()};return window.addEventListener("beforeunload",Se),()=>window.removeEventListener("beforeunload",Se)},[e,d]);const re=i.useCallback(()=>{K.current?.close(),K.current=null,n()},[n]),_e=i.useCallback(async()=>{if(l&&QP(l,a),!(y&&!await ie({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(K.current?.close(),K.current=null,d.type==="question"||d.type==="summary"||d.type==="error")try{await gb(d.sessionId,a,P)}catch{}c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),v(""),_(!1),z(!1),S(!1),R(!1),oe(void 0),L(void 0),Z.current=null,A(null),n()}},[l,y,d,n,a,P,ie]);i.useEffect(()=>{if(!e)return;const Se=G=>{G.key==="Escape"&&_e()};return document.addEventListener("keydown",Se),()=>document.removeEventListener("keydown",Se)},[e,_e]);const xt=i.useCallback(async Se=>{if(d.type!=="question")return;const{sessionId:G}=d;h(null),p(ge=>[...ge,Se]),x(ge=>[...ge,{question:d.question,response:Se}]),u({type:"loading"}),v("");try{Ue(G),await Y1(G,Se,a,P),S(!0)}catch(ge){K.current?.close(),K.current=null,h(Ee(ge)||"Failed to submit response"),u({type:"question",sessionId:G,question:d.question})}},[d,a,P,Ue]),ut=i.useCallback(async()=>{if(d.type!=="error")return;const Se=d.sessionId;h(null),z(!0),v(""),u({type:"loading"}),Ue(Se);try{Z.current=Se,A(Se),await Q1(Se,a,P)}catch(G){let ge=G;if((Ee(G)||"").includes("not in an error state"))try{const ke=await Ti(Se);if(!ke)throw new Error("Failed to refresh interview session.");const tt=jr(ke.conversationHistory);if(x(tt),p(tt.map(Rt=>Rt.response).filter(Rt=>!!(Rt&&typeof Rt=="object"&&!Array.isArray(Rt)))),Z.current=ke.id,A(ke.id),S(!0),ke.status==="generating")v(ke.thinkingOutput??""),u({type:"loading"}),K.current?.isConnected()||Ue(ke.id);else if(ke.status==="awaiting_input"){if(!ke.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");ia(a);const Rt=JSON.parse(ke.currentQuestion);u({type:"question",sessionId:ke.id,question:Rt}),K.current?.isConnected()||Ue(ke.id)}else if(ke.status==="complete"){if(!ke.result)throw new Error("Interview session is complete but has no result.");ia(a);const Rt=JSON.parse(ke.result);b(Rt),u({type:"summary",sessionId:ke.id,summary:Rt})}else ke.status==="error"&&u({type:"error",sessionId:ke.id,errorMessage:ke.error??"Retry failed. Please try again."});_(!1);return}catch(ke){ge=ke}K.current?.close(),K.current=null,u({type:"error",sessionId:Se,errorMessage:Ee(ge)||"Retry failed. Please try again."}),_(!1)}finally{z(!1)}},[Ue,a,P,d]),Qe=i.useCallback(async()=>{if(d.type==="summary"){h(null),R(!0);try{const Se=await X1(d.sessionId,w||void 0,a);s(Se),ia(a),K.current?.close(),K.current=null,c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),v(""),_(!1),z(!1),S(!1),R(!1),Z.current=null,A(null),n()}catch(Se){h(Ee(Se)||"Failed to create mission"),R(!1)}}},[d,w,s,n,a]),vt=()=>d.type==="question"?Math.min(f.length+1,6):6,Ae=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Je=O?ce.get(O):null,dt=Je&&Je.tabId!==P,Nt=!!(dt&&!Je.stale),yt=$&&(!dt||Je.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Se=>Se.target===Se.currentTarget&&_e(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Rs,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Ae&&t.jsx("button",{className:"modal-send-to-background",onClick:re,title:"Send to background","aria-label":"Send to background",children:t.jsx(Lo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:_e,"aria-label":"Close",children:t.jsx(un,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),F&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Nt&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),d.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(gs,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your vision into a structured mission"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build. The AI will interview you to understand scope, constraints, and requirements, then produce a structured plan with milestones, slices, and features."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"mission-goal",children:"What do you want to build?"}),t.jsx("textarea",{ref:D,id:"mission-goal",rows:4,className:"planning-textarea",placeholder:"e.g., Build a real-time collaborative document editor with presence, comments, and version history...",value:l,onChange:Se=>c(Se.target.value),onKeyDown:Se=>{Se.key==="Enter"&&!Se.shiftKey&&l.trim()&&(Se.preventDefault(),me())}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:d$.map((Se,G)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(Se),children:Se.length>45?Se.slice(0,45)+"...":Se},G))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",B&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Is,{id:"mission-interview-modal-model",label:"Planning Model",value:de,onChange:Se=>{const{provider:G,modelId:ge}=c$(Se);oe(G),L(ge)},models:pe,disabled:B,favoriteProviders:qe,onToggleFavorite:Ie,favoriteModels:nt,onToggleModelFavorite:$e}),Fe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Fe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{ve(!0);const Se=await Ks();fe(Se.models),Pe(Se.favoriteProviders),Be(Se.favoriteModels),ae(null)}catch(Se){ae(Ee(Se)||"Failed to load models")}finally{ve(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ee&&W?"model-badge-custom":"model-badge-default"}`,children:st(ee,W)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>me(),disabled:!l.trim(),children:[t.jsx(Rs,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:C?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>I(!N),type:"button",children:N?"Hide thinking":"Show thinking"}),N&&C&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:C})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[g.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(mi,{entries:g}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:d.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void ut(),disabled:M,children:[M?t.jsx(jt,{size:14,className:"spin"}):t.jsx(bs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:M?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:_e,disabled:M,children:"Cancel"})]})]})]})}),d.type==="question"&&t.jsx(m$,{question:d.question,progress:vt(),historyEntries:g,onSubmit:xt}),d.type==="summary"&&w&&t.jsx(h$,{summary:w,historyEntries:g,onSummaryChange:b,onApprove:Qe,onStartOver:()=>{u({type:"initial"}),S(!1),b(null),p([]),x([]),A(null),K.current?.close(),K.current=null},isCreating:U}),$&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(pc,{size:16}),t.jsx("span",{children:yt?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),yt&&t.jsx("button",{type:"button",onClick:()=>{k()},disabled:J,className:"btn btn-primary session-lock-take-control",children:J?"Taking control...":"Take Control"})]})})]})]})}):null}function m$({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),m=i.useCallback(()=>{let f;e.type==="text"?f={[e.id]:l}:e.type==="confirm"?f={[e.id]:r[e.id]===!0}:f=r;const p=d.trim();p.length>0&&(f={...f,_comment:p}),a(f)},[d,e,r,l,a]);i.useEffect(()=>{o({}),c(""),u("")},[e.id]);const h=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(mi,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(f=>t.jsx("div",{className:`planning-progress-step ${f<=n?"active":""}`},f))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&l.trim()&&(f.preventDefault(),m())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(f=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:f.id,checked:r[e.id]===f.id,onChange:()=>o({[e.id]:f.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(f=>{const p=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:f.id,checked:p.includes(f.id),onChange:g=>{const x=g.target.checked?[...p,f.id]:p.filter(w=>w!==f.id);o({[e.id]:x})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(Gn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(un,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:d,onChange:f=>u(f.target.value)})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!h(),children:["Continue",t.jsx($o,{size:16,className:"icon-ml-4"})]})})]})}function h$({summary:e,historyEntries:n,onSummaryChange:s,onApprove:a,onStartOver:r,isCreating:o}){const[l,c]=i.useState(()=>new Set(e.milestones.map((j,C)=>C))),[d,u]=i.useState(()=>{const j=new Set;return e.milestones.forEach((C,v)=>{C.slices.forEach((N,I)=>j.add(`${v}-${I}`))}),j}),m=j=>{c(C=>{const v=new Set(C);return v.has(j)?v.delete(j):v.add(j),v})},h=j=>{u(C=>{const v=new Set(C);return v.has(j)?v.delete(j):v.add(j),v})},f=(j,C)=>{const v=[...e.milestones];v[j]={...v[j],...C},s({...e,milestones:v})},p=(j,C,v)=>{const N=[...e.milestones],I=[...N[j].slices];I[C]={...I[C],...v},N[j]={...N[j],slices:I},s({...e,milestones:N})},g=(j,C,v,N)=>{const I=[...e.milestones],F=[...I[j].slices],_=[...F[C].features];_[v]={..._[v],...N},F[C]={...F[C],features:_},I[j]={...I[j],slices:F},s({...e,milestones:I})},x=j=>{const C=e.milestones.filter((v,N)=>N!==j);s({...e,milestones:C})},w=(j,C)=>{const v=[...e.milestones];v[j]={...v[j],slices:v[j].slices.filter((N,I)=>I!==C)},s({...e,milestones:v})},b=(j,C,v)=>{const N=[...e.milestones],I=[...N[j].slices];I[C]={...I[C],features:I[C].features.filter((F,_)=>_!==v)},N[j]={...N[j],slices:I},s({...e,milestones:N})},y=(j,C)=>{const v=[...e.milestones],N=[...v[j].slices];N[C]={...N[C],features:[...N[C].features,{title:"New feature",description:""}]},v[j]={...v[j],slices:N},s({...e,milestones:v})},S=e.milestones.reduce((j,C)=>j+C.slices.reduce((v,N)=>v+N.features.length,0),0);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(mi,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Gn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",S," features. Review and edit before approving."]})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Title"}),t.jsx("input",{type:"text",className:"form-input",value:e.missionTitle||"",onChange:j=>s({...e,missionTitle:j.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:j=>s({...e,missionDescription:j.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((j,C)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(C),children:[l.has(C)?t.jsx(pn,{size:16,className:"icon-text-secondary"}):t.jsx(On,{size:16,className:"icon-text-secondary"}),t.jsx($a,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:j.title,onChange:v=>f(C,{title:v.target.value}),onClick:v=>v.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:v=>{v.stopPropagation(),x(C)},title:"Remove milestone",children:t.jsx(_n,{size:14,className:"icon-text-secondary"})})]}),l.has(C)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:j.description||"",onChange:v=>f(C,{description:v.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:j.verification||"",onChange:v=>f(C,{verification:v.target.value})})]}),j.slices.map((v,N)=>{const I=`${C}-${N}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(I),children:[d.has(I)?t.jsx(pn,{size:14,className:"icon-text-secondary"}):t.jsx(On,{size:14,className:"icon-text-secondary"}),t.jsx(eu,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:v.title,onChange:F=>p(C,N,{title:F.target.value}),onClick:F=>F.stopPropagation()}),j.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:F=>{F.stopPropagation(),w(C,N)},title:"Remove slice",children:t.jsx(_n,{size:12,className:"icon-text-secondary"})})]}),d.has(I)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:v.verification||"",onChange:F=>p(C,N,{verification:F.target.value})})]}),v.features.map((F,_)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(Gd,{size:12,className:"icon-feature"}),t.jsxs("div",{className:"roadmap-feature-content",children:[t.jsx("input",{type:"text",className:"form-input roadmap-input-feature",value:F.title,onChange:M=>g(C,N,_,{title:M.target.value})}),F.description&&t.jsx("p",{className:"roadmap-feature-text",children:F.description}),F.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",F.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(C,N,_),title:"Remove feature",children:t.jsx(_n,{size:12,className:"icon-text-secondary"})})]},_)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(C,N),children:[t.jsx(Mn,{size:12}),"Add Feature"]})]})]},N)})]})]},C))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(Ha,{size:16,className:"icon-mr-4"}),"Start Over"]}),t.jsx("button",{className:"btn btn-primary",onClick:a,disabled:o||e.milestones.length===0,children:o?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Gn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}const p$=30,f$=16,g$=16;function b$(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let Dl=null;function mv(){return Dl===null&&(Dl=window.visualViewport?.height??window.innerHeight),Dl}function x$(e){const n=mv();e>n&&(Dl=e)}function v$(e){return e?e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?!new Set(["checkbox","radio","button","submit","reset","file","range","color","hidden"]).has(e.type):e instanceof HTMLElement&&e.isContentEditable:!1}function pf(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=v$(document.activeElement),s=e.offsetTop;n||x$(e.height);const a=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(a>0&&n)return{overlap:a,open:!0,vvHeight:e.height,vvOffsetTop:s};const r=mv(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=p$&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=f$&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=g$?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function Zi({enabled:e=!0}={}){const[n,s]=i.useState(0),[a,r]=i.useState(null),[o,l]=i.useState(0),[c,d]=i.useState(!1);return i.useEffect(()=>{if(!e||!b$()){s(0),r(null),l(0),d(!1);return}const u=window.visualViewport;if(!u){s(0),r(null),l(0),d(!1);return}const m=()=>{const v=pf();s(v.overlap),r(v.vvHeight),l(v.vvOffsetTop),d(v.open)},h=()=>{const v=pf();s(v.overlap),r(v.vvHeight),d(v.open)},f=[],p=v=>{if(typeof window>"u")return;const N=window.setTimeout(()=>{typeof window>"u"||m()},v);f.push(N)};let g=null,x=0,w=-1,b=0;const y=()=>{g!==null&&typeof window<"u"&&(window.cancelAnimationFrame(g),g=null)},S=()=>{if(typeof window>"u")return;m();const v=window.visualViewport?.offsetTop??0;if(v===w?b+=1:(b=0,w=v),b>=2||performance.now()>x){g=null;return}g=window.requestAnimationFrame(S)},j=()=>{typeof window>"u"||(y(),x=performance.now()+1500,w=-1,b=0,g=window.requestAnimationFrame(S))},C=()=>{m(),p(50),p(200),p(500),p(1e3),p(1500),j()};return C(),u.addEventListener("resize",m),u.addEventListener("scroll",h),document.addEventListener("focusin",C),document.addEventListener("focusout",m),document.addEventListener("visibilitychange",C),window.addEventListener("pageshow",C),()=>{u.removeEventListener("resize",m),u.removeEventListener("scroll",h),document.removeEventListener("focusin",C),document.removeEventListener("focusout",m),document.removeEventListener("visibilitychange",C),window.removeEventListener("pageshow",C);for(const v of f)clearTimeout(v);y(),s(0),r(null),l(0),d(!1)}},[e]),{keyboardOverlap:n,viewportHeight:a,viewportOffsetTop:o,keyboardOpen:c}}function y$({isOpen:e,onClose:n,onApplied:s,targetType:a,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:d}){const u=ri();Ni(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=Zi({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[x,w]=i.useState({type:"initial"}),[b,y]=i.useState(null),[S,j]=i.useState([]),[C,v]=i.useState([]),[N,I]=i.useState(null),[F,_]=i.useState(""),[M,z]=i.useState(!0),[U,R]=i.useState(!1),[D,K]=i.useState(!1),Z=i.useRef(null),ne=i.useRef(null),O=i.useRef(null),A=i.useRef(null),[P,$]=i.useState(null),k=i.useMemo(()=>Va(),[]);Ec(e?P:null);const{activeTabMap:J,broadcastUpdate:ce,broadcastCompleted:je,broadcastLock:He,broadcastUnlock:xe,broadcastHeartbeat:Ne}=Fr(),Y=a==="milestone"?e0:a0,ie=a==="milestone"?t0:r0,ee=a==="milestone"?n0:o0,oe=a==="milestone"?s0:l0,W=a==="milestone"?i0:c0,L=a==="milestone"?"Milestone":"Slice",pe=a==="milestone"?"milestone_interview":"slice_interview",fe=i.useCallback(Ue=>{ne.current?.close();const me=ee(Ue,c,{onThinking:re=>{_(_e=>_e+re),ce({sessionId:Ue,status:"generating",needsInput:!1,owningTabId:k,type:pe,title:o,projectId:c??null})},onQuestion:re=>{R(!1),B(),w({type:"question",sessionId:Ue,question:re}),_(""),ce({sessionId:Ue,status:"awaiting_input",needsInput:!0,owningTabId:k,type:pe,title:o,projectId:c??null})},onSummary:re=>{R(!1),B(),w({type:"summary",sessionId:Ue,summary:re}),I(re),_(""),ce({sessionId:Ue,status:"complete",needsInput:!1,owningTabId:k,type:pe,title:o,projectId:c??null})},onError:re=>{const _e=re||"Session failed while contacting the AI.";R(!1),y(null),w({type:"error",sessionId:Ue,errorMessage:_e}),_(""),O.current=Ue,ce({sessionId:Ue,status:"error",needsInput:!1,owningTabId:k,type:pe,title:o,projectId:c??null}),je({sessionId:Ue,status:"error"})},onComplete:()=>{R(!1),O.current=null,je({sessionId:Ue,status:"complete"})},onConnectionStateChange:re=>{R(re==="reconnecting")}});ne.current=me},[je,ce,ee,pe,c,k,o]),B=()=>{I(null),j([]),v([]),_("")},ve=i.useCallback(async()=>{y(null),B(),R(!1),w({type:"loading"});try{const{sessionId:Ue}=await Y(r,c);O.current=Ue,$(Ue),fe(Ue)}catch(Ue){R(!1),y(Ee(Ue)||`Failed to start ${L.toLowerCase()} interview`),w({type:"initial"}),O.current=null,$(null)}},[fe,c,Y,r,L]),Fe=i.useCallback(async()=>{y(null),K(!0);try{await W(r,c),s(),w({type:"applied"})}catch(Ue){y(Ee(Ue)||`Failed to skip ${L.toLowerCase()} interview`),K(!1)}},[s,c,W,r,L]);i.useEffect(()=>{e&&x.type==="initial"&&Z.current?.focus()},[e,x.type]),i.useEffect(()=>{if(!e||!d||x.type!=="initial")return;let Ue=!1;return Ti(d).then(me=>{if(Ue||!me)return;const re=jr(me.conversationHistory);if(v(re),$(me.id),j(re.map(_e=>_e.response).filter(_e=>!!(_e&&typeof _e=="object"&&!Array.isArray(_e)))),me.status==="awaiting_input"&&me.currentQuestion)try{const _e=JSON.parse(me.currentQuestion);O.current=me.id,w({type:"question",sessionId:me.id,question:_e})}catch{y("Failed to restore session question.")}else if(me.status==="complete"&&me.result)try{const _e=JSON.parse(me.result);O.current=me.id,I(_e),w({type:"summary",sessionId:me.id,summary:_e})}catch{y("Failed to restore session result.")}else me.status==="generating"?(O.current=me.id,me.thinkingOutput&&_(me.thinkingOutput),w({type:"loading"}),fe(me.id)):me.status==="error"&&(O.current=me.id,y(null),w({type:"error",sessionId:me.id,errorMessage:me.error??"The session encountered an error."}))}).catch(()=>{Ue||y("Failed to resume session.")}),()=>{Ue=!0}},[fe,e,d,x.type]),i.useEffect(()=>{e||(R(!1),$(null))},[e]),i.useEffect(()=>{if(!(!e||!P)){if(A.current!==P){A.current&&xe(A.current,k),He(P,k),A.current=P;return}!P&&A.current&&(xe(A.current,k),A.current=null)}},[He,xe,e,P,k]),i.useEffect(()=>{if(!e||!P||A.current!==P)return;Ne(k);const Ue=setInterval(()=>{Ne(k)},3e4);return()=>{clearInterval(Ue)}},[Ne,e,P,k]),i.useEffect(()=>()=>{ne.current?.close(),ne.current=null,A.current&&(xe(A.current,k),A.current=null)},[xe,k]);const ae=i.useCallback(()=>{ne.current?.close(),ne.current=null,n()},[n]),qe=i.useCallback(async()=>{ne.current?.close(),ne.current=null,B(),w({type:"initial"}),y(null),O.current=null,$(null),n()},[n]),Pe=i.useCallback(async Ue=>{if(x.type!=="question")return;const{sessionId:me}=x;y(null),j(re=>[...re,Ue]),v(re=>[...re,{question:x.question,response:Ue}]),w({type:"loading"}),_("");try{fe(me),await ie(me,Ue,c,k)}catch(re){ne.current?.close(),ne.current=null,y(Ee(re)||"Failed to submit response"),w({type:"question",sessionId:me,question:x.question})}},[fe,c,ie,k,x]),nt=i.useCallback(async()=>{if(x.type==="summary"){y(null),K(!0);try{await oe(x.sessionId,N||void 0,c),s(),w({type:"applied"})}catch(Ue){y(Ee(Ue)||"Failed to apply interview results"),K(!1)}}},[oe,N,s,c,x]),Be=()=>x.type==="question"?Math.min(S.length+1,6):6,de=x.type==="loading"||x.type==="question"||x.type==="summary"||x.type==="error",Ie=P?J.get(P):null,st=!!(Ie&&Ie.tabId!==k&&!Ie.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ue=>Ue.target===Ue.currentTarget&&qe(),role:"dialog","aria-modal":"true","data-testid":"milestone-slice-interview-modal",children:t.jsxs("div",{className:"modal modal-lg planning-modal",style:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(gs,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",L,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[de&&t.jsx("button",{className:"modal-send-to-background",onClick:ae,title:"Send to background","aria-label":"Send to background",children:t.jsx(Lo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:qe,"aria-label":"Close",children:t.jsx(un,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[b&&t.jsx("div",{className:"form-error planning-error",children:b}),U&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),st&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),x.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-intro",children:[t.jsx(gs,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",L," scope with AI"]}),t.jsxs("p",{className:"text-muted",children:["The AI will interview you to refine the ",a,"'s scope, acceptance criteria, and verification methods. Each ",a," can have its own refined plan or inherit context from the mission level."]}),l&&t.jsxs("div",{className:"planning-context-info",children:[t.jsx("span",{className:"planning-context-label",children:"Mission context:"}),t.jsx("span",{className:"planning-context-text",children:l})]})]})}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>void ve(),children:[t.jsx(gs,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void Fe(),disabled:D,children:[D?t.jsx(jt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:qe,children:"Cancel"})]})]}),x.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:F?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>z(!M),type:"button",children:M?"Hide thinking":"Show thinking"}),M&&F&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:F})})]})]}),x.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[C.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(mi,{entries:C}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:x.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:qe,children:"Cancel"})})]})]})}),x.type==="question"&&t.jsx(w$,{question:x.question,progress:Be(),historyEntries:C,onSubmit:Pe}),x.type==="summary"&&N&&t.jsx(k$,{summary:N,historyEntries:C,onSummaryChange:I,onApply:nt,onCancel:qe,isApplying:D}),x.type==="applied"&&t.jsxs("div",{className:"planning-summary planning-applied",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-applied-content",children:[t.jsx(Gn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[L," Updated"]}),t.jsxs("p",{className:"text-muted",children:["The ",a,"'s scope and verification have been ",x.type==="applied"?"applied":"updated","."]})]})}),t.jsx("div",{className:"planning-view-footer",children:t.jsx("button",{className:"btn btn-primary",onClick:s,children:"Done"})})]})]})]})}):null}function w$({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),m=i.useCallback(()=>{let f;e.type==="text"?f={[e.id]:l}:e.type==="confirm"?f={[e.id]:r[e.id]===!0}:f=r;const p=d.trim();p.length>0&&(f={...f,_comment:p}),a(f)},[d,e,r,l,a]);i.useEffect(()=>{o({}),c(""),u("")},[e.id]);const h=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(mi,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(f=>t.jsx("div",{className:`planning-progress-step ${f<=n?"active":""}`},f))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&l.trim()&&(f.preventDefault(),m())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(f=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:f.id,checked:r[e.id]===f.id,onChange:()=>o({[e.id]:f.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(f=>{const p=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:f.id,checked:p.includes(f.id),onChange:g=>{const x=g.target.checked?[...p,f.id]:p.filter(w=>w!==f.id);o({[e.id]:x})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(Gn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(un,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:d,onChange:f=>u(f.target.value)})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!h(),children:["Continue",t.jsx($o,{size:16,className:"icon-ml-4"})]})})]})}function k$({summary:e,historyEntries:n,onSummaryChange:s,onApply:a,onCancel:r,isApplying:o}){const[l,c]=i.useState(e),[d,u]=i.useState(!0),m=(h,f)=>{const p={...l,[h]:f};c(p),s(p)};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(mi,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-panel",children:[t.jsx("div",{className:"planning-summary-header",children:t.jsxs("button",{className:"planning-summary-toggle",onClick:()=>u(!d),"aria-expanded":d,children:[d?t.jsx(pn,{size:16}):t.jsx(On,{size:16}),t.jsx("span",{children:"Refined Scope"})]})}),d&&t.jsxs("div",{className:"planning-summary-content",children:[l.description&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:l.description,onChange:h=>m("description",h.target.value)})]}),l.planningNotes&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Planning Notes"}),t.jsx("textarea",{rows:3,value:l.planningNotes,onChange:h=>m("planningNotes",h.target.value)})]}),l.verification&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Verification Criteria"}),t.jsx("textarea",{rows:2,value:l.verification,onChange:h=>m("verification",h.target.value)})]}),!l.description&&!l.planningNotes&&!l.verification&&t.jsx("p",{className:"text-muted planning-summary-empty",children:"No additional details were generated for this item."})]})]})]}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:a,disabled:o,children:[o?t.jsx(jt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const ff=300,xl=220,vl=560,gf="fusion:mission-sidebar-width",to={planning:{bg:"var(--mission-planning-bg)",text:"var(--mission-planning-text)"},active:{bg:"var(--mission-active-bg)",text:"var(--mission-active-text)"},blocked:{bg:"var(--mission-blocked-bg)",text:"var(--mission-blocked-text)"},complete:{bg:"var(--mission-complete-bg)",text:"var(--mission-complete-text)"},archived:{bg:"var(--mission-archived-bg)",text:"var(--mission-archived-text)"}},bf={planning:{bg:"var(--mission-planning-bg)",text:"var(--mission-planning-text)"},active:{bg:"var(--mission-active-bg)",text:"var(--mission-active-text)"},blocked:{bg:"var(--mission-blocked-bg)",text:"var(--mission-blocked-text)"},complete:{bg:"var(--mission-complete-bg)",text:"var(--mission-complete-text)"}},xf={pending:{bg:"var(--slice-pending-bg)",text:"var(--slice-pending-text)"},active:{bg:"var(--slice-active-bg)",text:"var(--slice-active-text)"},complete:{bg:"var(--slice-complete-bg)",text:"var(--slice-complete-text)"}},yl={defined:{bg:"var(--feature-defined-bg)",text:"var(--feature-defined-text)"},triaged:{bg:"var(--feature-triaged-bg)",text:"var(--feature-triaged-text)"},"in-progress":{bg:"var(--feature-in-progress-bg)",text:"var(--feature-in-progress-text)"},done:{bg:"var(--feature-done-bg)",text:"var(--feature-done-text)"},blocked:{bg:"var(--mission-blocked-bg)",text:"var(--mission-blocked-text)"}},wl={inactive:{bg:"var(--autopilot-inactive-bg)",text:"var(--autopilot-inactive-text)"},watching:{bg:"var(--autopilot-watching-bg)",text:"var(--autopilot-watching-text)"},activating:{bg:"var(--autopilot-activating-bg)",text:"var(--autopilot-activating-text)"},completing:{bg:"var(--autopilot-completing-bg)",text:"var(--autopilot-completing-text)"}},kl={pending:{bg:"var(--assertion-pending-bg)",text:"var(--assertion-pending-text)"},passed:{bg:"var(--assertion-passed-bg)",text:"var(--assertion-passed-text)"},failed:{bg:"var(--assertion-failed-bg)",text:"var(--assertion-failed-text)"},blocked:{bg:"var(--assertion-blocked-bg)",text:"var(--assertion-blocked-text)"}},vf={not_started:{bg:"var(--assertion-pending-bg)",text:"var(--assertion-pending-text)"},needs_coverage:{bg:"var(--loop-needs-fix-bg)",text:"var(--loop-needs-fix-text)"},ready:{bg:"var(--loop-validating-bg)",text:"var(--loop-validating-text)"},passed:{bg:"var(--loop-passed-bg)",text:"var(--loop-passed-text)"},failed:{bg:"var(--loop-blocked-bg)",text:"var(--loop-blocked-text)"},blocked:{bg:"var(--loop-blocked-bg)",text:"var(--loop-blocked-text)"}},j$=3,N$=new Set(["generating","awaiting_input","error"]);function S$(e){switch(e){case"generating":return"Generating plan";case"awaiting_input":return"Awaiting input";case"error":return"Needs retry";default:return e}}function yf(e){return e==="error"?"Retry interview":"Resume interview"}function C$(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function wf({state:e}){const n=e==="planned"?"mission-plan-state-indicator--planned":e==="needs_update"?"mission-plan-state-indicator--needs-update":"mission-plan-state-indicator--not-started",s=e==="planned"?"Planned":e==="needs_update"?"Needs update":"Not planned";return t.jsx("span",{className:`mission-plan-state-indicator ${n}`,title:s,"aria-label":s})}function kf(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const jf={title:"",description:"",status:"planning",autopilotEnabled:!1},Cd={title:"",description:"",status:"planning",dependencies:[]},Ed={title:"",description:"",status:"pending"},_d={title:"",description:"",acceptanceCriteria:"",status:"defined"},E$=3600*1e3;function ec(e){if(!e)return"—";const n=new Date(e).getTime();if(Number.isNaN(n))return"—";const s=Date.now()-n;if(s<0)return"just now";const a=Math.floor(s/(60*1e3));if(a<1)return"just now";if(a<60)return`${a}m ago`;const r=Math.floor(a/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function _$(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=E$,s=e.totalTasks>0&&e.tasksFailed>e.totalTasks*.3;return n||s?"error":e.tasksFailed>0?"warning":e.tasksFailed===0&&e.tasksInFlight<=e.totalTasks?"healthy":"warning"}function M$(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.missionId=="string"&&typeof n.tasksCompleted=="number"&&typeof n.tasksFailed=="number"&&typeof n.tasksInFlight=="number"&&typeof n.totalTasks=="number"&&typeof n.estimatedCompletionPercent=="number"}function A$(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.id=="string"&&typeof n.missionId=="string"&&typeof n.eventType=="string"&&typeof n.description=="string"&&typeof n.timestamp=="string"}function Md(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.rollup?.milestoneId=="string"&&typeof n.rollup?.state=="string"&&Array.isArray(n.validationTelemetry?.validationRounds)&&typeof n.validationTelemetry?.totalRuns=="number"&&n.validationContract!==void 0&&Array.isArray(n.fixFeatures)}const hv=["feature_triaged","feature_completed"],pv=["slice_activated","slice_completed","milestone_completed"],fv=["mission_started","mission_paused","mission_resumed","mission_completed"],gv=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Nf(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return fv.includes(e);case"tasks":return hv.includes(e);case"slices":return pv.includes(e);case"autopilot":return gv.includes(e);default:return!0}}function R$(e){return e==="error"||e==="warning"?"mission-event__type--error":fv.includes(e)?"mission-event__type--state":hv.includes(e)?"mission-event__type--task":pv.includes(e)?"mission-event__type--slice":gv.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function I$(e){return e.replace(/_/g," ")}function T$(e,n){return n?e==="watching"?`Watching since ${ec(n)}`:`Last activation ${ec(n)}`:null}function P$({isOpen:e,isInline:n=!1,onClose:s,addToast:a,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:d,milestoneSliceResumeSessionId:u,onMilestoneSliceResumeFetchError:m}){const h=n||e,[f,p]=i.useState([]),[g,x]=i.useState(null),[w,b]=i.useState(!0),[y,S]=i.useState(!1),j=ri()==="mobile",[C,v]=i.useState(()=>{if(typeof window>"u")return ff;const H=window.localStorage.getItem(gf),ze=H?Number(H):NaN;return Number.isFinite(ze)?Math.max(xl,Math.min(vl,ze)):ff}),N=i.useCallback(H=>{try{window.localStorage.setItem(gf,String(H))}catch{}},[]),I=i.useCallback(H=>{if(j)return;H.preventDefault(),H.stopPropagation();const ze=H.currentTarget;typeof ze.setPointerCapture=="function"&&ze.setPointerCapture(H.pointerId);const Ge=H.clientX,Ct=C;let Nn=Ct;document.body.style.userSelect="none";const Vt=Ze=>{const ot=Ze.clientX-Ge,Bt=Math.max(xl,Math.min(vl,Ct+ot));Nn=Bt,v(Bt)},kn=Ze=>{typeof ze.releasePointerCapture=="function"&&ze.releasePointerCapture(Ze.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",Vt),document.removeEventListener("pointerup",kn),N(Nn)};document.addEventListener("pointermove",Vt),document.addEventListener("pointerup",kn)},[j,N,C]),F=i.useCallback(H=>{if(j||H.key!=="ArrowLeft"&&H.key!=="ArrowRight")return;H.preventDefault();const ze=H.shiftKey?50:10,Ge=H.key==="ArrowLeft"?-ze:ze,Ct=Math.max(xl,Math.min(vl,C+Ge));v(Ct),N(Ct)},[j,N,C]),[_,M]=i.useState(!1),[z,U]=i.useState(null),[R,D]=i.useState(jf),[K,Z]=i.useState(!1),[ne,O]=i.useState(new Set),[A,P]=i.useState(new Set),[$,k]=i.useState(null),[J,ce]=i.useState(Cd),[je,He]=i.useState(!1),[xe,Ne]=i.useState(null),[Y,ie]=i.useState(Ed),[ee,oe]=i.useState(!1),[W,L]=i.useState(null),[pe,fe]=i.useState(null),[B,ve]=i.useState(_d),[Fe,ae]=i.useState(!1),[qe,Pe]=i.useState(null),[nt,Be]=i.useState(null),[de,Ie]=i.useState(""),[$e,st]=i.useState(!1),[Ue,me]=i.useState([]),[re,_e]=i.useState(void 0),xt=i.useRef(null),ut=re??(c&&xt.current===c?void 0:c),[Qe,vt]=i.useState(null),[Ae,Je]=i.useState(null),[dt,Nt]=i.useState(null);i.useEffect(()=>{h&&ut&&st(!0)},[h,ut]),i.useEffect(()=>{c&&xt.current!==c&&(xt.current=null)},[c]),i.useEffect(()=>{if(!h)return;let H=!1;return zu(r).then(ze=>{if(H)return;const Ge=ze.filter(Ct=>Ct.type!=="mission_interview"||!N$.has(Ct.status)?!1:r?Ct.projectId===r:Ct.projectId==null);me(Ge)}).catch(ze=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",ze)}),()=>{H=!0}},[h,r,ut]),i.useEffect(()=>{if(!h||!u)return;let H=!1;return Ti(u).then(ze=>{if(!(H||!ze))try{const Ge=JSON.parse(ze.inputPayload||"{}");Ge.targetId&&Ge.targetType&&vt({type:Ge.targetType,id:Ge.targetId,title:Ge.targetTitle||ze.title,resumeSessionId:u})}catch{vt({type:"milestone",id:"",title:ze.title,resumeSessionId:u})}}).catch(ze=>{H||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",ze),m?.())}),()=>{H=!0}},[h,u,m]);const[yt,Se]=i.useState(null),[G,ge]=i.useState(new Map),[pt,ke]=i.useState(null),[tt,Rt]=i.useState({title:"",assertion:"",status:"pending"}),[Re,be]=i.useState(!1),[rt,lt]=i.useState(null),[gt,St]=i.useState(new Map),[Lt,Yt]=i.useState(new Set),[tn,mn]=i.useState(new Set),[Qt,yn]=i.useState(null),[Gt,on]=i.useState(new Map),[sn,ln]=i.useState(null),[Wt,ye]=i.useState(null),[Le,Ke]=i.useState(!0),[mt,Ve]=i.useState(new Set),[Pt,Ot]=i.useState(new Map),[bt,Dt]=i.useState(null),[Ft,Ht]=i.useState(new Map),[rn,Xt]=i.useState(null),[an,Me]=i.useState(new Map),[it,kt]=i.useState(new Map),[$t,se]=i.useState("structure"),[te,De]=i.useState([]),ft=i.useRef([]),qt=i.useRef([]),zt=i.useRef(null),Pn=i.useRef(null),he=i.useRef("structure"),ht=i.useRef("all"),[at,wt]=i.useState(!1),[Xe,Et]=i.useState(0),[Zt,le]=i.useState("all"),[ct,nn]=i.useState(new Set),Rn=i.useRef(null),Un=i.useRef(null);qt.current=f,zt.current=g,Pn.current=sn,he.current=$t,ht.current=Zt;const wn=i.useCallback((H="auto")=>{const ze=Un.current;if(ze&&typeof ze.scrollIntoView=="function"){ze.scrollIntoView({block:"end",behavior:H});return}const Ge=Rn.current;Ge&&(Ge.scrollTop=Ge.scrollHeight)},[]),rs=i.useCallback(()=>{const H=Rn.current;return H?H.scrollHeight-H.scrollTop-H.clientHeight<=100:!0},[]),_s=i.useCallback(async H=>{if(H.length===0){kt(new Map);return}const ze=await k1(r);kt(Ge=>{const Ct=new Map(Ge);for(const[Nn,Vt]of Object.entries(ze))M$(Vt)&&Ct.set(Nn,Vt);return Ct})},[r]),bn=i.useCallback(async()=>{try{b(!0);const H=await b1(r);p(H),_s(H)}catch(H){a(Ee(H)||"Failed to load missions","error")}finally{b(!1)}},[a,r,_s]),Ut=i.useCallback(async H=>{try{S(!0);const ze=await fb(H,r);if(!ze||!Array.isArray(ze.milestones)){S(!1);return}if(x(ze),ze.milestones.length>0){const Ge=ze.milestones[0].id;ln(Ge),Ke(!0),O(new Set([Ge])),Dc(Ge,r).then(Ct=>{ge(Nn=>{const Vt=new Map(Nn);return Vt.set(Ge,Ct),Vt})}).catch(()=>{}),Lc(Ge,r).then(Ct=>{on(Nn=>{const Vt=new Map(Nn);return Vt.set(Ge,Ct),Vt})}).catch(()=>{}),ze.milestones[0].slices.length>0&&P(new Set([ze.milestones[0].slices[0].id]))}else ln(null),ye(null)}catch(ze){a(Ee(ze)||"Failed to load mission details","error")}finally{S(!1)}},[a,r]);i.useEffect(()=>{if(!h||!sn){ye(null);return}let H=!1;return ye(null),nh(sn,r).then(ze=>{if(!H){if(!Md(ze)){ye(null);return}ye(ze),on(Ge=>{const Ct=new Map(Ge);return Ct.set(sn,ze.rollup),Ct})}}).catch(()=>{H||ye(null)}),()=>{H=!0}},[h,sn,r]),i.useEffect(()=>{Ke(!0)},[sn]);const xs=i.useCallback(H=>{!H||H!==Pn.current||nh(H,r).then(ze=>{Pn.current!==H||!Md(ze)||(ye(ze),on(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze.rollup),Ct}))}).catch(()=>{})},[r]),xn=i.useCallback(async(H,ze)=>{const Ge=ze?.append??!1,Ct=Ge?ft.current.length:0;Ge||(wt(!0),nn(new Set));try{const Nn=await w1(H,{limit:50,offset:Ct,eventType:void 0},r),Vt=Nn.events.filter(kn=>Nf(kn.eventType,Zt));De(kn=>{if(!Ge)return ft.current=Vt,Vt;const Ze=new Set(kn.map(Bt=>Bt.id)),ot=[...kn];for(const Bt of Vt)Ze.has(Bt.id)||ot.push(Bt);return ft.current=ot,ot}),Et(Nn.total),Ge||requestAnimationFrame(()=>{wn("auto")})}catch(Nn){a(Ee(Nn)||"Failed to load mission activity","error")}finally{Ge||wt(!1)}},[a,Zt,r,wn]);i.useEffect(()=>{ft.current=te},[te]),i.useEffect(()=>{h&&(bn(),x(null),ln(null),ye(null),De([]),Et(0),se("structure"),le("all"),nn(new Set))},[h,bn]);const Xn=i.useRef(null);i.useEffect(()=>{h&&d&&Xn.current!==d&&f.length>0&&(Xn.current=d,Ut(d))},[h,d,f,Ut]),i.useEffect(()=>{h||(Xn.current=null)},[h]);const $n=i.useRef(!1);i.useEffect(()=>{!h||!n||j||w||$n.current||g||d||f.length!==0&&($n.current=!0,Ut(f[0].id))},[h,n,j,w,f,g,d,Ut]),i.useEffect(()=>{h||($n.current=!1)},[h]),i.useEffect(()=>{!h||!g||$t!=="activity"||xn(g.id)},[$t,h,xn,g,Zt]),i.useEffect(()=>{if(!h||typeof EventSource>"u")return;const H=new URLSearchParams;r&&H.set("projectId",r);const ze=`/api/events${H.size>0?`?${H.toString()}`:""}`,Ge=()=>{_s(qt.current)},Ct=Tn=>{Ge();const Vn=Tn;if(Vn.data)try{const dn=JSON.parse(Vn.data);dn?.id&&p(Gs=>Gs.map(Ps=>Ps.id===dn.id?{...Ps,...dn}:Ps))}catch{}zt.current&&Ut(zt.current.id)},Nn=Tn=>{Ge(),zt.current&&Ut(zt.current.id)},Vt=()=>{Ge(),zt.current&&Ut(zt.current.id)},kn=Tn=>{Ge(),zt.current&&Ut(zt.current.id)},Ze=Tn=>{const Vn=Tn;if(Vn.data)try{const dn=JSON.parse(Vn.data);dn&&dn.featureId&&(oi(dn.featureId),gn(dn.featureId),dn.milestoneId&&xs(dn.milestoneId))}catch{}},ot=Tn=>{const Vn=Tn;if(Vn.data)try{const dn=JSON.parse(Vn.data);dn&&dn.featureId&&(oi(dn.featureId),gn(dn.featureId),dn.milestoneId&&xs(dn.milestoneId),zt.current&&Ut(zt.current.id))}catch{}},Bt=Tn=>{const Vn=Tn;if(Vn.data)try{const dn=JSON.parse(Vn.data);dn&&dn.milestoneId&&(Zn(dn.milestoneId),xs(dn.milestoneId))}catch{}},In=Tn=>{const Vn=Tn;if(Vn.data)try{const dn=JSON.parse(Vn.data);dn&&dn.milestoneId&&(ns(dn.milestoneId),Zn(dn.milestoneId),xs(dn.milestoneId))}catch{}};return hi(ze,{events:{"mission:updated":Ct,"slice:updated":Nn,"feature:updated":Vt,"milestone:updated":kn,"mission:event":Tn=>{Ge();const Vn=zt.current;if(!Vn||he.current!=="activity")return;const dn=rs(),Gs=Tn;if(Gs.data)try{const Ps=JSON.parse(Gs.data);if(!A$(Ps)||Ps.missionId!==Vn.id||!Nf(Ps.eventType,ht.current))return;De(fi=>{const Ca=fi.filter(qr=>qr.id!==Ps.id);return[Ps,...Ca].slice(0,100)}),Et(fi=>fi+1),dn&&requestAnimationFrame(()=>{const fi=Rn.current;fi&&(fi.scrollTop=0)})}catch{}},"validator-run:started":Ze,"validator-run:completed":ot,"milestone:validation:updated":Bt,"assertion:created":In,"assertion:updated":In,"assertion:deleted":In,"assertion:linked":In,"assertion:unlinked":In,"fix-feature:created":Tn=>{const Vn=Tn;if(Vn.data)try{const dn=JSON.parse(Vn.data);if(dn&&dn.sourceFeatureId){oi(dn.sourceFeatureId);const Gs=dn?.feature?.sliceId,Ps=zt.current;if(Gs&&Ps){const fi=Ps.milestones.find(Ca=>Ca.slices.some(qr=>qr.id===Gs));fi&&xs(fi.id)}zt.current&&Ut(zt.current.id)}}catch{}}}})},[h,rs,Ut,_s,r,xs]);const vs=i.useCallback(H=>{U(H.id),M(!1),D({title:H.title,description:H.description||"",status:H.status,autopilotEnabled:H.autopilotEnabled??!1})},[]),ms=i.useCallback(()=>{U(null),M(!1),D(jf)},[]),hs=i.useCallback(async()=>{if(!R.title.trim()){a("Mission title is required","error");return}try{if(Z(!0),_)await x1({title:R.title.trim(),description:R.description.trim()||void 0,autopilotEnabled:R.autopilotEnabled},r),a("Mission created","success");else if(z){const H={title:R.title.trim(),description:R.description.trim()||void 0,status:R.status,autopilotEnabled:R.autopilotEnabled};R.autopilotEnabled&&(H.autoAdvance=!0),await v1(z,H,r),a("Mission updated","success"),g?.id===z&&await Ut(z)}await bn(),ms()}catch(H){a(Ee(H)||"Failed to save mission","error")}finally{Z(!1)}},[R,_,z,a,bn,Ut,g,ms,r]),Jn=i.useCallback(async H=>{try{await y1(H,r),a("Mission deleted","success"),g?.id===H&&x(null),await bn(),Se(null)}catch(ze){a(Ee(ze)||"Failed to delete mission","error")}},[a,bn,g,r]),ps=i.useCallback(()=>{He(!0),k(null),ce(Cd)},[]),Ns=i.useCallback(H=>{k(H.id),He(!1),ce({title:H.title,description:H.description||"",status:H.status,dependencies:H.dependencies})},[]),Yn=i.useCallback(()=>{k(null),He(!1),ce(Cd)},[]),ys=i.useCallback(async()=>{if(!J.title.trim()){a("Milestone title is required","error");return}try{Z(!0),je&&g?(await j1(g.id,{title:J.title.trim(),description:J.description.trim()||void 0,dependencies:J.dependencies},r),a("Milestone created","success")):$&&(await N1($,{title:J.title.trim(),description:J.description.trim()||void 0,status:J.status,dependencies:J.dependencies},r),a("Milestone updated","success")),await Ut(g.id),Yn()}catch(H){a(Ee(H)||"Failed to save milestone","error")}finally{Z(!1)}},[J,je,$,g,a,Ut,Yn,R.title,r]),ws=i.useCallback(async H=>{try{await S1(H,r),a("Milestone deleted","success"),await Ut(g.id),Se(null)}catch(ze){a(Ee(ze)||"Failed to delete milestone","error")}},[a,Ut,g,r]),Ms=i.useCallback(H=>{ln(H),Ke(!0),O(ze=>{const Ge=new Set(ze);return!Ge.has(H)?(Ge.add(H),Dc(H,r).then(Nn=>{ge(Vt=>{const kn=new Map(Vt);return kn.set(H,Nn),kn})}).catch(()=>{}),Lc(H,r).then(Nn=>{on(Vt=>{const kn=new Map(Vt);return kn.set(H,Nn),kn})}).catch(()=>{})):Ge.delete(H),Ge})},[r]),X=i.useCallback(H=>{L(H),oe(!0),Ne(null),ie(Ed)},[]),E=i.useCallback(H=>{Ne(H.id),oe(!1),ie({title:H.title,description:H.description||"",status:H.status})},[]),ue=i.useCallback(()=>{Ne(null),oe(!1),L(null),ie(Ed)},[]),Ce=i.useCallback(async()=>{if(!Y.title.trim()){a("Slice title is required","error");return}try{Z(!0),ee&&W?(await C1(W,{title:Y.title.trim(),description:Y.description.trim()||void 0},r),a("Slice created","success")):xe&&(await E1(xe,{title:Y.title.trim(),description:Y.description.trim()||void 0,status:Y.status},r),a("Slice updated","success")),await Ut(g.id),ue()}catch(H){a(Ee(H)||"Failed to save slice","error")}finally{Z(!1)}},[Y,ee,xe,W,g,a,Ut,ue,r]),We=i.useCallback(async H=>{try{await _1(H,r),a("Slice deleted","success"),await Ut(g.id),Se(null)}catch(ze){a(Ee(ze)||"Failed to delete slice","error")}},[a,Ut,g,r]),At=i.useCallback(async H=>{try{await M1(H,r),a("Slice activated","success"),await Ut(g.id)}catch(ze){a(Ee(ze)||"Failed to activate slice","error")}},[a,Ut,g,r]),q=i.useCallback(H=>{P(ze=>{const Ge=new Set(ze);return Ge.has(H)?Ge.delete(H):Ge.add(H),Ge})},[]),we=i.useCallback(H=>{Pe(H),ae(!0),fe(null),ve(_d)},[]),Oe=i.useCallback(H=>{fe(H.id),ae(!1),ve({title:H.title,description:H.description||"",acceptanceCriteria:H.acceptanceCriteria||"",status:H.status})},[]),It=i.useCallback(()=>{fe(null),ae(!1),Pe(null),ve(_d)},[]),Kt=i.useCallback(async()=>{if(!B.title.trim()){a("Feature title is required","error");return}try{Z(!0),Fe&&qe?(await A1(qe,{title:B.title.trim(),description:B.description.trim()||void 0,acceptanceCriteria:B.acceptanceCriteria.trim()||void 0},r),a("Feature created","success")):pe&&(await R1(pe,{title:B.title.trim(),description:B.description.trim()||void 0,acceptanceCriteria:B.acceptanceCriteria.trim()||void 0,status:B.status},r),a("Feature updated","success")),await Ut(g.id),It()}catch(H){a(Ee(H)||"Failed to save feature","error")}finally{Z(!1)}},[B,Fe,pe,qe,g,a,Ut,It,r]),fn=i.useCallback(async H=>{try{await I1(H,r),a("Feature deleted","success"),await Ut(g.id),Se(null)}catch(ze){a(Ee(ze)||"Failed to delete feature","error")}},[a,Ut,g,r]),An=i.useCallback(async()=>{if(!nt||!de.trim()){a("Task ID is required","error");return}try{await T1(nt,de.trim(),r),a("Feature linked to task","success"),await Ut(g.id),Be(null),Ie("")}catch(H){a(Ee(H)||"Failed to link feature to task","error")}},[nt,de,a,Ut,g,r]),jn=i.useCallback(async H=>{try{await P1(H,r),a("Feature unlinked from task","success"),await Ut(g.id)}catch(ze){a(Ee(ze)||"Failed to unlink feature","error")}},[a,Ut,g,r]),En=i.useCallback(async H=>{try{Z(!0),await $1(H,void 0,void 0,r),a("Feature triaged — task created","success"),await Ut(g.id)}catch(ze){a(Ee(ze)||"Failed to triage feature","error")}finally{Z(!1)}},[a,Ut,g,r]),ts=i.useCallback(async H=>{Nt(H);try{const ze=await d0(H,r);Je({featureId:H,enrichedDescription:ze.description})}catch{await En(H)}finally{Nt(null)}},[En,r]),Ln=i.useCallback(async()=>{Ae&&(Je(null),await En(Ae.featureId))},[En,Ae]),os=i.useCallback(()=>{Je(null)},[]),fs=i.useCallback(async H=>{try{Z(!0);const ze=await D1(H,r);a(`Triaged ${ze.count} feature${ze.count!==1?"s":""}`,"success"),await Ut(g.id)}catch(ze){a(Ee(ze)||"Failed to triage slice features","error")}finally{Z(!1)}},[a,Ut,g,r]),ns=i.useCallback(async H=>{try{const ze=await Dc(H,r);ge(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze),Ct})}catch{}},[r]),Zn=i.useCallback(async H=>{try{const ze=await Lc(H,r);on(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze),Ct})}catch{}},[r]),es=i.useCallback(async H=>{if(!tt.title.trim()||!tt.assertion.trim()){a("Title and assertion text are required","error");return}try{Z(!0),await L1(H,{title:tt.title.trim(),assertion:tt.assertion.trim(),status:tt.status},r),a("Assertion created","success"),await ns(H),await Zn(H),be(!1),Rt({title:"",assertion:"",status:"pending"})}catch(ze){a(Ee(ze)||"Failed to create assertion","error")}finally{Z(!1)}},[tt,a,ns,Zn,r]),Ss=i.useCallback(H=>{ke(H.id),Rt({title:H.title,assertion:H.assertion,status:H.status})},[]),ls=i.useCallback(()=>{ke(null),be(!1),Rt({title:"",assertion:"",status:"pending"})},[]),ss=i.useCallback(async(H,ze)=>{if(!tt.title.trim()||!tt.assertion.trim()){a("Title and assertion text are required","error");return}try{Z(!0),await O1(H,{title:tt.title.trim(),assertion:tt.assertion.trim(),status:tt.status},r),a("Assertion updated","success"),await ns(ze),await Zn(ze),ls()}catch(Ge){a(Ee(Ge)||"Failed to update assertion","error")}finally{Z(!1)}},[tt,a,ns,Zn,ls,r]),Zs=i.useCallback(async H=>{try{const ze=await B1(H,r);St(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze),Ct})}catch{}},[r]),Si=i.useCallback(async H=>{const ze=rt!==H;lt(Ge=>Ge===H?null:H),ze&&await Zs(H)},[rt,Zs]),ga=i.useCallback(H=>{lt(H),Zs(H),requestAnimationFrame(()=>{const ze=document.querySelector(`[data-mission-assertion-id="${H}"]`);ze instanceof HTMLElement&&typeof ze.scrollIntoView=="function"&&ze.scrollIntoView({behavior:"smooth",block:"center"})})},[Zs]),Wa=i.useCallback(async(H,ze)=>{try{Yt(Ge=>new Set(Ge).add(ze)),await F1(H,ze,r),a("Feature linked to assertion","success"),await Zs(ze),yn(null)}catch(Ge){a(Ee(Ge)||"Failed to link feature","error")}finally{Yt(Ge=>{const Ct=new Set(Ge);return Ct.delete(ze),Ct})}},[a,Zs,r]),Ka=i.useCallback(async(H,ze)=>{const Ge=`${H}-${ze}`;try{mn(Ct=>new Set(Ct).add(Ge)),await z1(H,ze,r),a("Feature unlinked from assertion","success"),await Zs(ze)}catch(Ct){a(Ee(Ct)||"Failed to unlink feature","error")}finally{mn(Ct=>{const Nn=new Set(Ct);return Nn.delete(Ge),Nn})}},[a,Zs,r]),Ga=i.useCallback(async H=>{try{Ve(Ge=>new Set(Ge).add(H)),await U1(H,r),a("Validation triggered","success");const ze=await sh(H,r);Ot(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze),Ct})}catch(ze){a(Ee(ze)||"Failed to trigger validation","error")}finally{Ve(ze=>{const Ge=new Set(ze);return Ge.delete(H),Ge})}},[a,r]),oi=i.useCallback(async H=>{try{const ze=await sh(H,r);Ot(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze),Ct})}catch{}},[r]),gn=i.useCallback(async H=>{try{const ze=await H1(H,{limit:10},r);Ht(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze),Ct})}catch{}},[r]),Fi=i.useCallback(H=>{const ze=zt.current;if(ze){for(const Ge of ze.milestones)for(const Ct of Ge.slices)if(Ct.features.find(Vt=>Vt.id===H)){O(Vt=>{const kn=new Set(Vt);return kn.add(Ge.id),kn}),P(Vt=>{const kn=new Set(Vt);return kn.add(Ct.id),kn}),Dt(H),ln(Ge.id),oi(H),gn(H),requestAnimationFrame(()=>{const Vt=document.querySelector(`[data-mission-feature-id="${H}"]`);Vt instanceof HTMLElement&&typeof Vt.scrollIntoView=="function"&&Vt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[oi,gn]),ea=i.useCallback(async H=>{try{const ze=await q1(H,r);Me(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze),Ct})}catch{}},[r]),ba=i.useCallback(async H=>{bt===H?Dt(null):(Dt(H),await oi(H),await gn(H))},[bt,oi,gn]),Ja=i.useCallback(async H=>{rn===H?Xt(null):(Xt(H),await ea(H))},[rn,ea]),xa=i.useCallback(async H=>{try{await V1(H,r),a("Mission resumed","success"),await Ut(H),bn()}catch(ze){a(Ee(ze)||"Failed to resume mission","error")}},[a,Ut,bn,r]),va=i.useCallback(async H=>{try{const Ge=(await W1(H,r)).pausedTaskIds?.length??0;a(`Mission stopped (${Ge} task${Ge!==1?"s":""} paused)`,"success"),await Ut(H),bn()}catch(ze){a(Ee(ze)||"Failed to stop mission","error")}},[a,Ut,bn,r]),ya=i.useCallback(async H=>{try{await K1(H,r),a("Mission started — first slice activated","success"),await Ut(H),bn()}catch(ze){a(Ee(ze)||"Failed to start mission","error")}},[a,Ut,bn,r]),Ya=i.useCallback(async(H,ze)=>{try{await G1(H,{enabled:ze},r),a(ze?"Autopilot enabled":"Autopilot disabled","success"),await Ut(H),bn()}catch(Ge){a(Ee(Ge)||"Failed to update autopilot","error")}},[a,Ut,bn,r]),wa=i.useCallback(H=>{se("structure"),ln(null),ye(null),De([]),Et(0),le("all"),nn(new Set),Ut(H.id)},[Ut]),zr=i.useCallback(()=>{x(null),ln(null),ye(null),se("structure"),De([]),Et(0),le("all"),nn(new Set),bn()},[bn]),ka=te.length<Xe,Us=g?.autopilotState??"inactive",Ci=Us==="watching"||Us==="activating",ei=T$(Us,g?.lastAutopilotActivityAt),ta=i.useMemo(()=>!Wt||!sn||!Md(Wt)?null:Wt.rollup.milestoneId===sn?Wt:null,[sn,Wt]),ja=i.useMemo(()=>{const H=new Map;for(const ze of ta?.validationTelemetry.validationRounds??[]){const Ge=H.get(ze.featureId);(!Ge||ze.startedAt>Ge.startedAt)&&H.set(ze.featureId,ze)}return H},[ta]),Br=i.useCallback(()=>{!g||at||!ka||xn(g.id,{append:!0})},[at,ka,xn,g]),Ei=i.useCallback(H=>{nn(ze=>{const Ge=new Set(ze);return Ge.has(H)?Ge.delete(H):Ge.add(H),Ge})},[]),Na=i.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),hs())},[hs]),Sa=i.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),ys())},[ys]),zi=i.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),Ce())},[Ce]),Qa=i.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),Kt())},[Kt]),Ur=i.useRef(null);if(i.useEffect(()=>{if(!h)return;const H=ze=>{ze.key==="Escape"&&s()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[h,s]),!h)return null;const Xa=()=>g?t.jsxs("div",{className:"mission-detail",children:[t.jsxs("div",{className:"mission-detail__header",children:[t.jsxs("div",{className:"mission-detail__title-row",children:[t.jsxs("div",{className:"mission-detail__title-text",children:[Ci&&t.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),t.jsx("h3",{className:"mission-detail__title",children:g.title})]}),t.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(to[g.status]||to.planning).bg,color:(to[g.status]||to.planning).text},children:g.status})]}),g.description&&t.jsx("p",{className:"mission-detail__description",children:g.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[g.milestones.length," milestones"]})}),t.jsxs("div",{className:"mission-detail__autopilot",children:[t.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[t.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[t.jsx("input",{type:"checkbox",checked:g.autopilotEnabled??!1,onChange:H=>Ya(g.id,H.target.checked),"aria-label":"Autopilot"}),t.jsx("span",{className:"mission-toggle__track","aria-hidden":"true",children:t.jsx("span",{className:"mission-toggle__thumb"})}),t.jsxs("span",{className:"mission-toggle__label",children:[t.jsx(as,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(wl[Us]||wl.inactive).bg,color:(wl[Us]||wl.inactive).text},"data-testid":"autopilot-state-badge",children:[Ci&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),Us]})]}),ei&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:ei})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>va(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(Ii,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>xa(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(is,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ya(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>vs(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(_n,{size:14})})]})]}),z===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:R.title,onChange:H=>D({...R,title:H.target.value}),onKeyDown:Na,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:R.description,onChange:H=>D({...R,description:H.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:R.status,onChange:H=>D({...R,status:H.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:R.autopilotEnabled,onChange:H=>D({...R,autopilotEnabled:H.target.checked})}),t.jsx(as,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:hs,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ms,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${$t==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>se("structure"),role:"tab","aria-selected":$t==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${$t==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>se("activity"),role:"tab","aria-selected":$t==="activity","data-testid":"mission-tab-activity",children:["Activity (",Xe,")"]})]}),$t==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(H=>{const ze=ta?.rollup.milestoneId===H.id?ta:null,Ge=ze?.rollup??Gt.get(H.id),Ct=ze?.validationTelemetry.validationRounds??[],Nn=ze?.fixFeatures??[],Vt=vf[Ge?.state??"not_started"]??vf.not_started,kn=Ge&&(Ge.state==="blocked"||Ge.state==="failed")?ze?.validationTelemetry.validationRounds.find(Ze=>Ze.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Ms(H.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:ne.has(H.id)?t.jsx(pn,{size:16}):t.jsx(On,{size:16})}),t.jsx($a,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:H.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:bf[H.status].bg,color:bf[H.status].text},children:H.status}),t.jsxs("span",{className:"mission-milestone__count",children:[H.slices.length," slices"]}),t.jsx(wf,{state:C$(H.interviewState)}),Ge&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Vt.bg,color:Vt.text},title:"Validation state",children:kf(Ge.state)}),Ge.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Ge.passedAssertions??0} of ${Ge.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Ge.passedAssertions??0)/Ge.totalAssertions*100}%`,backgroundColor:(Ge.passedAssertions??0)===Ge.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),H.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>vt({type:"milestone",id:H.id,title:H.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(ua,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Ze=>Ze.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>X(H.id),title:"Add slice",children:t.jsx(Mn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ns(H),title:"Edit milestone",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"milestone",id:H.id}),title:"Delete milestone",children:t.jsx(_n,{size:14})})]})]}),ne.has(H.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(je||$===H.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:J.title,onChange:Ze=>ce({...J,title:Ze.target.value}),onKeyDown:Sa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:Ze=>ce({...J,description:Ze.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ys,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),$?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Yn,children:"Cancel"})]})]}),ze&&t.jsxs("div",{className:"mission-validation-telemetry",children:[t.jsxs("div",{className:"mission-validation-telemetry__header",children:[t.jsx("span",{className:"mission-validation-telemetry__title",children:"Validation Telemetry"}),t.jsxs("span",{className:"mission-validation-telemetry__meta",children:[ze.validationTelemetry.totalRuns," rounds",ze.validationTelemetry.lastValidatorStatus?` · Last ${ze.validationTelemetry.lastValidatorStatus}`:""]})]}),kn&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",kn]}),Ct.length>0&&t.jsxs("div",{className:"mission-validation-rounds",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm mission-validation-rounds__toggle",onClick:()=>Ke(Ze=>!Ze),title:Le?"Hide validation rounds":"Show validation rounds",children:[Le?t.jsx(pn,{size:12}):t.jsx(On,{size:12}),"Validation rounds (",Ct.length,")"]}),Le&&t.jsx("div",{className:"mission-validation-rounds__list",children:Ct.map(Ze=>t.jsxs("div",{className:"mission-validation-round",children:[t.jsxs("div",{className:"mission-validation-round__header",children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-validation-round__status mission-validation-round__status--${Ze.validatorStatus}`,children:Ze.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Ze.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Ze.implementationAttempt," · reviewer #",Ze.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Ze.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ze.failedAssertionIds.map(ot=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ga(ot),title:`Jump to assertion ${ot}`,children:ot},`${Ze.roundId}-${ot}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Generated fix features:"}),Ze.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ze.generatedFixFeatureIds.map(ot=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Fi(ot),title:`Jump to fix feature ${ot}`,children:ot},`${Ze.roundId}-${ot}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Ze.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Ze.blockedReason})]},Ze.roundId))})]}),Nn.length>0&&t.jsxs("div",{className:"mission-fix-features",children:[t.jsx("div",{className:"mission-fix-features__title",children:"Generated Fix Features"}),t.jsx("div",{className:"mission-fix-features__list",children:Nn.map(Ze=>t.jsxs("div",{className:"mission-fix-feature",children:[t.jsxs("div",{className:"mission-fix-feature__header",children:[t.jsx("button",{className:"mission-fix-feature__title",onClick:()=>Fi(Ze.id),title:`Jump to feature ${Ze.id}`,children:Ze.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:yl[Ze.status].bg,color:yl[Ze.status].text},children:Ze.status}),Ze.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Ze.loopState}`,children:Ze.loopState})]}),t.jsxs("div",{className:"mission-fix-feature__meta",children:[t.jsx("span",{children:"Source:"}),t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Fi(Ze.sourceFeatureId),title:`Jump to source feature ${Ze.sourceFeatureId}`,children:Ze.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Ze.runId})]}),Ze.failedAssertionIds.length>0&&t.jsxs("div",{className:"mission-fix-feature__assertions",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),t.jsx("div",{className:"mission-validation-round__chip-list",children:Ze.failedAssertionIds.map(ot=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ga(ot),title:`Jump to assertion ${ot}`,children:ot},`${Ze.id}-${ot}`))})]})]},Ze.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[H.slices.map(Ze=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>q(Ze.id),children:[t.jsx("button",{className:"mission-slice__expand",children:A.has(Ze.id)?t.jsx(pn,{size:16}):t.jsx(On,{size:16})}),t.jsx(eu,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Ze.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:xf[Ze.status].bg,color:xf[Ze.status].text},children:Ze.status}),t.jsxs("span",{className:"mission-slice__count",children:[Ze.features?.length||0," features"]}),t.jsx(wf,{state:Ze.planState??"not_started"}),Ze.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>vt({type:"slice",id:Ze.id,title:Ze.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(ua,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:ot=>ot.stopPropagation(),children:[Ze.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>At(Ze.id),title:"Activate slice",children:t.jsx(is,{size:14})}),Ze.status==="active"&&Ze.features?.some(ot=>ot.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>fs(Ze.id),title:"Triage all features",disabled:K,children:K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(as,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>we(Ze.id),title:"Add feature",children:t.jsx(Mn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>E(Ze),title:"Edit slice",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"slice",id:Ze.id}),title:"Delete slice",children:t.jsx(_n,{size:14})})]})]}),A.has(Ze.id)&&t.jsxs("div",{className:"mission-slice__body",children:[ee&&W===H.id&&!xe&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:Y.title,onChange:ot=>ie({...Y,title:ot.target.value}),onKeyDown:zi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:ot=>ie({...Y,description:ot.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ce,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ue,children:"Cancel"})]})]}),xe===Ze.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:Y.title,onChange:ot=>ie({...Y,title:ot.target.value}),onKeyDown:zi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:ot=>ie({...Y,description:ot.target.value}),rows:2}),t.jsxs("select",{value:Y.status,onChange:ot=>ie({...Y,status:ot.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"complete",children:"Complete"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ce,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ue,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Ze.features?.map(ot=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":ot.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>ba(ot.id),title:bt===ot.id?"Collapse details":"Expand to show run history",children:bt===ot.id?t.jsx(pn,{size:14}):t.jsx(On,{size:14})}),t.jsx(Gd,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:ot.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:yl[ot.status].bg,color:yl[ot.status].text},children:ot.status}),ot.loopState&&ot.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${ot.loopState}`,title:`Loop state: ${ot.loopState}`,children:[ot.loopState==="implementing"&&"⏳",ot.loopState==="validating"&&"🔄",ot.loopState==="needs_fix"&&"🔧",ot.loopState==="passed"&&"✅",ot.loopState==="blocked"&&"🚫"]}),ot.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Fi(ot.generatedFromFeatureId),title:`Generated from feature: ${ot.generatedFromFeatureId}`,children:"🔗 Fix"}),(ot.loopState==="validating"||ot.loopState==="needs_fix")&&(()=>{const Bt=Pt.get(ot.id),In=ja.get(ot.id),qn=Bt?.implementationAttemptCount??In?.implementationAttempt??ot.implementationAttemptCount??0,ti=Bt?.retryBudgetRemaining??Math.max(0,j$-qn);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",qn," · ",ti," ",ti===1?"retry":"retries"," left"]})})(),ot.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Ga(ot.id),title:"Validate feature",disabled:mt.has(ot.id),children:mt.has(ot.id)?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(gs,{size:14})}),ot.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(ot.taskId),title:"Click to view task",children:ot.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[ot.status==="defined"&&!ot.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ts(ot.id),title:"Triage — create task",disabled:K||dt===ot.id,children:dt===ot.id?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(as,{size:14})}),ot.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>jn(ot.id),title:"Unlink task",children:t.jsx(Rm,{size:14})}):ot.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Be(ot.id),title:"Link to task",children:t.jsx(vr,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>Oe(ot),title:"Edit feature",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"feature",id:ot.id}),title:"Delete feature",children:t.jsx(_n,{size:14})})]})]}),ot.description&&t.jsx("p",{className:"mission-feature__description",children:ot.description}),ot.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",ot.acceptanceCriteria]}),Ae?.featureId===ot.id&&t.jsxs("div",{className:"mission-triage-preview",children:[t.jsx("div",{className:"mission-triage-preview__header",children:"Enriched Description Preview"}),t.jsx("div",{className:"mission-triage-preview__content",children:Ae.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:Ln,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:os,disabled:K,children:"Cancel"})]})]}),pe===ot.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:B.title,onChange:Bt=>ve({...B,title:Bt.target.value}),onKeyDown:Qa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:B.description,onChange:Bt=>ve({...B,description:Bt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:B.acceptanceCriteria,onChange:Bt=>ve({...B,acceptanceCriteria:Bt.target.value}),rows:2}),t.jsxs("select",{value:B.status,onChange:Bt=>ve({...B,status:Bt.target.value}),children:[t.jsx("option",{value:"defined",children:"Defined"}),t.jsx("option",{value:"triaged",children:"Triaged"}),t.jsx("option",{value:"in-progress",children:"In Progress"}),t.jsx("option",{value:"done",children:"Done"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Kt,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:It,children:"Cancel"})]})]}),bt===ot.id&&t.jsxs("div",{className:"mission-feature__run-history",children:[t.jsx("div",{className:"mission-feature__run-history-header",children:t.jsx("span",{className:"mission-feature__run-history-title",children:"Validation Runs"})}),(Ft.get(ot.id)??[]).map(Bt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>Ja(Bt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${Bt.status}`,title:Bt.status,children:Bt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(Bt.startedAt).toLocaleString()}),Bt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(Bt.completedAt).getTime()-new Date(Bt.startedAt).getTime())/1e3),"s"]}),Bt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:Bt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:rn===Bt.id?"Hide details":"Show details",children:rn===Bt.id?t.jsx(pn,{size:12}):t.jsx(On,{size:12})})]}),rn===Bt.id&&an.get(Bt.id)&&t.jsxs("div",{className:"mission-run__details",children:[Bt.summary&&t.jsx("p",{className:"mission-run__summary",children:Bt.summary}),Bt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",Bt.blockedReason]}),an.get(Bt.id)?.failures&&an.get(Bt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),an.get(Bt.id).failures.map(In=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:In.message}),In.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",In.expected]}),In.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",In.actual]})]},In.id))]}),(!an.get(Bt.id)?.failures||an.get(Bt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},Bt.id)),(!Ft.get(ot.id)||Ft.get(ot.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},ot.id)),Fe&&qe===Ze.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:B.title,onChange:ot=>ve({...B,title:ot.target.value}),onKeyDown:Qa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:B.description,onChange:ot=>ve({...B,description:ot.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:B.acceptanceCriteria,onChange:ot=>ve({...B,acceptanceCriteria:ot.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Kt,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:It,children:"Cancel"})]})]}),!Fe&&(!Ze.features||Ze.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(Gd,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Ze.id)),H.slices.length===0&&!ee&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(eu,{size:16}),t.jsx("span",{children:"No slices yet"})]}),t.jsxs("div",{className:"mission-assertions",children:[t.jsxs("div",{className:"mission-assertions__header",children:[t.jsx("span",{className:"mission-assertions__title",children:"Assertions"}),Ge&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Vt.bg,color:Vt.text},children:kf(Ge.state)}),Ge&&Ge.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Ge.passedAssertions??0} of ${Ge.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Ge.passedAssertions??0)/Ge.totalAssertions*100}%`,backgroundColor:(Ge.passedAssertions??0)===Ge.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{be(!0),ke(null),Rt({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(Mn,{size:14})})]}),Re&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:tt.title,onChange:Ze=>Rt({...tt,title:Ze.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:tt.assertion,onChange:Ze=>Rt({...tt,assertion:Ze.target.value}),rows:2}),t.jsxs("select",{value:tt.status,onChange:Ze=>Rt({...tt,status:Ze.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>es(H.id),disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ls,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(G.get(H.id))?G.get(H.id):[]).map(Ze=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Ze.id,children:[t.jsx("div",{className:"mission-assertion__header",children:pt===Ze.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:tt.title,onChange:ot=>Rt({...tt,title:ot.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:tt.assertion,onChange:ot=>Rt({...tt,assertion:ot.target.value}),rows:2}),t.jsxs("select",{value:tt.status,onChange:ot=>Rt({...tt,status:ot.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>ss(Ze.id,H.id),disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ls,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(kl[Ze.status]??kl.pending).bg,color:(kl[Ze.status]??kl.pending).text},children:Ze.status}),t.jsx("span",{className:"mission-assertion__title",children:Ze.title}),(()=>{const Bt=gt.get(Ze.id)?.length??0;return Bt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${Bt} linked feature${Bt!==1?"s":""}`,children:["(",Bt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Si(Ze.id),title:"Toggle details",children:rt===Ze.id?t.jsx(pn,{size:14}):t.jsx(On,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ss(Ze),title:"Edit assertion",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"assertion",id:Ze.id}),title:"Delete assertion",children:t.jsx(_n,{size:14})})]})}),rt===Ze.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Ze.assertion}),t.jsxs("div",{className:"mission-assertion__linked-features",children:[t.jsxs("div",{className:"mission-assertion__linked-features-header",children:[t.jsx("span",{className:"mission-assertion__linked-features-label",children:"Linked Features"}),t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:async()=>{rt!==Ze.id&&await Si(Ze.id),yn(Qt===Ze.id?null:Ze.id)},title:"Link a feature",children:[t.jsx(vr,{size:12}),"Link Feature"]})]}),Qt===Ze.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const ot=new Set((gt.get(Ze.id)??[]).map(In=>In.id)),Bt=[];return g?.milestones.forEach(In=>In.slices.forEach(qn=>Bt.push(...qn.features.filter(ti=>!ot.has(ti.id))))),Bt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):Bt.map(In=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>Wa(In.id,Ze.id),disabled:Lt.has(Ze.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:In.title}),Lt.has(Ze.id)&&t.jsx(jt,{size:12,className:"spinner"})]},In.id))})()})}),(()=>{const ot=gt.get(Ze.id)??[];return ot.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):ot.map(Bt=>{const In=`${Bt.id}-${Ze.id}`,qn=tn.has(In);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:Bt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ka(Bt.id,Ze.id),disabled:qn,title:"Unlink feature",children:qn?t.jsx(jt,{size:12,className:"spinner"}):t.jsx(Rm,{size:12})})]},Bt.id)})})()]})]})]},Ze.id)),(!G.get(H.id)||G.get(H.id)?.length===0)&&!Re&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},H.id)}),g&&!je&&$===null&&t.jsxs("button",{className:"mission-add-btn",onClick:ps,children:[t.jsx(Mn,{size:16}),"Add Milestone"]}),je&&$===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:J.title,onChange:H=>ce({...J,title:H.target.value}),onKeyDown:Sa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:H=>ce({...J,description:H.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ys,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Yn,children:"Cancel"})]})]}),g.milestones.length===0&&!je&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx($a,{size:24}),t.jsx("span",{children:"No milestones yet. Add one to get started."})]})]}):t.jsxs("div",{className:"mission-detail__activity","data-testid":"mission-activity-tab",children:[t.jsxs("div",{className:"mission-detail__activity-controls",children:[t.jsxs("label",{className:"mission-detail__activity-filter",children:[t.jsx("span",{children:"Filter"}),t.jsxs("select",{value:Zt,onChange:H=>le(H.target.value),"data-testid":"mission-activity-filter",children:[t.jsx("option",{value:"all",children:"All events"}),t.jsx("option",{value:"errors",children:"Errors & warnings"}),t.jsx("option",{value:"state_changes",children:"State changes"}),t.jsx("option",{value:"tasks",children:"Task events"}),t.jsx("option",{value:"slices",children:"Slice & milestone events"}),t.jsx("option",{value:"autopilot",children:"Autopilot events"})]})]}),t.jsxs("span",{className:"mission-detail__activity-count",children:[te.length," of ",Xe]})]}),!at&&ka&&t.jsx("div",{className:"mission-detail__activity-load-more mission-detail__activity-load-more--top",children:t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Br,"data-testid":"mission-activity-load-more",children:"Load more"})}),at?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(jt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):te.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ys,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:Rn,className:"mission-events","data-testid":"mission-activity-events",children:[te.map(H=>{const ze=!!(H.metadata&&Object.keys(H.metadata).length>0),Ge=ct.has(H.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${R$(H.eventType)}`,children:I$(H.eventType)}),t.jsx("span",{className:"mission-event__time",children:ec(H.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:H.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(H.timestamp).toLocaleString()}),ze&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Ei(H.id),"data-testid":`mission-event-metadata-${H.id}`,children:[Ge?"Hide":"Show"," metadata"]}),Ge&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(H.metadata,null,2)})]})]},H.id)}),t.jsx("div",{ref:Un})]})]})]}):null,Za=H=>{_e(H),st(!0)},er=()=>{xt.current=ut??null,_e(void 0),st(!1)},Hr=()=>Ue.map(H=>{const ze=H.status==="error",Ge=H.status==="generating";return t.jsxs("div",{className:"mission-list__item mission-list__item--interview",onClick:()=>Za(H.id),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(gs,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:H.title||"Mission interview"})]}),t.jsx("div",{className:"mission-list__item-tags",children:t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-interview-status mission-interview-status--${H.status}`,children:S$(H.status)})}),t.jsx("p",{className:"mission-list__item-description",children:Ge?"Generating mission hierarchy from interview context.":ze?"Interview hit an error. Retry from this list item.":"Interview is waiting for your next response."})]}),t.jsx("div",{className:"mission-list__item-actions",onClick:Ct=>Ct.stopPropagation(),children:t.jsx("button",{className:`mission-icon-btn ${ze?"mission-icon-btn--danger":"mission-icon-btn--success"}`,onClick:()=>Za(H.id),title:yf(H.status),"aria-label":yf(H.status),children:Ge?t.jsx(jt,{size:14,className:"spinner"}):ze?t.jsx(bs,{size:14}):t.jsx(gs,{size:14})})})]},H.id)}),Ye=(H,ze)=>H.map(Ge=>{const Ct=Ge,Nn=g?.id===Ct.id,Vt=to[Ct.status]||{bg:"",text:""},kn=Ct.summary,Ze=it.get(Ct.id),ot=_$(Ze),Bt=!!(kn&&(kn.totalMilestones>0||kn.totalFeatures>0)),In=Ze?.totalTasks??0,qn=Ze?.tasksCompleted??0,ti=Ze?.tasksFailed??0,Tn=Ze?.estimatedCompletionPercent??kn?.progressPercent??0,Vn=Bt||In>0||ti>0||!!Ze?.lastActivityAt,dn=ze?.interviewStyle===!0;return t.jsxs("div",{className:`mission-list__item ${Nn?"mission-list__item--selected":""} ${dn?"mission-list__item--interview":""}`,onClick:()=>wa(Ge),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(Rs,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Ct.title})]}),t.jsxs("div",{className:"mission-list__item-tags",children:[Ge.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(as,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${ot}`,"data-testid":`mission-health-badge-${Ct.id}`,"aria-label":`Mission health: ${ot}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Vt.bg,color:Vt.text},children:Ct.status}),dn&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm mission-interview-status mission-interview-status--awaiting_input",children:"Interview in progress"})]}),dn?t.jsx("p",{className:"mission-list__item-description",children:"Mission interview is still in progress. Open this mission to continue planning."}):Ct.description?t.jsx("p",{className:"mission-list__item-description",children:Ct.description}):null,Vn&&t.jsxs("div",{className:"mission-list__item-summary",children:[Bt&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[kn.completedMilestones,"/",kn.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[kn.completedFeatures,"/",kn.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ct.id}`,children:[qn,"/",In," tasks"]}),ti>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Gs=>{Gs.stopPropagation(),wa(Ge)},"data-testid":`mission-failed-${Ct.id}`,title:"View mission failures",children:[ti," failed"]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${ot}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Tn}%`}})})]}),Vn&&t.jsx("div",{className:"mission-list__item-activity",children:t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ct.id}`,children:["Activity ",ec(Ze?.lastActivityAt)]})})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Gs=>Gs.stopPropagation(),children:[Ct.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>va(Ct.id),title:"Stop mission",children:t.jsx(Ii,{size:14})}),Ct.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>xa(Ct.id),title:"Resume mission",children:t.jsx(is,{size:14})}),Ct.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ya(Ct.id),title:"Start mission",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>vs(Ge),title:"Edit mission",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"mission",id:Ct.id}),title:"Delete mission",children:t.jsx(_n,{size:14})})]})]},Ct.id)}),Tt=({hideBottomButtons:H=!1}={})=>{const ze=f.filter(Vt=>Vt.interviewState==="in_progress"),Ge=f.filter(Vt=>Vt.interviewState!=="in_progress"),Ct=j&&f.length>0&&!_,Nn=!H&&!Ct;return t.jsxs("div",{className:"mission-list",children:[_&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:R.title,onChange:Vt=>D({...R,title:Vt.target.value}),onKeyDown:Na,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:R.description,onChange:Vt=>D({...R,description:Vt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:hs,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ms,children:"Cancel"})]})]}),Ct&&t.jsx("div",{className:"mission-list__top-action",children:t.jsxs("button",{className:"btn btn-sm btn-task-create mission-list__primary-cta",onClick:()=>st(!0),children:[t.jsx(gs,{size:14}),"Plan New Mission"]})}),Ye(ze,{interviewStyle:!0}),Ye(Ge),Hr(),z&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:R.title,onChange:Vt=>D({...R,title:Vt.target.value}),onKeyDown:Na,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:R.description,onChange:Vt=>D({...R,description:Vt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:R.status,onChange:Vt=>D({...R,status:Vt.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:R.autopilotEnabled,onChange:Vt=>D({...R,autopilotEnabled:Vt.target.checked})}),t.jsx(as,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:hs,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ms,children:"Cancel"})]})]}),f.length===0&&!_&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large mission-manager__empty--mission",children:[t.jsx(Rs,{size:32}),t.jsx("h3",{className:"mission-manager__empty-title",children:"No missions yet"}),t.jsx("p",{className:"mission-manager__empty-body",children:"Missions are large initiatives that bundle milestones, slices, and features into a single plan. Plan a mission to break down a goal end-to-end and let agents work through it autopilot-style."}),t.jsxs("button",{className:"btn btn-sm btn-primary mission-manager__empty-cta",onClick:()=>st(!0),children:[t.jsx(gs,{size:14}),"Plan New Mission"]})]}),!_&&t.jsx("div",{className:"mission-list__footer",children:Nn&&t.jsx("div",{className:"mission-list__footer-actions",children:t.jsxs("button",{className:"mission-add-btn",onClick:()=>st(!0),children:[t.jsx(gs,{size:16}),"Plan New Mission"]})})})]})},cn=()=>t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--danger",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsxs("p",{children:["Delete this ",yt?.type,"? This cannot be undone."]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--danger",onClick:async()=>{yt&&(yt.type==="mission"?await Jn(yt.id):yt.type==="milestone"?await ws(yt.id):yt.type==="slice"?await We(yt.id):yt.type==="feature"&&await fn(yt.id))},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>Se(null),children:"Cancel"})]})]})}),cs=()=>t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--link",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsx("p",{children:"Link feature to task:"}),t.jsx("input",{type:"text",placeholder:"Task ID (e.g., FN-001)",value:de,onChange:H=>Ie(H.target.value),autoFocus:!0}),l.length>0&&t.jsxs("div",{className:"mission-task-suggestions",children:[t.jsx("small",{children:"Or select:"}),t.jsx("div",{className:"mission-task-suggestions__list",children:l.slice(0,5).map(H=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Ie(H.id),children:[H.id,": ",H.title||"Untitled"]},H.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:An,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{Be(null),Ie("")},children:"Cancel"})]})]})}),Hn=t.jsxs("div",{ref:Ur,className:`mission-manager mission-manager--desktop${n?" mission-manager--inline":""}`,role:n?void 0:"dialog","aria-modal":n?void 0:!0,"aria-label":n?void 0:"Mission Manager","data-testid":"mission-manager-dialog",children:[t.jsxs("div",{className:`mission-manager__header${n?" mission-manager__header--inline":""}`,children:[t.jsxs("div",{className:"mission-manager__header-title",children:[g&&t.jsx("button",{className:"mission-manager__back-btn",onClick:zr,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(lc,{size:18})}),t.jsx(Rs,{size:18,className:"mission-manager__header-icon"}),t.jsxs("h2",{className:"mission-manager__title","data-testid":"mission-header-title",children:[t.jsx("span",{className:"mission-manager__title-text mission-manager__title-text--desktop",children:"Missions"}),t.jsx("span",{className:"mission-manager__title-text mission-manager__title-text--mobile",children:g?g.title:"Missions"})]})]}),!n&&t.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:t.jsx(un,{size:18})})]}),j?t.jsxs("div",{className:"mission-manager__body mission-manager__body--stacked",children:[w?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?Xa():Tt(),yt&&cn(),nt&&cs()]}):t.jsxs("div",{className:"mission-manager__split",children:[t.jsxs("aside",{className:"mission-manager__sidebar","data-testid":"mission-sidebar","aria-label":"Mission list",style:j?void 0:{width:`${C}px`},children:[t.jsx("div",{className:"mission-manager__sidebar-list",children:w?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):Tt({hideBottomButtons:!0})}),t.jsx("div",{className:"mission-manager__sidebar-footer","data-testid":"mission-sidebar-footer",children:t.jsxs("button",{className:"btn btn-primary mission-manager__sidebar-cta",onClick:()=>st(!0),title:"Plan New Mission","aria-label":"Plan New Mission",children:[t.jsx(gs,{size:14}),"Plan New Mission"]})})]}),!j&&t.jsx("div",{className:"mission-manager__sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":xl,"aria-valuemax":vl,"aria-valuenow":C,"aria-label":"Resize mission sidebar",tabIndex:0,onPointerDown:I,onKeyDown:F}),t.jsxs("div",{className:"mission-manager__detail-pane",children:[y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?Xa():t.jsxs("div",{className:"mission-manager__detail-pane-empty","data-testid":"mission-empty-detail",children:[t.jsx(Rs,{size:32}),t.jsx("span",{children:"Select a mission to view details"})]}),yt&&cn(),nt&&cs()]})]})]}),Cs=t.jsx(u$,{isOpen:$e,onClose:er,onMissionCreated:()=>{bn(),a("Mission created from AI interview","success")},projectId:r,resumeSessionId:ut}),na=Qe?t.jsx(y$,{isOpen:!0,onClose:()=>vt(null),onApplied:()=>{vt(null),g&&Ut(g.id)},targetType:Qe.type,targetId:Qe.id,targetTitle:Qe.title,missionContext:g?.title,projectId:r,resumeSessionId:Qe.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[Hn,Cs,na]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:H=>H.target===H.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:Hn}),Cs,na]})}const $$={pre:({children:e,...n})=>t.jsx("pre",{...n,className:"mailbox-markdown-pre",children:e}),table:({children:e,...n})=>t.jsx("table",{...n,className:"mailbox-markdown-table",children:e}),a:({children:e,...n})=>t.jsx("a",{...n,target:"_blank",rel:"noopener noreferrer",children:e})},Sf=i.memo(function({content:n,className:s,testId:a}){const r=s?`mailbox-markdown ${s}`:"mailbox-markdown";return t.jsx("div",{className:r,"data-testid":a,children:t.jsx(ki,{remarkPlugins:[ji],components:$$,children:n})})}),jl=2e3;function Cf({recipient:e,replyContext:n,agents:s=[],projectId:a,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[d,u]=i.useState(e?.id??""),[m,h]=i.useState(e?.type??"agent"),[f,p]=i.useState(""),[g,x]=i.useState(!1),[w,b]=i.useState(!1),[y,S]=i.useState(null),j=i.useRef(null),C=i.useMemo(()=>s.find(U=>U.id===d),[s,d]),v=i.useMemo(()=>e?s.find(U=>U.id===e.id):void 0,[s,e]),N=m==="agent",I=N&&C?.runtimeConfig?.messageResponseMode==="immediate",F=N&&(g||I),_=d.trim()!==""&&f.trim().length>0&&f.length<=jl,M=i.useCallback(async()=>{if(!(!_||w)){b(!0),S(null);try{const U=m==="agent"?"user-to-agent":"system",R=n?{replyTo:{messageId:n.messageId}}:void 0,D=F;await w0({toId:d.trim(),toType:m,content:f.trim(),type:U,...R?{metadata:R}:{},...D?{wakeImmediately:!0}:{}},a),r()}catch(U){const R=Ee(U)||"Failed to send message";S(R),l?.(R,"error")}finally{b(!1)}}},[_,w,d,m,f,F,n,a,r,l]),z=i.useCallback(U=>{u(U),h("agent")},[]);return i.useEffect(()=>{n&&j.current?.focus()},[n]),i.useEffect(()=>{if(!n||typeof window>"u"||window.visualViewport==null)return;const U=()=>{j.current?.scrollIntoView({block:"center",behavior:"auto"})};return window.visualViewport.addEventListener("resize",U),()=>{window.visualViewport?.removeEventListener("resize",U)}},[n]),t.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[t.jsxs("div",{className:"message-composer-header",children:[t.jsx("span",{children:n?"Reply":"New Message"}),t.jsx("button",{className:"btn-icon",onClick:o,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:t.jsx(un,{size:16})})]}),t.jsxs("div",{className:"message-composer-body",children:[!e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-recipient",children:"To:"}),t.jsxs("select",{id:"message-recipient",className:"message-composer-select",value:d,onChange:U=>z(U.target.value),disabled:c||s.length===0,"data-testid":"message-composer-recipient",children:[t.jsx("option",{value:"",children:c?"Loading agents…":s.length===0?"No agents available":"Select agent…"}),s.map(U=>t.jsx("option",{value:U.id,children:U.name||U.id},U.id))]})]}),e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("span",{className:"message-composer-label",children:"To:"}),t.jsxs("span",{className:"message-composer-recipient-fixed",children:[t.jsx(Kn,{size:14}),v?.name||e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",ref:j,className:"message-composer-textarea",placeholder:"Type your message…",value:f,onChange:U=>p(U.target.value),maxLength:jl,rows:4,"data-testid":"message-composer-content"}),t.jsx("div",{className:"message-composer-charcount","data-testid":"message-composer-charcount",children:t.jsxs("span",{className:f.length>jl?"over-limit":"",children:[f.length,"/",jl]})})]}),N&&t.jsx("div",{className:"message-composer-field message-composer-field--wake",children:t.jsxs("label",{className:"message-composer-wake-label",children:[t.jsx("input",{type:"checkbox",checked:F,disabled:I,onChange:U=>x(U.target.checked),"data-testid":"message-composer-wake"}),t.jsxs("span",{children:["Wake agent immediately",t.jsx("span",{className:"message-composer-wake-hint","data-testid":"message-composer-wake-hint",children:I?"(agent is already set to immediate response mode)":"(one-off override for this message only)"})]})]})}),y&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(Ws,{size:14}),t.jsx("span",{children:y})]})]}),t.jsxs("div",{className:"message-composer-footer",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:o,"data-testid":"message-composer-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:M,disabled:!_||w,"data-testid":"message-composer-send",children:w?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(Ia,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}const Ds="__all_agents__",tc=280,Nu=.65,Ad=16,Ef=320;function Su(e){return Math.max(tc,e*Nu)}function Rd(e,n){const s=Su(n);return Math.min(Math.max(e,tc),s)}function _f(e){try{const n=zn("kb-dashboard-mailbox-sidebar-width",e);if(!n)return Ef;const s=Number(n);if(Number.isFinite(s)&&s>0)return s}catch{}return Ef}function qi(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function D$(e,n,s){if(n==="user")return e==="dashboard"?"You":`User: ${e}`;if(n==="agent"){const a=s?.get(e)?.trim();return a?a===e?`Agent: ${e}`:`Agent: ${a} (${e})`:`Agent: ${e}`}return"System"}function L$(e){switch(e){case"agent-to-agent":return"Agent ↔ Agent";case"agent-to-user":return"Agent → You";case"user-to-agent":return"You → Agent";case"system":return"System"}}function Mf(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function Af(){if(typeof window>"u")return null;const n=new URLSearchParams(window.location.search).get("mailbox-message");return n||(/^#message-(.+)$/.exec(window.location.hash)?.[1]??null)}function no(e){return`mailbox-list-message-${e}`}function Id(e){return`mailbox-detail-message-${e}`}function O$(e,n){const s=[...e];s.some(o=>o.id===n.id)||s.push(n);const a=new Set([n.id]);let r=!0;for(;r;){r=!1;for(const o of s){const l=o.metadata?.replyTo?.messageId;a.has(o.id)&&l&&!a.has(l)&&(a.add(l),r=!0),l&&a.has(l)&&!a.has(o.id)&&(a.add(o.id),r=!0)}}return s.filter(o=>a.has(o.id)).sort((o,l)=>new Date(o.createdAt).getTime()-new Date(l.createdAt).getTime())}function F$({projectId:e,addToast:n,onUnreadCountChange:s}){const[a,r]=i.useState("inbox"),[o,l]=i.useState(null),[c,d]=i.useState(null),[u,m]=i.useState(0),[h,f]=i.useState(!1),[p,g]=i.useState(null),[x,w]=i.useState([]),[b,y]=i.useState(!1),[S,j]=i.useState(null),[C,v]=i.useState(null),[N,I]=i.useState(Ds),[F,_]=i.useState("inbox"),[M,z]=i.useState(null),[U,R]=i.useState(null),[D,K]=i.useState([]),[Z,ne]=i.useState("pending"),[O,A]=i.useState([]),[P,$]=i.useState(0),[k,J]=i.useState(null),[ce,je]=i.useState(""),[He,xe]=i.useState(!1),Ne=i.useMemo(()=>new Map(D.map(G=>[G.id,G.name??""])),[D]),Y=i.useCallback((G,ge)=>D$(G,ge,Ne),[Ne]),ee=ri()==="mobile",oe=!ee,[W,L]=i.useState(()=>_f(e)),pe=i.useRef(null),{keyboardOverlap:fe,viewportHeight:B,viewportOffsetTop:ve,keyboardOpen:Fe}=Zi({enabled:ee}),ae=i.useMemo(()=>{if(Fe)return{"--keyboard-overlap":`${fe}px`,"--vv-offset-top":`${ve}px`,...B!=null?{"--vv-height":`${B}px`}:{}}},[Fe,fe,B,ve]);i.useEffect(()=>{L(_f(e))},[e]),i.useEffect(()=>{if(!oe)return;const G=pe.current?.clientWidth;G&&L(ge=>Rd(ge,G))},[oe]),i.useEffect(()=>{if(oe)try{us("kb-dashboard-mailbox-sidebar-width",String(W),e)}catch{}},[oe,e,W]);const qe=i.useCallback(G=>{if(!oe)return;G.preventDefault();const ge=pe.current;if(!ge)return;const pt=ge.getBoundingClientRect(),ke=Rt=>{const Re=Rt.clientX-pt.left;L(Rd(Re,pt.width))},tt=()=>{window.removeEventListener("mousemove",ke),window.removeEventListener("mouseup",tt)};window.addEventListener("mousemove",ke),window.addEventListener("mouseup",tt)},[oe]),Pe=i.useCallback(G=>{if(!oe)return;const ge=pe.current?.clientWidth??0,pt=W/Nu+Ad,ke=Math.max(ge,pt),tt=Su(ke);if(G.key==="ArrowLeft"||G.key==="ArrowRight"){G.preventDefault();const Rt=G.key==="ArrowLeft"?-Ad:Ad;L(Re=>Rd(Re+Rt,ke));return}if(G.key==="Home"){G.preventDefault(),L(tc);return}G.key==="End"&&(G.preventDefault(),L(tt))},[oe,W]),nt=i.useCallback(async()=>{f(!0);try{const G=await v0({limit:50},e);l(G),m(G.unreadCount),s?.(G.unreadCount)}catch{}finally{f(!1)}},[e,s]),Be=i.useCallback(async()=>{f(!0);try{const G=await y0({limit:50},e);d(G)}catch{}finally{f(!1)}},[e]),de=i.useCallback(async G=>{f(!0);try{const ge=await C0(G,e);z(ge)}catch{}finally{f(!1)}},[e]),Ie=i.useCallback(async()=>{f(!0);try{const G=await E0(e);R(G)}catch{}finally{f(!1)}},[e]),$e=i.useCallback(async()=>{try{const G=await $r(void 0,e);K(G)}catch{}},[e]),st=i.useCallback(async()=>{try{const G=await xb(e);m(G.unreadCount),s?.(G.unreadCount)}catch{}},[e,s]),Ue=i.useCallback(async G=>{f(!0);try{const ge=await nl({status:G==="pending"?"pending":void 0,limit:100},e);if(G==="pending")A(ge.requests);else{const[pt,ke,tt]=await Promise.all([nl({status:"approved",limit:100},e),nl({status:"denied",limit:100},e),nl({status:"completed",limit:100},e)]);A([...pt.requests,...ke.requests,...tt.requests].sort((Rt,Re)=>Re.updatedAt.localeCompare(Rt.updatedAt)))}$(ge.pendingCount)}catch{}finally{f(!1)}},[e]);i.useEffect(()=>{a==="inbox"?nt():a==="outbox"?Be():a==="agents"?$e():a==="approvals"&&Ue(Z)},[a,nt,Be,$e,Ue,Z]),i.useEffect(()=>{if(N===Ds){Ie();return}de(N)},[N,de,Ie]),i.useEffect(()=>{st()},[st]),i.useEffect(()=>{$e()},[$e]),i.useEffect(()=>{if(typeof EventSource>"u")return;const G=e?`?projectId=${encodeURIComponent(e)}`:"",ge=()=>{st(),a==="inbox"?nt():a==="outbox"?Be():a==="approvals"&&Ue(Z),N===Ds?Ie():N&&de(N)};return hi(`/api/events${G}`,{events:{"message:sent":ge,"message:received":ge,"message:read":ge,"message:deleted":ge,"approval:requested":ge,"approval:updated":ge,"approval:decided":ge}})},[e,a,N,st,nt,Be,de,Ie,Ue,Z]);const me=i.useCallback(async G=>{if(g(G),!G.read&&a==="inbox")try{const ge=await k0(G.id,e);ge&&l(ke=>ke&&{...ke,messages:ke.messages.map(tt=>tt.id===ge.id?ge:tt),unreadCount:Math.max(0,ke.unreadCount-1)});const pt=Math.max(0,u-1);m(pt),s?.(pt)}catch{}try{const ge=await S0(G.fromId,G.fromType,e);w(ge)}catch{w([G])}},[e,u,s,a]);i.useEffect(()=>{const G=Af();if(!G)return;const ge=[...o?.messages??[],...c?.messages??[],...M?.inbox??[],...M?.outbox??[],...U?.messages??[],...x].find(pt=>pt.id===G);ge&&me(ge)},[o,c,M,U,x,me]),i.useEffect(()=>{const G=Af();if(!G)return;const ge=document.getElementById(Id(G));if(!ge)return;ge.scrollIntoView({behavior:"smooth",block:"center"}),ge.classList.add("mailbox-message-highlight");const pt=window.setTimeout(()=>{ge.classList.remove("mailbox-message-highlight")},2e3);return()=>{window.clearTimeout(pt)}},[p,x]);const re=i.useCallback(()=>{g(null),w([])},[]),_e=i.useCallback(async()=>{try{const G=await j0(e);m(0),s?.(0),l(ge=>ge&&{...ge,messages:ge.messages.map(pt=>({...pt,read:!0})),unreadCount:0}),n?.(`Marked ${G.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),xt=i.useCallback(async G=>{try{await N0(G,e),g(null),w([]),a==="inbox"?nt():a==="outbox"?Be():N===Ds?Ie():N&&de(N),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,a,N,nt,Be,de,Ie,n]),ut=i.useCallback(G=>{j({id:G.fromId,type:G.fromType}),v({messageId:G.id,preview:Mf(G.content,120)}),y(!0)},[]),Qe=i.useCallback(()=>{y(!1),j(null),v(null),n?.("Message sent","success"),a==="outbox"?Be():a==="agents"&&N===Ds?Ie():a==="agents"&&N&&de(N),st()},[a,Be,N,de,Ie,n,st]),vt=i.useCallback(()=>{j(a==="agents"&&N&&N!==Ds?{id:N,type:"agent"}:null),v(null),y(!0)},[a,N]),Ae=i.useCallback(()=>{y(!1),j(null),v(null)},[]),Je=i.useCallback(async G=>{try{const ge=await ih(G.id,e);J(ge),je("")}catch{n?.("Failed to load approval request","error")}},[e,n]),dt=i.useCallback(async G=>{if(!(!k||He)){xe(G);try{await _0(k.id,{decision:G,comment:ce||void 0},e),await Ue(Z);const ge=await ih(k.id,e);J(ge),je(""),n?.(`Request ${G==="approve"?"approved":"denied"}`,"success")}catch{n?.("Failed to submit decision","error")}finally{xe(!1)}}},[k,He,ce,e,Ue,Z,n]),Nt=()=>{if(!p||b)return null;const G=O$(x,p);return t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",id:Id(p.id),children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[ee&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:re,"data-testid":"mailbox-back-to-list",children:"← Back"}),t.jsxs("div",{className:"mailbox-message-detail-meta",children:[t.jsx("span",{className:"mailbox-message-type",children:L$(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:qi(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ut(p),"data-testid":"mailbox-reply",children:[t.jsx(Ki,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>xt(p.id),"data-testid":"mailbox-delete",children:[t.jsx(_n,{size:14}),t.jsx("span",{children:"Delete"})]})]})]}),t.jsxs("div",{className:"mailbox-message-participants",children:[t.jsxs("div",{className:"mailbox-participant",children:[t.jsx("span",{className:"mailbox-participant-label",children:"From:"}),t.jsxs("span",{className:"mailbox-participant-value",children:[p.fromType==="agent"?t.jsx(Kn,{size:14}):t.jsx(Ea,{size:14}),Y(p.fromId,p.fromType)]})]}),t.jsxs("div",{className:"mailbox-participant",children:[t.jsx("span",{className:"mailbox-participant-label",children:"To:"}),t.jsxs("span",{className:"mailbox-participant-value",children:[p.toType==="agent"?t.jsx(Kn,{size:14}):t.jsx(Ea,{size:14}),Y(p.toId,p.toType)]})]})]}),G.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),G.map(ge=>{const pt=ge.metadata?.replyTo?.messageId,ke=pt?G.find(tt=>tt.id===pt):void 0;return t.jsxs("div",{id:Id(ge.id),className:`mailbox-conversation-msg ${ge.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:Y(ge.fromId,ge.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:qi(ge.createdAt)})]}),pt&&t.jsxs("div",{className:"mailbox-reply-context-static","data-testid":`mailbox-reply-context-${ge.id}`,children:["↪ Replying to ",ke?Mf(ke.content,60):`message ${pt}`]}),t.jsx(Sf,{content:ge.content,className:"mailbox-conversation-msg-body"})]},ge.id)})]}),G.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context-static","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx(Sf,{content:p.content,className:"mailbox-message-body",testId:"mailbox-message-body"})]})]})},yt=()=>t.jsxs(t.Fragment,{children:[a==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Nl,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(ra,{size:32}),t.jsx("p",{children:"No messages in your inbox"})]}),o?.messages.map(G=>t.jsxs("div",{id:no(G.id),className:`mailbox-item ${G.read?"":"unread"}`,onClick:()=>me(G),"data-testid":`mailbox-item-${G.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:G.fromType==="agent"?t.jsx(Kn,{size:16}):t.jsx(Ea,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:Y(G.fromId,G.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:qi(G.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[G.content.slice(0,80),G.content.length>80?"…":""]})]}),!G.read&&t.jsx("div",{className:"mailbox-item-unread-dot","data-testid":`mailbox-unread-dot-${G.id}`})]},G.id))]}),a==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Nl,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(Ia,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(G=>t.jsxs("div",{id:no(G.id),className:"mailbox-item",onClick:()=>me(G),"data-testid":`mailbox-item-${G.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:G.toType==="agent"?t.jsx(Kn,{size:16}):t.jsx(Ea,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",Y(G.toId,G.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:qi(G.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[G.content.slice(0,80),G.content.length>80?"…":""]})]})]},G.id))]}),a==="approvals"&&t.jsxs("div",{className:"mailbox-approvals","data-testid":"mailbox-approvals",children:[t.jsxs("div",{className:"mailbox-approval-filters","data-testid":"mailbox-approval-filters",children:[t.jsx("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${Z==="pending"?"active":""}`,onClick:()=>{ne("pending"),J(null)},"data-testid":"mailbox-approval-filter-pending",children:"Pending"}),t.jsx("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${Z==="history"?"active":""}`,onClick:()=>{ne("history"),J(null)},"data-testid":"mailbox-approval-filter-history",children:"History"})]}),t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-approval-list",children:[O.length===0&&!h&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-approval-empty",children:[t.jsx(ra,{size:32}),t.jsx("p",{children:Z==="pending"?"No pending approvals":"No historical approvals"})]}),O.map(G=>t.jsxs("div",{className:"mailbox-item mailbox-approval-item",onClick:()=>void Je(G),"data-testid":`mailbox-approval-item-${G.id}`,children:[t.jsx("div",{className:`status-dot mailbox-approval-status-dot mailbox-approval-status-dot--${G.status}`}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-from",children:[G.agentId," · ",G.actionCategory]}),t.jsx("span",{className:"mailbox-item-time",children:qi(G.createdAt)})]}),t.jsx("div",{className:"mailbox-item-preview",children:G.actionSummary})]}),t.jsx("span",{className:`mailbox-approval-status mailbox-approval-status--${G.status}`,children:G.status})]},G.id))]})]}),a==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:D.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Kn,{size:32}),t.jsx("p",{children:"No agents found"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mailbox-agents-header",children:[t.jsx("div",{className:"mailbox-agents-dropdown",children:t.jsxs("select",{className:"message-composer-select mailbox-agent-select",value:N,onChange:G=>{I(G.target.value),_("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:Ds,children:"All agents"}),D.map(G=>t.jsx("option",{value:G.id,children:G.name||G.id},G.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:vt,"data-testid":"mailbox-compose-btn",children:[t.jsx(Ki,{size:14}),t.jsx("span",{children:"Compose"})]})]}),N&&N!==Ds&&t.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"mailbox-agent-subtabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${F==="inbox"?"active":""}`,onClick:()=>_("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(ra,{size:12}),t.jsx("span",{children:"Inbox"}),M&&M.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:M.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${F==="outbox"?"active":""}`,onClick:()=>_("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(Ia,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[N===Ds&&h&&!U&&t.jsx(Nl,{}),N===Ds&&U&&U.messages.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(ra,{size:32}),t.jsx("p",{children:"No agent-to-agent messages"})]}),N===Ds&&U&&U.messages.map(G=>t.jsxs("div",{id:no(G.id),className:`mailbox-item ${G.read?"":"unread"}`,onClick:()=>me(G),"data-testid":`mailbox-item-${G.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:G.fromType==="agent"?t.jsx(Kn,{size:16}):t.jsx(Ea,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:Y(G.fromId,G.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:qi(G.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-participants","data-testid":`mailbox-item-participants-${G.id}`,children:[t.jsxs("span",{children:["From: ",Y(G.fromId,G.fromType)]}),t.jsxs("span",{children:["To: ",Y(G.toId,G.toType)]})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[G.content.slice(0,80),G.content.length>80?"…":""]})]})]},G.id)),N&&N!==Ds&&h&&!M&&t.jsx(Nl,{}),N&&N!==Ds&&M&&F==="inbox"&&M.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(ra,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),N&&N!==Ds&&M&&F==="outbox"&&M.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Ia,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),N&&N!==Ds&&M&&F==="inbox"&&M.inbox.map(G=>t.jsxs("div",{id:no(G.id),className:`mailbox-item ${G.read?"":"unread"}`,onClick:()=>me(G),"data-testid":`mailbox-item-${G.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:G.fromType==="agent"?t.jsx(Kn,{size:16}):t.jsx(Ea,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:Y(G.fromId,G.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:qi(G.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[G.content.slice(0,80),G.content.length>80?"…":""]})]})]},G.id)),N&&N!==Ds&&M&&F==="outbox"&&M.outbox.map(G=>t.jsxs("div",{id:no(G.id),className:"mailbox-item",onClick:()=>me(G),"data-testid":`mailbox-item-${G.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:G.toType==="agent"?t.jsx(Kn,{size:16}):t.jsx(Ea,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",Y(G.toId,G.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:qi(G.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[G.content.slice(0,80),G.content.length>80?"…":""]})]})]},G.id))]})]})})]}),Se=()=>b?t.jsx(Cf,{recipient:S,replyContext:C,agents:D,projectId:e,onSend:Qe,onCancel:Ae,addToast:n}):p?Nt():a==="approvals"&&k?t.jsxs("div",{className:"mailbox-message-detail mailbox-approval-detail","data-testid":"mailbox-approval-detail",children:[ee&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>J(null),"data-testid":"mailbox-approval-back-to-list",children:"← Back"}),t.jsx("div",{className:"mailbox-message-detail-header",children:t.jsxs("div",{className:"mailbox-message-detail-meta",children:[t.jsx("span",{className:"mailbox-message-type",children:k.actionCategory}),t.jsx("span",{className:"mailbox-message-time",children:k.status})]})}),t.jsxs("div",{className:"mailbox-message-body",children:[t.jsx("strong",{children:k.actionSummary}),t.jsxs("p",{children:["Requester: ",k.requester.actorName," (",k.agentId,")"]}),k.taskId&&t.jsxs("p",{children:["Task: ",k.taskId]}),t.jsxs("p",{children:["Requested: ",qi(k.createdAt)]})]}),t.jsx("div",{className:"mailbox-conversation","data-testid":"mailbox-approval-history",children:k.history.map(G=>t.jsxs("div",{className:"mailbox-conversation-msg",children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:G.eventType}),t.jsx("span",{children:G.actor.actorName})]}),G.note&&t.jsx("div",{className:"mailbox-item-preview",children:G.note})]},G.id))}),k.status==="pending"&&t.jsxs("div",{className:"mailbox-approval-decision","data-testid":"mailbox-approval-decision",children:[t.jsx("textarea",{className:"message-composer-textarea mailbox-approval-comment",value:ce,onChange:G=>je(G.target.value),placeholder:"Optional comment","data-testid":"mailbox-approval-comment"}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>void dt("deny"),disabled:He!==!1,"data-testid":"mailbox-approval-deny",children:"Deny"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void dt("approve"),disabled:He!==!1,"data-testid":"mailbox-approval-approve",children:"Approve"})]})]})]}):t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(Da,{size:24}),t.jsx("p",{children:"Select a message to read"})]});return t.jsxs("div",{className:"mailbox-view",style:ae,"data-testid":"mailbox-view",children:[t.jsxs("div",{className:"mailbox-header",children:[t.jsxs("div",{className:"mailbox-title",children:[t.jsx(Da,{size:18}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mailbox-unread-badge","data-testid":"mailbox-unread-badge",children:u})]}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:vt,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(Ki,{size:14}),t.jsx("span",{children:"Compose"})]}),a==="inbox"&&u>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:_e,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Em,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{a==="inbox"?nt():a==="outbox"?Be():a==="approvals"?Ue(Z):N===Ds?Ie():N&&de(N)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(jt,{size:14,className:"spin"}):t.jsx(bs,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="inbox"?"active":""}`,onClick:()=>{r("inbox"),g(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(ra,{size:14}),t.jsx("span",{children:"Inbox"}),u>0&&t.jsx("span",{className:"mailbox-tab-badge",children:u})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="outbox"?"active":""}`,onClick:()=>{r("outbox"),g(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(Ia,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="agents"?"active":""}`,onClick:()=>{r("agents"),g(null),J(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(Kn,{size:14}),t.jsx("span",{children:"Agents"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="approvals"?"active":""}`,onClick:()=>{r("approvals"),g(null),J(null)},"data-testid":"mailbox-tab-approvals",children:[t.jsx(Em,{size:14}),t.jsx("span",{children:"Approvals"}),P>0&&t.jsx("span",{className:"mailbox-tab-badge","data-testid":"mailbox-approvals-pending-badge",children:P})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:oe?t.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",ref:pe,children:[t.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",style:{width:`${W}px`},children:yt()}),t.jsx("div",{className:"mailbox-split-resize-handle","data-testid":"mailbox-split-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize message list pane",tabIndex:0,"aria-valuemin":tc,"aria-valuemax":Math.round(Su(pe.current?.clientWidth??W/Nu)),"aria-valuenow":Math.round(W),onMouseDown:qe,onKeyDown:Pe}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:Se()})]}):t.jsxs(t.Fragment,{children:[Nt(),a==="approvals"&&k&&Se(),b&&t.jsx(Cf,{recipient:S,replyContext:C,agents:D,projectId:e,onSend:Qe,onCancel:Ae,addToast:n}),!p&&!k&&!b&&yt()]})})]})}function Nl(){return t.jsx("div",{className:"mailbox-skeleton","data-testid":"mailbox-skeleton",children:Array.from({length:5}).map((e,n)=>t.jsxs("div",{className:"mailbox-skeleton-item",children:[t.jsx("div",{className:"mailbox-skeleton-avatar"}),t.jsxs("div",{className:"mailbox-skeleton-content",children:[t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--short"}),t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--long"})]})]},n))})}const z$=640;function B$({isOpen:e,onClose:n,onImport:s,tasks:a,projectId:r}){Ni(e);const[o,l]=i.useState(""),[c,d]=i.useState(""),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState("issues"),[x,w]=i.useState([]),[b,y]=i.useState(null),[S,j]=i.useState([]),[C,v]=i.useState(null),[N,I]=i.useState(null),[F,_]=i.useState(!1),[M,z]=i.useState([]),[U,R]=i.useState(!1),[D,K]=i.useState(""),Z=i.useRef(!1),ne=i.useRef(null);Li(ne,e,"fusion:github-modal-size");const O=Qi(n),[A,P]=i.useState(!1),[$,k]=i.useState("list"),J=i.useRef(null),ce=new Set;for(const me of a){const re=me.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);re&&ce.add(re[1]);const _e=me.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);_e&&ce.add(_e[1])}i.useEffect(()=>{if(e)return l(""),d(""),m(""),w([]),y(null),j([]),v(null),g("issues"),I(null),_(!1),z([]),R(!0),K(""),J.current=null,Z.current=!0,NN().then(me=>{if(Z.current)if(z(me),R(!1),me.length===1){const re=me[0];l(re.owner),d(re.repo),K(re.name)}else me.length>1&&(l(""),d(""),K(""))}).catch(()=>{Z.current&&R(!1)}),()=>{Z.current=!1}},[e]);const je=i.useCallback(me=>{if(K(me),me==="")l(""),d("");else{const re=M.find(_e=>_e.name===me);re&&(l(re.owner),d(re.repo))}},[M]),He=i.useCallback(async()=>{if(!o.trim()||!c.trim()){I("Repository must be selected");return}f(!0),I(null),w([]),y(null);try{const me=u.split(",").map(_e=>_e.trim()).filter(Boolean),re=await yN(o.trim(),c.trim(),30,me.length>0?me:void 0);w(re),re.length===0&&I("No open issues found")}catch(me){I(Ee(me)||"Failed to fetch issues")}finally{f(!1)}},[o,c,u]),xe=i.useCallback(async()=>{if(!o.trim()||!c.trim()){I("Repository must be selected");return}f(!0),I(null),j([]),v(null);try{const me=await kN(o.trim(),c.trim(),30);j(me),me.length===0&&I("No open pull requests found")}catch(me){I(Ee(me)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);i.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||F)return;const me={owner:o.trim(),repo:c.trim(),labels:u.trim(),tab:p};J.current?.owner===me.owner&&J.current?.repo===me.repo&&J.current?.labels===me.labels&&J.current?.tab===me.tab||(J.current=me,p==="issues"?He():xe())},[o,c,u,p,e,h,F,He,xe]),i.useEffect(()=>{if(!e)return;const me=re=>{re.key==="Escape"&&n()};return document.addEventListener("keydown",me),()=>document.removeEventListener("keydown",me)},[e,n]),i.useEffect(()=>{if(!e)return;const me=()=>{P(window.innerWidth<=z$)};return me(),window.addEventListener("resize",me),()=>window.removeEventListener("resize",me)},[e]);const Ne=i.useCallback(me=>{y(me),A&&k("preview")},[A]),Y=i.useCallback(me=>{v(me),A&&k("preview")},[A]),ie=i.useCallback(()=>{k("list")},[]),ee=i.useCallback(async()=>{if(p==="issues"){if(b===null)return;_(!0),I(null);try{const me=await wN(o.trim(),c.trim(),b,r);s(me),y(null),A&&$==="preview"&&k("list")}catch(me){const re=Ee(me);re?.includes("already imported")?I(re):I(re||"Failed to import issue")}finally{_(!1)}}else{if(C===null)return;_(!0),I(null);try{const me=await jN(o.trim(),c.trim(),C,r);s(me),v(null),A&&$==="preview"&&k("list")}catch(me){const re=Ee(me);re?.includes("already imported")?I(re):I(re||"Failed to import pull request")}finally{_(!1)}}},[p,b,C,o,c,s,A,$]),oe=x.find(me=>me.number===b),W=S.find(me=>me.number===C);if(!e)return null;const L=M.length>0,pe=M.length===1,fe=x.filter(me=>ce.has(me.html_url)).length,B=S.filter(me=>ce.has(me.html_url)).length,ve=N==="No open issues found",Fe=N==="No open pull requests found",ae=p==="issues"?ve:Fe,qe=!!N&&!ve&&x.length===0&&!h,Pe=!!N&&!Fe&&S.length===0&&!h,nt=p==="issues"?qe:Pe,Be=h||x.length>0||ve||qe,de=h||S.length>0||Fe||Pe,Ie=p==="issues"?Be:de,$e=!!N&&x.length>0&&!ve,st=!!N&&S.length>0&&!Fe,Ue=p==="issues"?$e:st;return t.jsx("div",{className:"modal-overlay open",...O,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:ne,children:[t.jsxs("div",{className:"modal-header github-import-modal__header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Import from GitHub"}),t.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),t.jsxs("div",{className:"modal-body github-import-modal__body",children:[t.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[t.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{g("issues"),v(null)},disabled:h||F,children:[t.jsx(cc,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{g("pulls"),y(null)},disabled:h||F,children:[t.jsx(si,{size:16}),t.jsx("span",{children:"Pull Requests"})]})]}),t.jsxs("div",{className:"github-import-toolbar","data-testid":"github-import-toolbar",role:"toolbar","aria-label":"GitHub import controls",children:[t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--remote",children:U?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(jt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):L?pe?t.jsxs("div",{className:"github-import-remote-pill","data-testid":"github-import-single-remote",children:[t.jsx("span",{className:"github-import-remote-pill__name",children:M[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[M[0].owner,"/",M[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:D,onChange:me=>je(me.target.value),disabled:h||F,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),M.map(me=>t.jsxs("option",{value:me.name,children:[me.name," (",me.owner,"/",me.repo,")"]},me.name))]})]}):t.jsx("span",{className:"github-import-toolbar__no-remote",children:"No remotes"})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--filter",children:p==="issues"?t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"gh-labels",className:"visually-hidden",children:"Filter by labels"}),t.jsx("input",{id:"gh-labels",type:"text",placeholder:"Filter: bug,enhancement…",value:u,onChange:me=>m(me.target.value),onKeyDown:me=>me.key==="Enter"&&He(),disabled:h||F||!L,"aria-label":"Filter issues by labels"})]}):t.jsxs("span",{className:"github-import-filter-hint",children:["Open pull requests from ",o||"selected remote"]})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--action",children:t.jsxs("button",{id:"gh-load",className:"btn btn-primary github-import-load-button",onClick:p==="issues"?He:xe,disabled:h||F||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(jt,{size:14,className:"spin"}):t.jsx(bs,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!U&&!L&&t.jsxs("div",{className:"github-import-state github-import-state--warning",role:"alert",children:[t.jsxs("div",{children:[t.jsx("strong",{children:"No GitHub remotes detected"}),t.jsx("span",{children:"Add a GitHub remote to this repository, then reopen the modal."})]}),t.jsx("code",{className:"github-import-command",children:"git remote add origin https://github.com/owner/repo.git"})]}),Ue&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:N}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${A?"mobile":""} ${$==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[t.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&x.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[x.length," issue",x.length===1?"":"s"]}),t.jsxs("span",{children:[fe," imported"]})]}),p==="pulls"&&S.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[S.length," pull request",S.length===1?"":"s"]}),t.jsxs("span",{children:[B," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!Ie&&t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-results-idle",children:t.jsxs("div",{children:[t.jsx("strong",{children:"Nothing loaded yet"}),t.jsx("span",{children:"Select a repository and click Load to start reviewing import candidates."})]})}),h&&t.jsxs("div",{className:"github-import-state github-import-state--loading",role:"status","aria-live":"polite",children:[t.jsx(jt,{size:16,className:"spin"}),t.jsxs("div",{children:[t.jsxs("strong",{children:["Loading open ",p==="issues"?"issues":"pull requests","…"]}),t.jsx("span",{children:"Fetching the latest list from GitHub."})]})]}),nt&&t.jsx("div",{className:"github-import-state github-import-state--error",role:"alert",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["Could not load ",p==="issues"?"issues":"pull requests"]}),t.jsx("span",{children:N})]})}),ae&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&x.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:x.map(me=>{const re=ce.has(me.html_url);return t.jsxs("div",{className:`issue-item ${b===me.number?"selected":""} ${re?"imported":""}`,onClick:()=>!re&&Ne(me.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===me.number,onChange:()=>Ne(me.number),disabled:re,"aria-label":`Select issue #${me.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",me.number]}),t.jsx("span",{className:"issue-title",children:me.title})]}),me.labels.length>0&&t.jsx("span",{className:"issue-labels",children:me.labels.map(_e=>t.jsx("span",{className:"label-chip",children:_e.name},_e.name))})]}),re&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},me.number)})}),p==="pulls"&&S.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:S.map(me=>{const re=ce.has(me.html_url);return t.jsxs("div",{className:`issue-item ${C===me.number?"selected":""} ${re?"imported":""}`,onClick:()=>!re&&Y(me.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:C===me.number,onChange:()=>Y(me.number),disabled:re,"aria-label":`Select pull request #${me.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",me.number]}),t.jsx("span",{className:"issue-title",children:me.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[me.headBranch," → ",me.baseBranch]})]}),re&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},me.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${A?"mobile":""} ${$==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[A&&t.jsxs("button",{className:"github-import-back-button",onClick:ie,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(Ha,{size:16}),t.jsx("span",{children:"Back"})]}),t.jsx("h4",{id:"github-import-preview-heading",children:"Preview"})]}),t.jsxs("div",{className:"github-import-pane-content",children:[p==="issues"&&oe?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",oe.number]}),t.jsx("div",{className:"preview-title",children:oe.title}),t.jsx("div",{className:"preview-body",children:oe.body?oe.body.slice(0,200)+(oe.body.length>200?"…":""):"(no description)"})]}):p==="issues"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No issue selected"}),t.jsx("span",{children:"Choose an issue from the list to inspect its title and description."})]})}):null,p==="pulls"&&W?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",W.number]}),t.jsx("div",{className:"preview-title",children:W.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",W.headBranch," → ",W.baseBranch]}),t.jsx("div",{className:"preview-body",children:W.body?W.body.slice(0,200)+(W.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No pull request selected"}),t.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),t.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[t.jsx("button",{className:"btn",onClick:n,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:ee,disabled:(p==="issues"?b===null:C===null)||F,children:F?t.jsx(jt,{size:14,className:"spin"}):"Import"})]})]})})}function di({summary:e,children:n,className:s="",onToggle:a,defaultOpen:r=!1}){const[o,l]=i.useState(r);return t.jsxs("div",{className:`onboarding-disclosure ${s}`.trim(),children:[t.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>{const c=!o;l(c),a?.(c)},"aria-expanded":o,type:"button",children:[t.jsx(On,{size:14,className:"onboarding-disclosure-chevron","aria-hidden":"true"}),t.jsx("span",{children:e})]}),o?t.jsx("div",{className:"onboarding-disclosure-content",children:n}):null]})}const U$=["Build a user authentication system with login and signup","Add dark mode support to the dashboard","Create an API endpoint for exporting tasks as CSV","Refactor the task card component for better performance"];function Ba(e){return e&&pa.includes(e)?e:Ls}function Td(e){return{...e,priority:Ba(e.priority)}}function H$(e,n){return e.length===n.length&&e.every((s,a)=>s===n[a])}function q$(e,n){const s=new Map(e.map(a=>[a.id,a]));return n.map(a=>{const r=s.get(a.id),o=Ba(a.priority),l={id:a.id};return(!r||a.title!==r.title)&&(l.title=a.title),(!r||a.description!==r.description)&&(l.description=a.description),(!r||a.suggestedSize!==r.suggestedSize)&&(l.suggestedSize=a.suggestedSize),(!r||o!==Ba(r.priority))&&(l.priority=o),(!r||!H$(a.dependsOn,r.dependsOn))&&(l.dependsOn=a.dependsOn),l})}function V$(e,n){return e&&n?`${e}/${n}`:""}function W$(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function K$({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:a,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[d,u]=i.useState(""),[m,h]=i.useState({type:"initial"}),[f,p]=i.useState(null),[g,x]=i.useState([]),[w,b]=i.useState([]),[y,S]=i.useState(null),j=i.useRef(!1),C=i.useRef(!1),[v,N]=i.useState(""),[I,F]=i.useState(!0),[_,M]=i.useState(!1),[z,U]=i.useState(!1),[R,D]=i.useState(null),[K,Z]=i.useState(0),ne=i.useRef(null),O=i.useRef(null),A=i.useRef(null),P=i.useRef(null),$=i.useRef(null),k=i.useRef(null),J=i.useRef(null),[ce,je]=i.useState(c??null),He=i.useMemo(()=>Va(),[]),{isLockedByOther:xe,takeControl:Ne,isLoading:Y}=Ec(e?ce:null),{activeTabMap:ie,broadcastUpdate:ee,broadcastCompleted:oe,broadcastLock:W,broadcastUnlock:L,broadcastHeartbeat:pe}=Fr(),[fe,B]=i.useState(void 0),[ve,Fe]=i.useState(void 0),[ae,qe]=i.useState("medium"),[Pe,nt]=i.useState(""),[Be,de]=i.useState([]),[Ie,$e]=i.useState(!1),[st,Ue]=i.useState(null),[me,re]=i.useState([]),[_e,xt]=i.useState([]),[ut,Qe]=i.useState({}),vt=i.useRef(null),[Ae,Je]=i.useState([]),[dt,Nt]=i.useState(!1),[yt,Se]=i.useState(c??null),[G,ge]=i.useState(!!c),[pt,ke]=i.useState(null),[tt,Rt]=i.useState(!1),Re=i.useRef(!1),be=i.useRef(null),rt=i.useRef(""),lt=i.useRef(null),gt=i.useRef(null);Li(O,e,"fusion:planning-modal-size");const St=ri(),{keyboardOverlap:Lt,viewportHeight:Yt,viewportOffsetTop:tn,keyboardOpen:mn}=Zi({enabled:St==="mobile"});Ni(St==="mobile"&&e),i.useEffect(()=>{const he=O.current;he&&(mn?(he.style.setProperty("--keyboard-overlap",`${Lt}px`),he.style.setProperty("--vv-offset-top",`${tn}px`),Yt!==null?he.style.setProperty("--vv-height",`${Yt}px`):he.style.removeProperty("--vv-height")):(he.style.removeProperty("--keyboard-overlap"),he.style.removeProperty("--vv-offset-top"),he.style.removeProperty("--vv-height")))},[mn,Lt,tn,Yt]),i.useEffect(()=>{rt.current=v},[v]),i.useEffect(()=>{const he=be.current;if(!he)return;he.scrollHeight-he.scrollTop-he.clientHeight<32&&(he.scrollTop=he.scrollHeight)},[v]),i.useEffect(()=>{if(m.type!=="loading"){D(null),Z(0);return}const he=Date.now();D(he),Z(0);const ht=setInterval(()=>{Z(Math.max(0,Math.floor((Date.now()-he)/1e3)))},1e3);return()=>clearInterval(ht)},[m.type]),i.useEffect(()=>{if(m.type!=="loading")return;const he=P.current;if(!he)return;let ht=!1;const wt=setInterval(async()=>{try{const Xe=await Ti(he);if(ht||!Xe||P.current!==he)return;if(Xe.status==="awaiting_input"&&Xe.currentQuestion){const Et=JSON.parse(Xe.currentQuestion);h({type:"question",session:{sessionId:he,currentQuestion:Et,summary:null}}),N("")}else if(Xe.status==="complete"&&Xe.result){const Et=Td(JSON.parse(Xe.result));h({type:"summary",session:{sessionId:he,currentQuestion:null,summary:Et},summary:Et}),S(Et),N("")}}catch{}},8e3);return()=>{ht=!0,clearInterval(wt)}},[m.type]);const Qt=i.useCallback(()=>{u(""),h({type:"initial"}),p(null),x([]),b([]),S(null),N(""),M(!1),U(!1),B(void 0),Fe(void 0),qe("medium"),nt(""),P.current=null,je(null)},[]),yn=V$(fe,ve),Gt=i.useCallback((he,ht)=>{if(!he||!ht)return ut.provider&&ut.modelId?`${ut.provider}/${ut.modelId}`:"Using default";const at=Be.find(wt=>wt.provider===he&&wt.id===ht);return at?`${at.provider}/${at.id}`:`${he}/${ht}`},[Be,ut.modelId,ut.provider]),on=i.useCallback(async()=>{$e(!0),Ue(null);try{const he=await Ks();de(he.models),re(he.favoriteProviders),xt(he.favoriteModels),Qe({provider:he.resolvedPlanningProvider,modelId:he.resolvedPlanningModelId})}catch(he){Ue(Ee(he)||"Failed to load models")}finally{$e(!1)}},[]),sn=i.useCallback(he=>{re(ht=>{const at=ht,Xe=at.includes(he)?at.filter(Et=>Et!==he):[he,...at];return Dn({favoriteProviders:Xe,favoriteModels:_e}).catch(()=>{re(at)}),Xe})},[_e]),ln=i.useCallback(he=>{xt(ht=>{const at=ht,Xe=at.includes(he)?at.filter(Et=>Et!==he):[he,...at];return Dn({favoriteProviders:me,favoriteModels:Xe}).catch(()=>{xt(at)}),Xe})},[me]),Wt=i.useCallback(he=>{A.current?.close();const ht=()=>P.current!==he,at=CS(he,l,{onThinking:wt=>{ht()||(N(Xe=>Xe+wt),ee({sessionId:he,status:"generating",needsInput:!1,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onQuestion:wt=>{if(ht())return;M(!1),U(!1),or(l);const Xe=rt.current.trim();Xe&&b(Et=>Et[Et.length-1]?.thinkingOutput===Xe?Et:[...Et,{thinkingOutput:Xe}]),h({type:"question",session:{sessionId:he,currentQuestion:wt,summary:null}}),N(""),ee({sessionId:he,status:"awaiting_input",needsInput:!0,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null})},onSummary:wt=>{if(ht())return;M(!1),U(!1),or(l);const Xe=rt.current.trim();Xe&&b(Et=>Et[Et.length-1]?.thinkingOutput===Xe?Et:[...Et,{thinkingOutput:Xe}]),h({type:"summary",session:{sessionId:he,currentQuestion:null,summary:wt},summary:wt}),S(wt),N(""),ee({sessionId:he,status:"complete",needsInput:!1,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null})},onError:wt=>{const Xe=wt||"Session failed while contacting the AI.";M(!0),(async()=>{try{const Et=await Ti(he);if(Et&&(Et.status==="generating"||Et.status==="awaiting_input")){Wt(he);return}}catch{}M(!1),U(!1),p(null),h(Et=>Et.type==="question"||Et.type==="summary"||Et.type==="error"?{type:"error",session:Et.session,errorMessage:Xe}:{type:"error",session:{sessionId:he,currentQuestion:null,summary:null},errorMessage:Xe}),N(""),P.current=he,ee({sessionId:he,status:"error",needsInput:!1,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null}),oe({sessionId:he,status:"error"})})()},onComplete:()=>{M(!1),U(!1),P.current=null,oe({sessionId:he,status:"complete"})},onConnectionStateChange:wt=>{M(wt==="reconnecting")}});A.current=at},[oe,ee,d,l,He]),ye=i.useCallback(async he=>{const ht=he??d;if(ht.trim()){p(null),N(""),b([]),x([]),M(!1),h({type:"loading"});try{const at=fe&&ve?{planningModelProvider:fe,planningModelId:ve}:void 0,wt=Pe.trim()?Number.parseInt(Pe,10):void 0,Xe=$.current,{sessionId:Et}=await lS(ht.trim(),l,at,{planningDepth:ae,customQuestionCount:Number.isInteger(wt)?wt:void 0},Xe??void 0);$.current=null,P.current=Et,je(Et),Se(Et),Wt(Et),x([])}catch(at){M(!1),p(Ee(at)||"Failed to start planning session"),h({type:"initial"}),P.current=null,je(null)}}},[Wt,Pe,d,ae,ve,fe,l]);i.useEffect(()=>{e&&m.type==="initial"&&ne.current?.focus()},[e,m.type]),i.useEffect(()=>{e&&on()},[e,on]),i.useEffect(()=>{if(e&&o&&!j.current&&m.type==="initial"){u(o);const he=setTimeout(()=>{j.current=!0,ye(o)},0);return()=>clearTimeout(he)}else if(e&&!o&&!j.current&&!C.current&&m.type==="initial"){C.current=!0;const he=GP(l);he&&u(he)}},[e,o,m.type,ye,l]);const Le=i.useCallback(async he=>{A.current?.close(),A.current=null,p(null),N(""),x([]),b([]),S(null),U(!1),h({type:"loading"});try{const ht=await Ti(he);if(!ht){Se(null),ge(!1),h({type:"initial"});return}P.current=he,je(he);const at=jr(ht.conversationHistory);if(b(at),x(at.map(wt=>wt.response).filter(wt=>!!(wt&&typeof wt=="object"&&!Array.isArray(wt)))),ht.status==="draft"){let wt="",Xe,Et;try{const Zt=ht.inputPayload?JSON.parse(ht.inputPayload):null;Zt&&typeof Zt.initialPlan=="string"&&(wt=Zt.initialPlan),Zt&&typeof Zt.modelProvider=="string"&&typeof Zt.modelId=="string"&&(Xe=Zt.modelProvider,Et=Zt.modelId)}catch{}u(wt),B(Xe),Fe(Et),$.current=he,gt.current=wt?{sessionId:he,initialPlan:wt.trim(),modelProvider:Xe,modelId:Et}:null,h({type:"initial"})}else if(ht.status==="awaiting_input"&&ht.currentQuestion){or(l);const wt=JSON.parse(ht.currentQuestion);if(h({type:"question",session:{sessionId:he,currentQuestion:wt,summary:null}}),ht.thinkingOutput){const Xe=ht.thinkingOutput.trim();Xe&&b(Et=>Et[Et.length-1]?.thinkingOutput===Xe?Et:[...Et,{thinkingOutput:Xe}])}Wt(he)}else if(ht.status==="complete"&&ht.result){or(l);const wt=Td(JSON.parse(ht.result));h({type:"summary",session:{sessionId:he,currentQuestion:null,summary:wt},summary:wt}),S(wt)}else ht.status==="generating"?(h({type:"loading"}),ht.thinkingOutput&&N(ht.thinkingOutput),Wt(he)):ht.status==="error"&&h({type:"error",session:{sessionId:he,currentQuestion:null,summary:null},errorMessage:ht.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[Wt,l]);i.useEffect(()=>{!e||!c||P.current!==c&&J.current!==c&&(Se(c),ge(!0),Le(c))},[e,c]),i.useEffect(()=>{e&&yt&&(c&&c===yt||Le(yt))},[e]);const Ke=i.useCallback(async()=>{Nt(!0);try{const ht=(await zu(l,{includeCompleted:!0,includeArchived:tt})).filter(at=>at.type==="planning").sort((at,wt)=>Date.parse(wt.updatedAt)-Date.parse(at.updatedAt));Je(ht)}catch{}finally{Nt(!1)}},[l,tt]);i.useEffect(()=>{e&&Ke()},[e,Ke]);const mt=i.useRef(!1);i.useEffect(()=>{const he=mt.current&&!dt;mt.current=dt,he&&St==="mobile"&&(G||c||yt||Ae.length>0||ge(!0))},[St,G,c,yt,dt,Ae.length]),i.useEffect(()=>{if(!e)return;const he=l?`?projectId=${encodeURIComponent(l)}`:"",ht=wt=>{try{const Xe=JSON.parse(wt.data);if(Xe.type!=="planning")return;Je(Et=>{const Zt=Et.findIndex(ct=>ct.id===Xe.id);return(Zt>=0?[...Et.slice(0,Zt),Xe,...Et.slice(Zt+1)]:[Xe,...Et]).sort((ct,nn)=>Date.parse(nn.updatedAt)-Date.parse(ct.updatedAt))})}catch{}},at=wt=>{try{const Xe=JSON.parse(wt.data);Je(Et=>Et.filter(Zt=>Zt.id!==Xe))}catch{}};return hi(`/api/events${he}`,{events:{"ai_session:updated":ht,"ai_session:deleted":at},onReconnect:()=>{Ke()}})},[e,l,Ke]);const Ve=i.useCallback(he=>{if(yt===he){ge(!0);return}Se(he),ge(!0),Le(he)},[Le,yt]),Pt=i.useCallback(()=>{A.current?.close(),A.current=null,$.current=null,k.current&&(clearTimeout(k.current),k.current=null),c&&(J.current=c),Qt(),Se(null),ge(!0)},[Qt,c]),Ot=i.useCallback(()=>{ge(!1)},[]),bt=i.useCallback(async(he,ht)=>{const at=ht.trim();if(!(!at||gt.current?.sessionId===he&&gt.current.initialPlan===at&&gt.current.modelProvider===fe&&gt.current.modelId===ve))try{await b0(he,{initialPlan:at,modelProvider:fe&&ve?fe:void 0,modelId:fe&&ve?ve:void 0},l),gt.current={sessionId:he,initialPlan:at,modelProvider:fe,modelId:ve}}catch{}},[ve,fe,l]);i.useEffect(()=>{if(lt.current&&(clearTimeout(lt.current),lt.current=null),!(!e||m.type!=="initial"||!yt))return lt.current=setTimeout(()=>{bt(yt,d)},500),()=>{lt.current&&(clearTimeout(lt.current),lt.current=null)}},[d,e,yt,bt,m.type]),i.useEffect(()=>{gt.current=null},[yt]),i.useEffect(()=>()=>{lt.current&&(clearTimeout(lt.current),lt.current=null)},[]);const Dt=i.useCallback(async he=>{const ht=wt=>wt==="generating"||wt==="awaiting_input",at=Ae.find(wt=>wt.id===he);if(at&&ht(at.status))try{await lb(he,l,He)}catch{}try{await bb(he)}catch{}oe({sessionId:he,status:"complete",timestamp:Date.now()}),Je(wt=>wt.filter(Xe=>Xe.id!==he)),yt===he&&(A.current?.close(),A.current=null,Qt(),Se(null),ge(!1)),ke(null)},[oe,Ae,l,Qt,yt,He]),Ft=i.useCallback(async he=>{const at=Ae.find(wt=>wt.id===he)?.archived===!0;try{at?await m0(he):await u0(he)}catch{return}Je(wt=>!at&&!tt?wt.filter(Xe=>Xe.id!==he):wt.map(Xe=>Xe.id===he?{...Xe,archived:!at}:Xe)),!at&&yt===he&&!tt&&(A.current?.close(),A.current=null,Qt(),Se(null),ge(!1))},[Ae,Qt,yt,ge,tt]);i.useEffect(()=>{e||(j.current=!1,C.current=!1,M(!1),U(!1),je(null))},[e]),i.useEffect(()=>{if(!e){vt.current&&(L(vt.current,He),vt.current=null);return}if(ce&&vt.current!==ce){vt.current&&L(vt.current,He),W(ce,He),vt.current=ce;return}!ce&&vt.current&&(L(vt.current,He),vt.current=null)},[W,L,e,ce,He]),i.useEffect(()=>{if(!e||!ce||vt.current!==ce)return;pe(He);const he=setInterval(()=>{pe(He)},3e4);return()=>{clearInterval(he)}},[pe,e,ce,He]),i.useEffect(()=>()=>{k.current&&(clearTimeout(k.current),k.current=null),A.current?.close(),A.current=null,vt.current&&(L(vt.current,He),vt.current=null)},[L,He]),i.useEffect(()=>{if(!e)return;const he=()=>{A.current?.close(),A.current=null};return window.addEventListener("beforeunload",he),()=>window.removeEventListener("beforeunload",he)},[e]);const Ht=i.useCallback((he,ht)=>{lt.current&&(clearTimeout(lt.current),lt.current=null),(async()=>{try{await bt(he,ht),await x0(he,l)}catch{}})()},[l,bt]),rn=i.useCallback(()=>{if(St!=="mobile")return;const he=document.activeElement;he instanceof HTMLElement&&he.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})},[St]),Xt=i.useCallback(()=>{d&&m.type==="initial"&&KP(d,l);const he=$.current;he&&d.trim()&&Ht(he,d),$.current=null,k.current&&(clearTimeout(k.current),k.current=null),A.current?.close(),A.current=null,M(!1),U(!1),rn(),n()},[Ht,d,n,l,rn,m.type]);i.useEffect(()=>{if(!e)return;const he=ht=>{ht.key==="Escape"&&Xt()};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[e,Xt]);const an=i.useCallback(async he=>{if(m.type!=="question")return;const{session:ht}=m,at=ht.sessionId,wt=ht.currentQuestion;if(!wt){p("No active question in session");return}p(null),x(Xe=>[...Xe,he]),b(Xe=>{const Et=rt.current.trim();let Zt=Xe;return Et&&Zt[Zt.length-1]?.thinkingOutput!==Et&&(Zt=[...Zt,{thinkingOutput:Et}]),[...Zt,{question:wt,response:he}]}),h({type:"loading"}),N("");try{await qm(at,he,l,He)}catch(Xe){p(Ee(Xe)||"Failed to submit response"),h({type:"question",session:ht})}},[l,He,m]),Me=i.useCallback(async()=>{if(m.type!=="summary")return;const{session:he,summary:ht}=m,at=he.sessionId;P.current=at,je(at),p(null),U(!1),N(""),h({type:"loading"}),Wt(at);try{await qm(at,{refine:!0},l,He)}catch(wt){A.current?.close(),A.current=null,p(Ee(wt)||"Failed to refine plan"),h({type:"summary",session:he,summary:y??ht})}},[Wt,y,l,He,m]),it=i.useCallback(async()=>{const he=P.current;if(he){try{await uS(he,l,He)}catch{}A.current?.close(),A.current=null,M(!1),U(!1),h({type:"error",session:{sessionId:he,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),N("")}},[l,He]),kt=i.useCallback(async()=>{if(m.type!=="error")return;const he=m.session;p(null),U(!0),N(""),h({type:"loading"}),Wt(he.sessionId);try{P.current=he.sessionId,je(he.sessionId),await dS(he.sessionId,l,He)}catch(ht){let at=ht;if((Ee(ht)||"").includes("not in an error state"))try{const Xe=await Ti(he.sessionId);if(!Xe)throw new Error("Failed to refresh planning session.");if(P.current=Xe.id,je(Xe.id),Xe.status==="generating")N(Xe.thinkingOutput??""),h({type:"loading"});else if(Xe.status==="awaiting_input"){if(!Xe.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const Et=JSON.parse(Xe.currentQuestion);if(or(l),h({type:"question",session:{sessionId:Xe.id,currentQuestion:Et,summary:null}}),Xe.thinkingOutput){const Zt=Xe.thinkingOutput.trim();Zt&&b(le=>le[le.length-1]?.thinkingOutput===Zt?le:[...le,{thinkingOutput:Zt}])}A.current?.isConnected()||Wt(Xe.id)}else if(Xe.status==="complete"){if(!Xe.result)throw new Error("Planning session is complete but has no result.");const Et=Td(JSON.parse(Xe.result));or(l),h({type:"summary",session:{sessionId:Xe.id,currentQuestion:null,summary:Et},summary:Et}),S(Et)}else Xe.status==="error"&&h({type:"error",session:{sessionId:Xe.id,currentQuestion:null,summary:null},errorMessage:Xe.error||"Retry failed. Please try again."});M(!1);return}catch(Xe){at=Xe}A.current?.close(),A.current=null,h({type:"error",session:he,errorMessage:Ee(at)||"Retry failed. Please try again."}),M(!1)}finally{U(!1)}},[Wt,l,He,m]),$t=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const he=m.session.sessionId,ht=await mS(he,y??void 0,l);s(ht),Se(null),Je(at=>at.filter(wt=>wt.id!==he)),oe({sessionId:he,status:"complete",timestamp:Date.now()}),Xt()}catch(he){p(Ee(he)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[oe,y,m,l,s,Xt]),se=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const he=await hS(m.session.sessionId,y??void 0,l),ht=he.subtasks.map(at=>({...at,priority:Ba(at.priority),dependsOn:[...at.dependsOn]}));je(he.sessionId),h({type:"breakdown",sessionId:he.sessionId,originalSubtasks:ht.map(at=>({...at,dependsOn:[...at.dependsOn]})),subtasks:ht.map(at=>({...at,dependsOn:[...at.dependsOn]})),dirty:!1})}catch(he){p(Ee(he)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),te=i.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const he=m.sessionId,ht=await pS(he,q$(m.originalSubtasks,m.subtasks.map(at=>({...at,priority:Ba(at.priority)}))),l);a(ht.tasks),Je(at=>at.filter(wt=>wt.id!==he)),oe({sessionId:he,status:"complete",timestamp:Date.now()}),u(""),h({type:"initial"}),p(null),x([]),b([]),S(null),N(""),B(void 0),Fe(void 0),qe("medium"),nt(""),P.current=null,je(null),Se(null),Xt()}catch(he){p(Ee(he)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,originalSubtasks:m.originalSubtasks,subtasks:m.subtasks,dirty:m.dirty})}}},[oe,Xt,m,a,l]),De=i.useCallback(async()=>{if(m.type!=="question"||g.length===0)return;const he=m.session.sessionId;p(null),h({type:"loading"});try{const ht=await cS(he,l,He);x(ht.history.map(at=>at.response&&typeof at.response=="object"&&!Array.isArray(at.response)?at.response:{[at.question.id]:at.response})),b(ht.history.map(at=>({question:at.question,response:at.response&&typeof at.response=="object"&&!Array.isArray(at.response)?at.response:{[at.question.id]:at.response},thinkingOutput:at.thinkingOutput}))),N(""),h({type:"question",session:{...m.session,currentQuestion:ht.currentQuestion,summary:null}})}catch(ht){p(Ee(ht)||"Failed to go back to the previous question"),h({type:"question",session:m.session})}},[l,g.length,He,m]),ft=()=>m.type==="question"?Math.min(g.length+1,3):3,qt=ce?ie.get(ce):null,zt=qt&&qt.tabId!==He,Pn=xe&&(!zt||qt.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:he=>{Re.current=he.target===he.currentTarget},onClick:he=>{he.target===he.currentTarget&&Re.current&&Xt(),Re.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:O,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[G&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:Ot,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(lc,{size:18})}),t.jsx($i,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Planning Mode"})]}),t.jsx("div",{className:"modal-header-actions",children:t.jsx("button",{className:"modal-close",onClick:Xt,"aria-label":"Close",children:t.jsx(un,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${G?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(X$,{sessions:Ae,loading:dt,selectedSessionId:yt,pendingDeleteId:pt,showArchived:tt,onToggleShowArchived:()=>Rt(he=>!he),onArchive:he=>void Ft(he),onSelectSession:Ve,onNewSession:Pt,onRequestDelete:ke,onConfirmDelete:he=>void Dt(he),onCancelDelete:()=>ke(null)}),t.jsxs("div",{className:"planning-detail",children:[f&&t.jsx("div",{className:"form-error planning-error",children:f}),_&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),m.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(gs,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your idea into a detailed task"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build in plain language. The AI will ask clarifying questions and help you structure a well-defined task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"initial-plan",children:"What do you want to build?"}),t.jsx("textarea",{ref:ne,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:d,onChange:he=>{const ht=he.target.value;u(ht),!($.current||ht.trim().length===0)&&(k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{if($.current)return;const at=ht.trim();if(!at)return;oS(at,l,fe&&ve?{planningModelProvider:fe,planningModelId:ve}:void 0).then(Xe=>{$.current=Xe.sessionId,Je(Et=>Et.some(le=>le.id===Xe.sessionId)?Et:[{id:Xe.sessionId,type:"planning",status:"draft",title:Xe.title,preview:at.length>80?`${at.slice(0,79).trimEnd()}…`:at,projectId:l??null,lockedByTab:null,updatedAt:new Date().toISOString(),archived:!1},...Et].sort((le,ct)=>Date.parse(ct.updatedAt)-Date.parse(le.updatedAt))),Se(Xe.sessionId)}).catch(()=>{})},300))},onKeyDown:he=>{he.key==="Enter"&&!he.shiftKey&&d.trim()&&(he.preventDefault(),ye())},onBlur:()=>{const he=$.current;he&&d.trim()&&Ht(he,d)}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:U$.map((he,ht)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>u(he),children:he.length>40?he.slice(0,40)+"...":he},ht))})]}),t.jsx(di,{summary:"Advanced planning settings",className:"planning-advanced-disclosure",children:t.jsxs("div",{className:"planning-advanced-content",children:[t.jsxs("div",{className:"planning-advanced-section planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",Ie&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx("p",{className:"planning-advanced-blurb",children:"Selects which model runs the planning interview and writes the final draft."}),t.jsx(Is,{id:"planning-modal-model",label:"Planning Model",value:yn,onChange:he=>{const{provider:ht,modelId:at}=W$(he);B(ht),Fe(at)},models:Be,disabled:Ie,favoriteProviders:me,onToggleFavorite:sn,favoriteModels:_e,onToggleModelFavorite:ln}),st&&t.jsxs("div",{className:"form-hint form-hint-error",children:[st," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{on()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${fe&&ve?"model-badge-custom":"model-badge-default"}`,children:Gt(fe,ve)})})]}),t.jsxs("div",{className:"planning-advanced-section planning-depth-selector",children:[t.jsx("p",{className:"planning-advanced-blurb",children:"Plan size sets default interview depth. Questions lets you override with an exact count."}),t.jsxs("div",{className:"planning-depth-controls-row",children:[t.jsx("div",{className:"planning-depth-chip-group",role:"group","aria-label":"Planning depth",children:[{value:"small",label:"Small"},{value:"medium",label:"Medium"},{value:"large",label:"Large"}].map(he=>t.jsx("button",{type:"button",className:`planning-depth-chip btn ${ae===he.value?"btn-primary planning-depth-chip-active":""}`,onClick:()=>qe(he.value),"aria-pressed":ae===he.value,children:he.label},he.value))}),t.jsxs("label",{className:"planning-depth-question-count",htmlFor:"planning-depth-questions",children:[t.jsx("span",{children:"Questions"}),t.jsx("input",{id:"planning-depth-questions",className:"input planning-depth-question-input",type:"number",min:1,max:20,value:Pe,onChange:he=>nt(he.target.value),placeholder:"Auto"})]})]})]})]})})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ye(),disabled:!d.trim(),children:[t.jsx($i,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:v?"AI is thinking...":"Generating next question..."}),R&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",K,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>F(!I),type:"button",children:I?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void it(),children:[t.jsx(Hy,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),I&&v&&t.jsx("div",{className:"planning-thinking-output",ref:be,children:t.jsx("pre",{children:v})})]})]}),m.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[w.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(mi,{entries:w}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:m.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void kt(),disabled:z,children:[z?t.jsx(jt,{size:14,className:"spin"}):t.jsx(bs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:z?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Xt,disabled:z,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"Creating tasks..."})]}),m.type==="question"&&m.session.currentQuestion&&t.jsx("div",{className:"planning-question",children:t.jsx(G$,{question:m.session.currentQuestion,progress:ft(),historyEntries:w,onSubmit:an,onBack:g.length>0?De:void 0})}),m.type==="summary"&&y&&t.jsx(J$,{summary:y,historyEntries:w,onSummaryChange:S,tasks:r,onCreateTask:$t,onBreakIntoTasks:se,onRefine:()=>{Me()},isLoading:!1}),m.type==="breakdown"&&t.jsx(Q$,{subtasks:m.subtasks,isLoading:!1,onUpdateSubtasks:he=>h({...m,subtasks:he,dirty:!0}),onCreateTasks:te,onBack:()=>{const ht={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:ht,summary:y})}})]}),xe&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(pc,{size:16}),t.jsx("span",{children:Pn?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Pn&&t.jsx("button",{type:"button",onClick:()=>{Ne()},disabled:Y,className:"btn btn-primary session-lock-take-control",children:Y?"Taking control...":"Take Control"})]})})]})]})}):null}function G$({question:e,progress:n,historyEntries:s,onSubmit:a,onBack:r}){const[o,l]=i.useState({}),[c,d]=i.useState(""),[u,m]=i.useState(""),h=i.useCallback(()=>{let p;e.type==="text"?p={[e.id]:c}:e.type==="confirm"?p={[e.id]:o[e.id]===!0}:p=o;const g=u.trim();g.length>0&&(p={...p,_comment:g}),a(p)},[u,e,o,c,a]);i.useEffect(()=>{l({}),d(""),m("")},[e.id]);const f=()=>{switch(e.type){case"text":return c.trim().length>0;case"single_select":return o[e.id]!==void 0;case"multi_select":return Array.isArray(o[e.id])&&o[e.id].length>0;case"confirm":return o[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(mi,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3].map(p=>t.jsx("div",{className:`planning-progress-step ${p<=n?"active":""}`},p))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~3"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:c,onChange:p=>d(p.target.value),onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&c.trim()&&(p.preventDefault(),h())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(p=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:p.id,checked:o[e.id]===p.id,onChange:()=>l({[e.id]:p.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(p=>{const g=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:p.id,checked:g.includes(p.id),onChange:x=>{const w=x.target.checked?[...g,p.id]:g.filter(b=>b!==p.id);l({[e.id]:w})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!0?"selected":""}`,onClick:()=>l({[e.id]:!0}),children:[t.jsx(Gn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(un,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:u,onChange:p=>m(p.target.value)})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(Ha,{size:16,className:"icon-mr-4"}),"Back"]}),t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:h,disabled:!f(),children:["Continue",t.jsx($o,{size:16,className:"icon-ml-4"})]})]})]})}function J$({summary:e,historyEntries:n,onSummaryChange:s,tasks:a,onCreateTask:r,onBreakIntoTasks:o,onRefine:l,isLoading:c}){const[d,u]=i.useState(!1),[m,h]=i.useState(e.suggestedDependencies),f=Ba(e.priority),p=g=>{const x=m.includes(g)?m.filter(w=>w!==g):[...m,g];h(x),s({...e,suggestedDependencies:x})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(di,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(mi,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Gn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Planning Complete!"}),t.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{children:["Description",t.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>u(!d),children:d?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${d?"expanded":""}`,rows:d?10:4,value:e.description,onChange:g=>s({...e,description:g.target.value})})]}),t.jsxs("div",{className:"planning-summary-meta-row",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planning-summary-size",children:"Suggested Size"}),t.jsxs("select",{id:"planning-summary-size",className:"planning-size-select",value:e.suggestedSize,onChange:g=>s({...e,suggestedSize:g.target.value}),disabled:c,children:[t.jsx("option",{value:"S",children:"S (Small)"}),t.jsx("option",{value:"M",children:"M (Medium)"}),t.jsx("option",{value:"L",children:"L (Large)"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planning-summary-priority",children:"Priority"}),t.jsx("select",{id:"planning-summary-priority",className:"planning-size-select",value:f,onChange:g=>s({...e,priority:g.target.value}),disabled:c,children:pa.map(g=>t.jsx("option",{value:g,children:g[0].toUpperCase()+g.slice(1)},g))})]})]}),a.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:a.map(g=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(g.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(g.id),onChange:()=>p(g.id)}),t.jsx("span",{className:"planning-dep-id",children:g.id}),t.jsx("span",{className:"planning-dep-title",children:g.title||g.description.slice(0,30)})]},g.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((g,x)=>t.jsx("li",{children:g},x))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(Ha,{size:16,className:"icon-mr-4"}),"Refine Further"]}),t.jsxs("div",{className:"planning-summary-actions-right",children:[t.jsx("button",{className:"btn",onClick:r,disabled:c,children:c?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Gn,{size:16,className:"icon-mr-8"}),"Create Single Task"]})}),t.jsx("button",{className:"btn btn-primary",onClick:o,disabled:c,title:"Break the plan into multiple tasks with dependencies",children:c?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(hc,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})})]})]})]})}function Rf(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,a=new Set,r=o=>{if(s.has(o))return!0;if(a.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),a.add(o),!1};return e.some(o=>r(o.id))}function Y$(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",priority:Ls,dependsOn:[]}}function Q$({subtasks:e,isLoading:n,onUpdateSubtasks:s,onCreateTasks:a,onBack:r}){const[o,l]=i.useState(null),[c,d]=i.useState(null),[u,m]=i.useState(null),h=i.useRef([]),f=i.useMemo(()=>e.length===0||e.some(v=>!v.title.trim())?!0:Rf(e),[e]),p=i.useCallback((v,N)=>{s(e.map(I=>I.id===v?{...I,...N}:I))},[e,s]),g=i.useCallback(()=>{s([...e,Y$(e.length+1)])},[e,s]),x=i.useCallback(v=>{s(e.filter(N=>N.id!==v).map(N=>({...N,dependsOn:N.dependsOn.filter(I=>I!==v)})))},[e,s]),w=i.useCallback((v,N)=>{if(N<0||N>=e.length)return;const I=[...e],[F]=I.splice(v,1);I.splice(N,0,F),s(I)},[e,s]),b=i.useCallback(v=>N=>{l(v),N.dataTransfer.setData("text/plain",v),N.dataTransfer.effectAllowed="move"},[]),y=i.useCallback(()=>{l(null),d(null),m(null)},[]),S=i.useCallback(v=>N=>{if(N.preventDefault(),v===o)return;const I=N.currentTarget.getBoundingClientRect(),F=I.top+I.height/2,_=N.clientY<F?"before":"after";d(v),m(_)},[o]),j=i.useCallback(v=>N=>{N.preventDefault();const I=N.dataTransfer.getData("text/plain");if(!I||I===v){y();return}const F=e.findIndex(R=>R.id===I),_=e.findIndex(R=>R.id===v);if(F===-1||_===-1){y();return}const M=[...e],[z]=M.splice(F,1);let U=_;u==="after"&&F<_&&U--,u==="after"&&U++,M.splice(U,0,z),s(M),y()},[e,u,s,y]),C=i.useCallback(v=>{const N=v.currentTarget.getBoundingClientRect(),I=v.clientX,F=v.clientY;(I<N.left||I>N.right||F<N.top||F>N.bottom)&&(d(null),m(null))},[]);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(hc,{size:24,className:"icon-triage"}),t.jsx("h4",{children:"Break into Tasks"}),t.jsx("p",{className:"text-muted",children:"Review and edit the subtasks generated from your plan. Adjust titles, descriptions, sizes, priorities, and dependencies before creating."})]}),t.jsxs("div",{className:"planning-summary-form",children:[e.map((v,N)=>{const I=o===v.id,F=c===v.id,_=["task-detail-section","subtask-item",I?"subtask-item-dragging":"",F?"subtask-item-drop-target":"",F&&u==="before"?"subtask-item-drop-before":"",F&&u==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:_,"data-testid":`subtask-item-${N}`,draggable:!n,onDragStart:b(v.id),onDragEnd:y,onDragOver:S(v.id),onDrop:j(v.id),onDragLeave:C,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(mc,{size:16}),t.jsx("strong",{children:v.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>w(N,N-1),disabled:n||N===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Ta,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>w(N,N+1),disabled:n||N===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Po,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>x(v.id),disabled:n,children:[t.jsx(_n,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:M=>{h.current[N]=M},value:v.title,onChange:M=>p(v.id,{title:M.target.value}),onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),N<e.length-1&&h.current[N+1]?.focus())},disabled:n})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:v.description,onChange:M=>p(v.id,{description:M.target.value}),disabled:n})]}),t.jsxs("div",{className:"planning-summary-meta-row",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`${v.id}-size`,children:"Size"}),t.jsxs("select",{id:`${v.id}-size`,className:"planning-size-select",value:v.suggestedSize,onChange:M=>p(v.id,{suggestedSize:M.target.value}),disabled:n,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`${v.id}-priority`,children:"Priority"}),t.jsx("select",{id:`${v.id}-priority`,className:"planning-size-select",value:Ba(v.priority),onChange:M=>p(v.id,{priority:M.target.value}),disabled:n,children:pa.map(M=>t.jsx("option",{value:M,children:M[0].toUpperCase()+M.slice(1)},M))})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,N).filter(M=>M.id!==v.id).map(M=>{const z=v.dependsOn.includes(M.id);return t.jsxs("label",{className:`planning-dep-chip ${z?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:z,onChange:()=>{const U=z?v.dependsOn.filter(R=>R!==M.id):[...v.dependsOn,M.id];p(v.id,{dependsOn:U})},disabled:n}),t.jsx("span",{className:"planning-dep-id",children:M.id}),t.jsx("span",{className:"planning-dep-title",children:M.title||"Untitled"})]},M.id)}),N===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),N>0&&e.slice(0,N).filter(M=>M.id!==v.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},v.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:g,disabled:n,children:[t.jsx(Mn,{size:16,className:"icon-mr-6"})," Add subtask"]}),Rf(e)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:n,children:[t.jsx(Ha,{size:16,className:"icon-mr-4"}),"Back to Summary"]}),t.jsx("button",{className:"btn btn-primary",onClick:a,disabled:n||f,children:n?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function X$({sessions:e,loading:n,selectedSessionId:s,pendingDeleteId:a,showArchived:r,onToggleShowArchived:o,onArchive:l,onSelectSession:c,onNewSession:d,onRequestDelete:u,onConfirmDelete:m,onCancelDelete:h}){return t.jsxs("aside",{className:"planning-sidebar","aria-label":"Planning sessions",children:[t.jsx("div",{className:"planning-sidebar-header",children:t.jsxs("button",{className:`planning-sidebar-new ${s===null?"active":""}`,onClick:d,type:"button",children:[t.jsx(rk,{size:16}),t.jsx("span",{children:"New session"})]})}),t.jsxs("div",{className:"planning-sidebar-list",children:[e.length===0&&!n&&t.jsx("div",{className:"planning-sidebar-empty text-muted",children:"No saved sessions yet. Start one on the right to see it here."}),e.map(f=>{const p=f.id===s,g=a===f.id,x=f.archived===!0,w=f.status==="complete"||f.status==="error";return t.jsxs("div",{className:`planning-sidebar-item ${p?"selected":""} ${g?"pending-delete":""} ${x?"archived":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>c(f.id),children:[t.jsx(Z$,{status:f.status}),t.jsxs("span",{className:"planning-sidebar-item-body",children:[t.jsx("span",{className:"planning-sidebar-item-title",children:f.status==="draft"&&(!f.title||f.title==="New planning session")?f.preview??"New planning session":f.title||"Untitled session"}),t.jsxs("span",{className:"planning-sidebar-item-meta",children:[t.jsx(e4,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:t4(f.updatedAt)})]})]})]}),g?t.jsxs("div",{className:"planning-sidebar-confirm",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>m(f.id),children:"Delete"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,children:"Cancel"})]}):t.jsxs("div",{className:"planning-sidebar-item-actions",children:[w&&t.jsx("button",{type:"button",className:"planning-sidebar-item-archive",onClick:b=>{b.stopPropagation(),l(f.id)},"aria-label":x?"Unarchive session":"Archive session",title:x?"Unarchive session":"Archive session",children:x?t.jsx(vy,{size:14}):t.jsx(To,{size:14})}),t.jsx("button",{type:"button",className:"planning-sidebar-item-delete",onClick:b=>{b.stopPropagation(),u(f.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(_n,{size:14})})]})]},f.id)})]}),t.jsx("div",{className:"planning-sidebar-footer",children:t.jsx("a",{href:"#",className:"planning-sidebar-toggle-archived-link",onClick:f=>{f.preventDefault(),o()},"aria-pressed":r,children:r?"Hide archived":"Show archived"})})]})}function Z$({status:e}){switch(e){case"generating":return t.jsx(jt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(Jd,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(Gn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(Ws,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(Ji,{size:14,className:"planning-sidebar-status-icon"})}}function e4({status:e}){switch(e){case"generating":return t.jsx("span",{children:"Generating"});case"awaiting_input":return t.jsx("span",{children:"Needs input"});case"complete":return t.jsx("span",{children:"Complete"});case"error":return t.jsx("span",{children:"Error"});default:return t.jsx("span",{children:e})}}function t4(e){const n=Date.now()-Date.parse(e);if(!Number.isFinite(n)||n<0)return"";const s=Math.floor(n/1e3);if(s<60)return"just now";const a=Math.floor(s/60);if(a<60)return`${a}m ago`;const r=Math.floor(a/60);if(r<24)return`${r}h ago`;const o=Math.floor(r/24);if(o<7)return`${o}d ago`;const l=Math.floor(o/7);return l<4?`${l}w ago`:new Date(e).toLocaleDateString()}function n4(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function If(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,a=new Set,r=o=>{if(s.has(o))return!0;if(a.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),a.add(o),!1};return e.some(o=>r(o.id))}function s4({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:a,parentTaskId:r,projectId:o,resumeSessionId:l}){const c=ri();Ni(e);const{keyboardOverlap:d,viewportHeight:u,viewportOffsetTop:m,keyboardOpen:h}=Zi({enabled:c==="mobile"}),f=h?{"--keyboard-overlap":`${d}px`,"--vv-offset-top":`${m}px`,...u!==null?{"--vv-height":`${u}px`}:{}}:{},[p,g]=i.useState({type:"initial"}),[x,w]=i.useState([]),[b,y]=i.useState([]),[S,j]=i.useState(""),[C,v]=i.useState(!0),[N,I]=i.useState(!1),[F,_]=i.useState(!1),[M,z]=i.useState(s),[U,R]=i.useState(null),[D,K]=i.useState(!1),[Z,ne]=i.useState("project-default"),[O,A]=i.useState(""),[P,$]=i.useState(""),[k,J]=i.useState("shared"),[ce,je]=i.useState(null),[He,xe]=i.useState(null),[Ne,Y]=i.useState(null),ie=i.useRef(null),ee=i.useRef([]),oe=i.useRef(!1),W=i.useRef(null),L=p.type==="generating"||p.type==="editing"||p.type==="creating"||p.type==="error"?p.sessionId:null,pe=i.useMemo(()=>Va(),[]),{isLockedByOther:fe,takeControl:B,isLoading:ve}=Ec(e?L:null),{activeTabMap:Fe,broadcastUpdate:ae,broadcastCompleted:qe,broadcastLock:Pe,broadcastUnlock:nt,broadcastHeartbeat:Be}=Fr(),de=i.useMemo(()=>x.length===0||x.some(Re=>!Re.title.trim())||(Z==="existing"||Z==="custom-new")&&!O.trim()?!0:If(x),[Z,O,x]),Ie=p.type==="generating"||p.type==="editing"||p.type==="error",$e=L?Fe.get(L):null,{confirm:st}=pi(),Ue=$e&&$e.tabId!==pe,me=!!(Ue&&!$e.stale),re=fe&&(!Ue||$e.stale),_e=i.useCallback(()=>{M&&JP(M,o),ie.current?.close(),ie.current=null,g({type:"initial"}),w([]),y([]),j(""),v(!0),I(!1),_(!1),R(null),K(!1),ne("project-default"),A(""),$(""),J("shared"),oe.current=!1},[M,o]),xt=i.useCallback(()=>{ie.current?.close(),ie.current=null,n()},[n]),ut=i.useCallback(async()=>{if(!((D||p.type==="editing"||p.type==="creating")&&!await st({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(L)try{await ub(L,o,pe)}catch{}_e(),n()}},[D,n,_e,L,pe,p.type,o,st]),Qe=i.useCallback(Re=>{ie.current?.close(),ie.current=HS(Re,o,{onThinking:be=>{j(rt=>rt+be),ae({sessionId:Re,status:"generating",needsInput:!1,owningTabId:pe,type:"subtask",title:M.trim()||void 0,projectId:o??null})},onSubtasks:be=>{I(!1),_(!1),Sd(o),w(be),g({type:"editing",sessionId:Re}),K(!1),ae({sessionId:Re,status:"awaiting_input",needsInput:!0,owningTabId:pe,type:"subtask",title:M.trim()||void 0,projectId:o??null})},onError:be=>{const rt=be||"Session failed while contacting the AI.";I(!1),_(!1),R(null),g({type:"error",sessionId:Re,errorMessage:rt}),ae({sessionId:Re,status:"error",needsInput:!1,owningTabId:pe,type:"subtask",title:M.trim()||void 0,projectId:o??null}),qe({sessionId:Re,status:"error"})},onComplete:()=>{qe({sessionId:Re,status:"complete"})},onConnectionStateChange:be=>{I(be==="reconnecting")}})},[qe,ae,M,o,pe]),vt=i.useCallback(async()=>{if(M.trim()){R(null),y([]),j(""),I(!1);try{const{sessionId:Re}=await zS(M.trim(),o);g({type:"generating",sessionId:Re}),Qe(Re)}catch(Re){R(Ee(Re)||"Failed to start subtask breakdown"),g({type:"initial"})}}},[Qe,M,o]);i.useEffect(()=>{if(!e){_e();return}if(e&&s&&!oe.current)z(s),oe.current=!0,vt();else if(e&&!s&&!oe.current){const Re=YP(o);Re&&z(Re)}},[e,s,vt,_e]),i.useEffect(()=>{!e||!l||p.type!=="initial"||(async()=>{try{const Re=await Ti(l);if(!Re)return;const be=jr(Re.conversationHistory);if(y(be),Re.status==="generating"||Re.status==="awaiting_input")j(Re.thinkingOutput??""),g({type:"generating",sessionId:l}),Qe(l);else if(Re.status==="complete"&&Re.result){Sd(o);const rt=JSON.parse(Re.result);w(rt),g({type:"editing",sessionId:l})}else Re.status==="error"&&(R(null),g({type:"error",sessionId:l,errorMessage:Re.error??"Session encountered an error"}))}catch(Re){R(Ee(Re)||"Failed to resume session")}})()},[Qe,e,l,p.type,o]),i.useEffect(()=>{if(!e){W.current&&(nt(W.current,pe),W.current=null);return}if(L&&W.current!==L){W.current&&nt(W.current,pe),Pe(L,pe),W.current=L;return}!L&&W.current&&(nt(W.current,pe),W.current=null)},[Pe,nt,e,L,pe]),i.useEffect(()=>{if(!e||!L||W.current!==L)return;Be(pe);const Re=setInterval(()=>{Be(pe)},3e4);return()=>{clearInterval(Re)}},[Be,e,L,pe]),i.useEffect(()=>()=>{ie.current?.close(),W.current&&(nt(W.current,pe),W.current=null)},[nt,pe]),i.useEffect(()=>{if(!e)return;const Re=be=>{be.key==="Escape"&&(be.preventDefault(),ut())};return document.addEventListener("keydown",Re),()=>document.removeEventListener("keydown",Re)},[e,ut]);const Ae=i.useCallback((Re,be)=>{w(rt=>rt.map(lt=>lt.id===Re?{...lt,...be}:lt)),K(!0)},[]),Je=i.useCallback(()=>{w(Re=>[...Re,n4(Re.length+1)]),K(!0)},[]),dt=i.useCallback(Re=>{w(be=>be.filter(rt=>rt.id!==Re).map(rt=>({...rt,dependsOn:rt.dependsOn.filter(lt=>lt!==Re)}))),K(!0)},[]),Nt=i.useCallback(Re=>be=>{je(Re),be.dataTransfer.setData("text/plain",Re),be.dataTransfer.effectAllowed="move"},[]),yt=i.useCallback(()=>{je(null),xe(null),Y(null)},[]),Se=i.useCallback(Re=>be=>{if(be.preventDefault(),Re===ce)return;const rt=be.currentTarget.getBoundingClientRect(),lt=rt.top+rt.height/2,gt=be.clientY<lt?"before":"after";xe(Re),Y(gt)},[ce]),G=i.useCallback(Re=>be=>{be.preventDefault();const rt=be.dataTransfer.getData("text/plain");if(!rt||rt===Re){je(null),xe(null),Y(null);return}w(lt=>{const gt=lt.findIndex(mn=>mn.id===rt),St=lt.findIndex(mn=>mn.id===Re);if(gt===-1||St===-1)return lt;const Lt=[...lt],[Yt]=Lt.splice(gt,1);let tn=St;return Ne==="after"&&gt<St&&tn--,Ne==="after"&&tn++,Lt.splice(tn,0,Yt),Lt}),K(!0),je(null),xe(null),Y(null)},[Ne]),ge=i.useCallback(Re=>{const be=Re.currentTarget.getBoundingClientRect(),rt=Re.clientX,lt=Re.clientY;(rt<be.left||rt>be.right||lt<be.top||lt>be.bottom)&&(xe(null),Y(null))},[]),pt=i.useCallback((Re,be)=>{be<0||be>=x.length||(w(rt=>{const lt=[...rt],[gt]=lt.splice(Re,1);return lt.splice(be,0,gt),lt}),K(!0))},[x.length]),ke=i.useCallback(Re=>{ee.current[Re+1]?.focus()},[]),tt=i.useCallback(async()=>{if(!(!L||de)){R(null),g({type:"creating",sessionId:L});try{const Re=await qS(L,x,r,o,{branchSelection:{mode:Z,...Z==="existing"||Z==="custom-new"?{branchName:O}:{},...P.trim()?{baseBranch:P.trim()}:{}},branchAssignment:{mode:k}});a(Re.tasks),_e(),n()}catch(Re){R(Ee(Re)||"Failed to create tasks"),g({type:"editing",sessionId:L})}}},[P,k,Z,O,de,n,a,r,o,_e,L,x]),Rt=i.useCallback(async()=>{if(p.type!=="error")return;const Re=p.sessionId;R(null),_(!0),j(""),g({type:"generating",sessionId:Re}),Qe(Re);try{await BS(Re,o,pe)}catch(be){let rt=be;if((Ee(be)||"").includes("not in an error state"))try{const gt=await Ti(Re);if(!gt)throw new Error("Failed to refresh subtask session.");if(y(jr(gt.conversationHistory)),gt.status==="generating"||gt.status==="awaiting_input")j(gt.thinkingOutput??""),g({type:"generating",sessionId:gt.id}),ie.current?.isConnected()||Qe(gt.id);else if(gt.status==="complete"){if(!gt.result)throw new Error("Subtask session is complete but has no result.");Sd(o);const St=JSON.parse(gt.result);w(St),g({type:"editing",sessionId:gt.id}),K(!1)}else gt.status==="error"&&g({type:"error",sessionId:gt.id,errorMessage:gt.error??"Retry failed. Please try again."});I(!1);return}catch(gt){rt=gt}ie.current?.close(),ie.current=null,g({type:"error",sessionId:Re,errorMessage:Ee(rt)||"Retry failed. Please try again."}),I(!1)}finally{_(!1)}},[Qe,o,pe,p]);return e?t.jsx("div",{className:"modal-overlay open",onClick:Re=>Re.target===Re.currentTarget&&void ut(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",style:f,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(hc,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Ie&&t.jsx("button",{className:"modal-send-to-background",onClick:xt,title:"Send to background","aria-label":"Send to background",children:t.jsx(Lo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void ut(),"aria-label":"Close",children:t.jsx(un,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[U&&t.jsx("div",{className:"form-error planning-error",children:U}),N&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),me&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),p.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:M})]})}),p.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(mi,{entries:b,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>v(!C),type:"button",children:C?"Hide thinking":"Show thinking"}),C&&S&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:S})})]})]}),p.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(mi,{entries:b,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:p.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void Rt(),disabled:F,children:[F?t.jsx(jt,{size:14,className:"spin"}):t.jsx(bs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:F?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void ut(),disabled:F,children:"Cancel"})]})]})]})}),(p.type==="editing"||p.type==="creating")&&t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(mi,{entries:b}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Gn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"task-detail-section",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch strategy"}),t.jsxs("select",{value:Z,onChange:Re=>ne(Re.target.value),disabled:p.type==="creating",children:[t.jsx("option",{value:"project-default",children:"Use project/default branch"}),t.jsx("option",{value:"auto-new",children:"Create auto-named branch per task"}),t.jsx("option",{value:"existing",children:"Use existing branch"}),t.jsx("option",{value:"custom-new",children:"Create custom new branch"})]})]}),(Z==="existing"||Z==="custom-new")&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch name"}),t.jsx("input",{value:O,onChange:Re=>A(Re.target.value),disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Merge target / base branch (optional)"}),t.jsx("input",{value:P,onChange:Re=>$(Re.target.value),disabled:p.type==="creating",placeholder:"main"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Planning branch mode"}),t.jsxs("select",{value:k,onChange:Re=>J(Re.target.value),disabled:p.type==="creating",children:[t.jsx("option",{value:"shared",children:"Shared branch for all subtasks"}),t.jsx("option",{value:"per-task-derived",children:"Per-task branch derived from planning branch"})]})]})]}),x.map((Re,be)=>{const rt=ce===Re.id,lt=He===Re.id,gt=["task-detail-section","subtask-item",rt?"subtask-item-dragging":"",lt?"subtask-item-drop-target":"",lt&&Ne==="before"?"subtask-item-drop-before":"",lt&&Ne==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:gt,"data-testid":`subtask-item-${be}`,draggable:p.type!=="creating",onDragStart:Nt(Re.id),onDragEnd:yt,onDragOver:Se(Re.id),onDrop:G(Re.id),onDragLeave:ge,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(mc,{size:16}),t.jsx("strong",{children:Re.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>pt(be,be-1),disabled:p.type==="creating"||be===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Ta,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>pt(be,be+1),disabled:p.type==="creating"||be===x.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Po,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>dt(Re.id),disabled:p.type==="creating",children:[t.jsx(_n,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:St=>{ee.current[be]=St},value:Re.title,onChange:St=>Ae(Re.id,{title:St.target.value}),onKeyDown:St=>{St.key==="Enter"&&(St.preventDefault(),ke(be))},disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:Re.description,onChange:St=>Ae(Re.id,{description:St.target.value}),disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:Re.suggestedSize,onChange:St=>Ae(Re.id,{suggestedSize:St.target.value}),disabled:p.type==="creating",children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[x.slice(0,be).filter(St=>St.id!==Re.id).map(St=>{const Lt=Re.dependsOn.includes(St.id);return t.jsxs("label",{className:`planning-dep-chip ${Lt?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:Lt,onChange:()=>{const Yt=Lt?Re.dependsOn.filter(tn=>tn!==St.id):[...Re.dependsOn,St.id];Ae(Re.id,{dependsOn:Yt})},disabled:p.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:St.id}),t.jsx("span",{className:"planning-dep-title",children:St.title||"Untitled"})]},St.id)}),be===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),be>0&&x.slice(0,be).filter(St=>St.id!==Re.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},Re.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:Je,disabled:p.type==="creating",children:[t.jsx(Mn,{size:16,className:"icon-mr-6"})," Add subtask"]}),If(x)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsx("button",{className:"btn",onClick:()=>void ut(),disabled:p.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void tt(),disabled:p.type==="creating"||de,children:p.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),fe&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(pc,{size:16}),t.jsx("span",{children:re?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),re&&t.jsx("button",{type:"button",onClick:()=>{B()},disabled:ve,className:"btn btn-primary session-lock-take-control",children:ve?"Taking control...":"Take Control"})]})})]})]})}):null}const i4=5,a4=1e3,r4=45e3;function Sl(){return{scrollback:null,connected:null,data:[]}}function o4(e,n){const[s,a]=i.useState("disconnected"),r=i.useRef(0),o=i.useRef(e),l=i.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const d=i.useRef(null),u=i.useRef(0),m=i.useRef(null),h=i.useRef(null),f=i.useRef(!1),p=i.useRef(new Set),g=i.useRef(new Set),x=i.useRef(new Set),w=i.useRef(new Set),b=i.useRef(new Set),y=i.useRef(Sl()),S=i.useCallback(R=>{p.current.add(R);const D=y.current;return D.data.length>0&&(D.data.forEach(K=>R(K)),D.data=[]),()=>p.current.delete(R)},[]),j=i.useCallback(R=>(g.current.add(R),()=>g.current.delete(R)),[]),C=i.useCallback(R=>{x.current.add(R);const D=y.current;return D.connected&&(R(D.connected),D.connected=null),()=>x.current.delete(R)},[]),v=i.useCallback(R=>{w.current.add(R);const D=y.current;return D.scrollback&&(R(D.scrollback),D.scrollback=null),()=>w.current.delete(R)},[]),N=i.useCallback(R=>(b.current.add(R),()=>b.current.delete(R)),[]),I=i.useCallback(R=>{const D=d.current;D?.readyState===WebSocket.OPEN&&D.send(JSON.stringify({type:"input",data:R}))},[]),F=i.useCallback((R,D)=>{const K=d.current;K?.readyState===WebSocket.OPEN&&K.send(JSON.stringify({type:"resize",cols:R,rows:D}))},[]),_=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),d.current&&(d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),y.current=Sl()},[]),M=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),d.current&&(f.current=!0,d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),y.current=Sl()},[]),z=i.useCallback(()=>{if(!e){a("disconnected");return}if(d.current?.readyState===WebSocket.OPEN)return;d.current&&(f.current=!0,d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),f.current=!1,a("connecting");const R=r.current;let K=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(K+=`&projectId=${encodeURIComponent(n)}`);const Z=new WebSocket(Di(K));d.current=Z,Z.onopen=()=>{if(r.current!==R){Z.close();return}y.current=Sl(),a("connected"),u.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===R&&Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"ping"}))},r4)},Z.onmessage=ne=>{if(r.current===R)try{const O=JSON.parse(ne.data),A=y.current;switch(O.type){case"data":O.data&&(p.current.size===0&&A.data.push(O.data),p.current.forEach(P=>P(O.data)));break;case"scrollback":O.data&&(A.scrollback=O.data,w.current.forEach(P=>P(O.data)));break;case"connected":O.shell&&O.cwd&&(A.connected={shell:O.shell,cwd:O.cwd},x.current.forEach(P=>P({shell:O.shell,cwd:O.cwd})));break;case"exit":O.exitCode!==void 0&&g.current.forEach(P=>P(O.exitCode));break;case"ping":Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},Z.onclose=ne=>{if(r.current!==R)return;if(d.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){a("disconnected");return}if(ne.code===4e3||ne.code===4004){a("disconnected"),ne.code===4004&&b.current.forEach(P=>P());return}if(u.current++,u.current>i4){a("disconnected");return}const O=a4*Math.pow(2,u.current-1);a("reconnecting");const A=r.current;m.current=setTimeout(()=>{r.current===A&&(f.current||z())},Math.min(O,16e3))},Z.onerror=()=>{}},[e,n]),U=i.useCallback(()=>{u.current=0,M(),z()},[M,z]);return i.useEffect(()=>(c&&(_(),u.current=0,a("disconnected")),e?z():a("disconnected"),M),[e,n,c,z,M,_]),{connectionStatus:s,sendInput:I,resize:F,onData:S,onExit:j,onConnect:C,onScrollback:v,reconnect:U,onSessionInvalid:N}}const bv="kb-terminal-tabs",l4=15e3,c4=15e3;function Tf(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function Pf(e){if(typeof window>"u")return[];try{const n=zn(bv,e);if(n)return JSON.parse(n)}catch{}return[]}function Pd(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function $f(e,n,s){let a;const r=new Promise((o,l)=>{a=setTimeout(()=>l(new Error(`${s} timed out after ${n}ms`)),n)});return Promise.race([e,r]).finally(()=>clearTimeout(a))}function d4(e){const[n,s]=i.useState(()=>Pf(e)),[a,r]=i.useState(!1),[o,l]=i.useState(!0),[c,d]=i.useState(null),[u,m]=i.useState(0),h=i.useRef(0);i.useEffect(()=>{h.current+=1,s(Pf(e)),r(!1),l(!0),d(null)},[e]),i.useEffect(()=>{try{us(bv,JSON.stringify(n),e)}catch{}},[e,n]),i.useEffect(()=>{let C=!1;const v=h.current;return(async()=>{if(!C)try{const I=await $f(TN(e),l4,"listTerminalSessions");if(C||v!==h.current)return;const F=new Set(I.map(_=>_.id));l(!0),s(_=>{if(C||v!==h.current)return _;const z=_.map(D=>({...D,_verified:F.has(D.sessionId)})).filter(D=>D._verified);if(z.length===0)return[];const U=z.map(({_verified:D,...K})=>K);return U.find(D=>D.isActive)?U:U.map((D,K)=>({...D,isActive:K===0}))}),r(!0)}catch(I){if(C||v!==h.current)return;const F=Pd(I);F||console.warn("Failed to validate terminal sessions with server:",I),l(!F),r(!0)}})(),()=>{C=!0}},[e]),i.useEffect(()=>{if(n.length===0&&a&&o){const C=h.current,v=setTimeout(()=>{$f(Zo(void 0,void 0,void 0,e),c4,"createTerminalSession").then(N=>{if(C!==h.current)return;const I={id:Tf(),sessionId:N.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(F=>F.length>0?F:[...F.map(M=>({...M,isActive:!1})),I]),d(null)}).catch(N=>{if(C!==h.current)return;Pd(N)||console.error(N);const I=N instanceof Error?N.message:typeof N=="string"?N:"Failed to create terminal session";d(I)})},0);return()=>clearTimeout(v)}},[a,o,n.length,u]);const f=i.useCallback(async()=>{const C=await Zo(void 0,void 0,void 0,e),v={id:Tf(),sessionId:C.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(N=>[...N.map(F=>({...F,isActive:!1})),v]),v},[n.length]),p=i.useCallback(async()=>f(),[f]),g=i.useCallback(C=>{s(v=>{const N=v.find(M=>M.id===C);if(!N)return v;zm(N.sessionId,e).catch(M=>{console.warn(`Failed to kill terminal session ${N.sessionId}:`,M)});const I=v.findIndex(M=>M.id===C),F=N.isActive,_=v.filter(M=>M.id!==C);if(_.length===0)return[];if(F){const M=Math.min(I,_.length-1);return _.map((z,U)=>({...z,isActive:U===M}))}return _})},[]),x=i.useCallback(C=>{s(v=>{let N=!1;const I=v.map(F=>F.id===C?(N=!0,{...F,isActive:!0}):{...F,isActive:!1});return N?I:v})},[]),w=i.useCallback((C,v)=>{s(N=>N.map(I=>I.id===C?{...I,title:v}:I))},[]),b=i.useCallback(async()=>{s(N=>{const I=N.find(F=>F.isActive);return I&&zm(I.sessionId,e).catch(F=>{console.warn(`Failed to kill old session ${I.sessionId}:`,F)}),N});const C=n.find(N=>N.isActive);if(!C)return;const v=await Zo(void 0,void 0,void 0,e);s(N=>N.map(I=>I.id===C.id?{...I,sessionId:v.sessionId}:I))},[n]),y=i.useCallback(async()=>{const C=n.find(v=>v.isActive);if(C)try{const v=await Zo(void 0,void 0,void 0,e);s(N=>N.map(I=>I.id===C.id?{...I,sessionId:v.sessionId}:I)),d(null)}catch(v){Pd(v)||console.error(v);const N=v instanceof Error?v.message:typeof v=="string"?v:"Failed to create terminal session";d(N)}},[n]),S=n.find(C=>C.isActive)??null,j=i.useCallback(()=>{d(null),h.current+=1,m(C=>C+1)},[]);return{tabs:n,activeTab:S,isReady:a,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:x,updateTabTitle:w,restartActiveTab:b,retryBootstrap:j,replaceActiveTabSession:y}}const u4=1e4,m4=[500,1500,3e3],xv="kb-terminal-font-size",go=14,h4=8,p4=32,f4='"Fusion Terminal Nerd Font Symbols", "MesloLGS NF", "MesloLGM Nerd Font", "JetBrainsMono Nerd Font", "FiraCode Nerd Font", "Hack Nerd Font", ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace';function g4(e){if(!e)return"";const n=e.slice(0,1).toUpperCase();return n==="["?"\x1B":n>="A"&&n<="Z"?String.fromCharCode(n.charCodeAt(0)-64):e}function b4(e){return`\x1B${e}`}const x4=[{label:"C",key:"c",description:"SigInt"},{label:"D",key:"d",description:"EOF"},{label:"Z",key:"z",description:"Suspend"},{label:"L",key:"l",description:"Clear"},{label:"R",key:"r",description:"Reverse search"},{label:"A",key:"a",description:"Home"},{label:"E",key:"e",description:"End"},{label:"U",key:"u",description:"Kill line"},{label:"K",key:"k",description:"Kill to EOL"},{label:"W",key:"w",description:"Del word"},{label:".",key:".",description:"Last argument"}];function bo(e){return Math.min(p4,Math.max(h4,e))}function v4(){if(typeof window>"u")return go;try{const e=window.localStorage.getItem(xv);if(!e)return go;const n=Number.parseInt(e,10);return Number.isFinite(n)?bo(n):go}catch{return go}}function y4(e){const n=typeof e=="string"?e:e instanceof Error?e.message:String(e);return n.includes("MIME type")||n.includes("Failed to fetch dynamically imported module")}function w4(e){return new Promise(n=>setTimeout(n,e))}async function k4(e,n=m4){let s;for(let a=0;a<=n.length;a+=1)try{return await e()}catch(r){if(!y4(r))throw r;s===void 0&&(s=r);const o=n[a];if(o===void 0)throw s??r;const l=r instanceof Error?r.message:String(r);console.warn(`[TerminalModal] Dynamic xterm import failed (attempt ${a+1}/${n.length+1}). Retrying in ${o}ms...`,l),await w4(o)}throw s??new Error("Dynamic import failed")}function Df(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function j4(){if(typeof window>"u"||!window.visualViewport)return 0;const e=window.visualViewport,n=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(n>0)return n;const a=N4()-e.offsetTop-e.height;return a>=30&&a>80?a:0}let $d=null;function N4(){return $d===null&&($d=window.innerHeight),$d}function S4({isOpen:e,onClose:n,initialCommand:s,projectId:a}){const[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1),[m,h]=i.useState(null),[f,p]=i.useState(0),[g,x]=i.useState(0),[w,b]=i.useState(null),[y,S]=i.useState(()=>v4()),[j,C]=i.useState(!1),[v,N]=i.useState(null),I=i.useRef(null),F=i.useRef(null),_=i.useRef(!1);Li(F,e,"fusion:terminal-modal-size");const M=i.useRef(null),z=i.useRef(null),U=i.useRef(!1),R=i.useRef(!1),D=i.useRef(null),K=i.useRef(()=>{}),Z=i.useRef(null),ne=i.useRef(0),O=i.useRef(y),A=i.useRef(null),P=i.useRef(a);ne.current=g,O.current=y;const $=i.useCallback(Ae=>{if(Ae&&R.current!==Ae)return;const Je=z.current,dt=M.current,Nt=D.current;if(!(!Je||!dt)&&!(Ae&&R.current!==Ae))try{Je.fit(),Nt&&Nt(dt.cols,dt.rows)}catch{}},[]);i.useEffect(()=>{e&&p(Ae=>Ae+1)},[e]),i.useEffect(()=>{if(!e||!Df())return;const Ae=window.visualViewport;if(!Ae)return;const Je=()=>{const dt=j4();x(dt),b(Ae.height),dt>0&&F.current?.scrollIntoView&&F.current.scrollIntoView({block:"end",behavior:"smooth"}),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null);const Nt=typeof R.current=="string"?R.current:void 0;A.current=requestAnimationFrame(()=>{A.current=null,$(Nt)})};return Je(),Ae.addEventListener("resize",Je),Ae.addEventListener("scroll",Je),()=>{Ae.removeEventListener("resize",Je),Ae.removeEventListener("scroll",Je),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),x(0),b(null)}},[$,e]),i.useEffect(()=>{if(!e)return;const Ae=F.current;if(!Ae||typeof ResizeObserver>"u")return;let Je=null;const dt=new ResizeObserver(()=>{Je!==null&&cancelAnimationFrame(Je),Je=requestAnimationFrame(()=>{Je=null;const Nt=typeof R.current=="string"?R.current:void 0;$(Nt)})});return dt.observe(Ae),()=>{dt.disconnect(),Je!==null&&cancelAnimationFrame(Je)}},[$,e]);const{tabs:k,activeTab:J,isReady:ce,bootstrapError:je,createTab:He,closeTab:xe,setActiveTab:Ne,updateTabTitle:Y,restartActiveTab:ie,retryBootstrap:ee,replaceActiveTabSession:oe}=d4(a),{connectionStatus:W,sendInput:L,resize:pe,onData:fe,onConnect:B,onExit:ve,onScrollback:Fe,reconnect:ae,onSessionInvalid:qe}=o4(J?.sessionId??null,a);D.current=pe,K.current=L,i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(xv,String(y))}catch{}},[y]);const Pe=i.useCallback(()=>{const Ae=M.current;if(Ae)try{z.current?.fit(),pe(Ae.cols,Ae.rows)}catch{}},[pe]);i.useEffect(()=>{if(!e||!ce)return;const Ae=J?.sessionId;if(!Ae)return;const Je=P.current!==a;if(Je&&(P.current=a),R.current===Ae&&M.current&&!Je)return;M.current&&(R.current!==Ae||Je)&&(M.current.dispose(),M.current=null,z.current=null,R.current=!1,Z.current&&(window.removeEventListener("resize",Z.current),Z.current=null),u(!1),h(null));let dt=!0,Nt;return(async()=>{const Se=k4(()=>Promise.all([Sn(()=>import("./vendor-xterm-DzcZoU0P.js").then(ke=>ke.x),__vite__mapDeps([5,1,6])),Sn(()=>import("./addon-fit-C7jRorKK.js").then(ke=>ke.a),__vite__mapDeps([8,1])),Sn(()=>import("./addon-web-links-CkJwd4cQ.js").then(ke=>ke.a),__vite__mapDeps([9,1]))])),G=new Promise((ke,tt)=>{Nt=setTimeout(()=>{tt(new Error("xterm initialization timed out"))},u4)});let ge,pt;try{const[{Terminal:ke},{FitAddon:tt},{WebLinksAddon:Rt}]=await Promise.race([Se,G]);if(!dt||!I.current||M.current)return;ge=new ke({cursorBlink:!0,cursorStyle:"block",fontSize:O.current,fontFamily:f4,theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78",black:"#1e1e1e",red:"#f48771",green:"#4ec9b0",yellow:"#dcdcaa",blue:"#569cd6",magenta:"#c586c0",cyan:"#9cdcfe",white:"#d4d4d4"},allowProposedApi:!0,scrollback:5e3}),pt=new tt,ge.loadAddon(pt);const Re=new Rt;if(ge.loadAddon(Re),!Df())try{const{WebglAddon:lt}=await Sn(async()=>{const{WebglAddon:St}=await import("./addon-webgl-BjvOw43o.js").then(Lt=>Lt.a);return{WebglAddon:St}},__vite__mapDeps([10,1])),gt=new lt;gt.onContextLoss(()=>{gt.dispose()}),ge.loadAddon(gt)}catch{}ge.open(I.current),Nt&&clearTimeout(Nt);const be=I.current?.querySelector(".xterm-helper-textarea");if(be&&be.focus(),I.current)try{I.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{pt.fit();const lt=I.current?.querySelector(".xterm-helper-textarea");lt&&lt.focus()},50),M.current=ge,z.current=pt,R.current=Ae,ne.current>0&&(A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),A.current=requestAnimationFrame(()=>{A.current=null,$(Ae)})),ge.onData(lt=>{R.current===Ae&&K.current(lt)});const rt=()=>{if(R.current===Ae&&z.current&&M.current)try{z.current.fit();const{cols:lt,rows:gt}=M.current;D.current?.(lt,gt)}catch{}};window.addEventListener("resize",rt),Z.current&&window.removeEventListener("resize",Z.current),Z.current=rt,u(!0),h(null)}catch(ke){if(Nt&&clearTimeout(Nt),!dt)return;const tt=ke instanceof Error?ke.message:"xterm initialization failed";h(tt)}})(),()=>{dt=!1,Nt&&clearTimeout(Nt)}},[$,e,ce,J?.sessionId,a]),i.useEffect(()=>{e||(M.current&&(M.current.dispose(),M.current=null),z.current=null,R.current=!1,Z.current&&(window.removeEventListener("resize",Z.current),Z.current=null),u(!1),h(null),U.current=!1,o(null),c(null),C(!1),N(null))},[e]),i.useEffect(()=>{if(!d||!M.current||!J)return;const Ae=J.sessionId,Je=G=>{R.current===Ae&&M.current?.write(G)},dt=fe(G=>{Je(G)}),Nt=Fe(G=>{Je(G)}),yt=B(G=>{Y(J.id,Hu(G.shell)||G.shell)}),Se=ve(G=>{R.current===Ae&&(c(G),M.current?.write(`\r
687
+ \x1B[33m[Process exited with code ${G}]\x1B[0m\r
688
+ `))});return()=>{dt(),Nt(),yt(),Se()}},[d,J?.sessionId,J?.id,J,W,fe,Fe,B,ve,Y]),i.useEffect(()=>{W==="connected"&&s&&U.current!==s&&J&&(U.current=s,setTimeout(()=>{L(s+`
689
+ `)},500))},[W,s,L,J,f]),i.useEffect(()=>{if(!d||!M.current)return;M.current.options.fontSize=y,A.current!==null&&(cancelAnimationFrame(A.current),A.current=null);const Ae=requestAnimationFrame(()=>{A.current=null,Pe()});return A.current=Ae,()=>{A.current===Ae&&(cancelAnimationFrame(Ae),A.current=null)}},[y,d,Pe]),i.useEffect(()=>{if(!e)return;const Ae=Je=>{if(!(!Je.ctrlKey&&!Je.metaKey)){if(Je.code==="Equal"||Je.code==="NumpadAdd"){Je.preventDefault(),S(dt=>bo(dt+1));return}if(Je.code==="Minus"||Je.code==="NumpadSubtract"){Je.preventDefault(),S(dt=>bo(dt-1));return}if(Je.code==="Digit0"||Je.code==="Numpad0"){Je.preventDefault(),S(go);return}}};return window.addEventListener("keydown",Ae),()=>window.removeEventListener("keydown",Ae)},[e,Pe]),i.useEffect(()=>{if(!e)return;const Ae=Je=>{Je.key==="Escape"&&n()};return document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)},[e,n]),i.useEffect(()=>{W==="connected"&&M.current&&setTimeout(()=>{if(!M.current||!I.current)return;const Ae=I.current.querySelector(".xterm-helper-textarea");Ae&&Ae.focus();try{I.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[W]);const nt=i.useCallback(()=>{if(!I.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;M.current?.focus();const Je=I.current.querySelector(".xterm-helper-textarea");if(!Je)return;Je.autocapitalize="off",Je.autocomplete="off",Je.autocorrect="off",Je.spellcheck=!1,Je.setAttribute("inputmode","text");try{Je.focus({preventScroll:!0})}catch{Je.focus()}const dt=Je.value.length;Je.setSelectionRange(dt,dt)},[]);i.useEffect(()=>qe(()=>{M.current?.clear(),c(null),U.current=!1,M.current&&(M.current.dispose(),M.current=null),z.current=null,R.current=!1,Z.current&&(window.removeEventListener("resize",Z.current),Z.current=null),u(!1),h(null),oe().catch(Je=>{console.error("Failed to replace invalid terminal session:",Je)})}),[qe,oe]);const Be=i.useCallback(Ae=>{Ae.target===Ae.currentTarget&&(_.current=!0)},[]),de=i.useCallback(Ae=>{_.current&&Ae.target===Ae.currentTarget&&n(),_.current=!1},[n]),Ie=i.useCallback(()=>{M.current?.clear()},[]),$e=i.useCallback(async()=>{M.current?.clear(),c(null),U.current=!1;try{await ie()}catch(Ae){o(Ee(Ae)||"Failed to restart terminal session")}},[ie]),st=i.useCallback(()=>{M.current&&(M.current.dispose(),M.current=null),z.current=null,R.current=!1,Z.current&&(window.removeEventListener("resize",Z.current),Z.current=null),h(null),u(!1)},[]),Ue=i.useCallback(()=>{window.location.reload()},[]),me=i.useCallback(()=>{S(Ae=>bo(Ae+1))},[]),re=i.useCallback(()=>{S(Ae=>bo(Ae-1))},[]),_e=i.useCallback(Ae=>{N(Je=>Je===Ae?null:Ae)},[]),xt=i.useCallback(Ae=>{if(v==="ctrl"){L(g4(Ae)),N(null);return}if(v==="alt"){L(b4(Ae)),N(null);return}L(Ae)},[L,v]),ut=i.useCallback(Ae=>{L(Ae),N(null)},[L]);if(!e)return null;const Qe=()=>{switch(W){case"connected":return t.jsx("span",{className:"terminal-status connected",title:"Connected"});case"connecting":case"reconnecting":return t.jsx("span",{className:"terminal-status connecting",title:"Connecting..."});case"disconnected":return t.jsx("span",{className:"terminal-status disconnected",title:"Disconnected"});default:return null}},vt=!ce||!J&&!je;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Be,onMouseUp:de,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:F,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}px`,"--vv-height":w?`${w}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[k.map(Ae=>t.jsxs("div",{className:`terminal-tab ${Ae.isActive?"terminal-tab--active":""}`,onClick:()=>Ne(Ae.id),title:Ae.title,role:"tab","aria-selected":Ae.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Ae.title}),k.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Je=>{Je.stopPropagation(),xe(Ae.id)},title:"Close tab",children:"×"})]},Ae.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:He,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Gi,{size:16}),Qe()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[W==="disconnected"&&J&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:ae,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(bs,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:$e,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(bs,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Ie,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(_n,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>C(Ae=>!Ae),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":j,children:[t.jsx(zw,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Shortcuts"})]}),t.jsx("button",{className:"terminal-close",onClick:n,"data-testid":"terminal-close-btn",title:"Close terminal",children:t.jsx(un,{size:20})})]})]}),r&&t.jsx("div",{className:"terminal-error","data-testid":"terminal-error",children:r}),t.jsxs("div",{className:"terminal-container","data-testid":"terminal-container",children:[vt&&!je&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),je&&!J&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Failed to start terminal: ",je]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:ee,"data-testid":"terminal-retry-btn",children:[t.jsx(bs,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Ue,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(bs,{size:14}),"Refresh page"]})]})]})}),m&&J&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-xterm-init-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Terminal UI failed to initialize: ",m]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:st,"data-testid":"terminal-reinit-btn",children:[t.jsx(bs,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Ue,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(bs,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:I,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:nt,onTouchStart:nt},J?.sessionId)]}),j&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${v==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>_e("ctrl"),"aria-pressed":v==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${v==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>_e("alt"),"aria-pressed":v==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ut("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ut(" "),children:"Tab"})]}),x4.map(Ae=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>xt(Ae.key),title:Ae.description,children:Ae.label},Ae.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${W}`,children:[W==="connected"&&"Connected",W==="connecting"&&"Connecting...",W==="reconnecting"&&"Reconnecting...",W==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsxs("span",{className:"terminal-font-size-controls",children:[t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:re,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(dk,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[y,"px"]}),t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:me,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(Mn,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const so={name:"",command:""};function Lf(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function C4(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function E4({isOpen:e,onClose:n,addToast:s,projectId:a,onRunScript:r}){Ni(e);const[o,l]=i.useState({}),[c,d]=i.useState(!0),[u,m]=i.useState(!1),[h,f]=i.useState(null),[p,g]=i.useState(so),[x,w]=i.useState(!1),[b,y]=i.useState(null),[S,j]=i.useState(null),C=Qi(n),v=i.useCallback(async()=>{try{d(!0);const K=await _o(a);l(K)}catch(K){s(Ee(K)||"Failed to load scripts","error")}finally{d(!1)}},[s,a]);i.useEffect(()=>{e&&v()},[e,v]);const N=i.useCallback(()=>{m(!0),f(null),g(so),j(null)},[]),I=i.useCallback((K,Z)=>{f(K),m(!1),g({name:K,command:Z}),j(null)},[]),F=i.useCallback(()=>{f(null),m(!1),g(so),j(null)},[]),_=i.useCallback(K=>{g(Z=>({...Z,name:K})),K&&!Lf(K)?j("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):j(null)},[]),M=i.useCallback(async()=>{const K=p.name.trim(),Z=p.command.trim();if(!K){s("Script name is required","error");return}if(!Lf(K)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!Z){s("Script command is required","error");return}w(!0);try{await OS(K,Z,a),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(so),j(null),await v()}catch(ne){const O=Ee(ne);O?.includes("already exists")?s("A script with this name already exists","error"):s(O||"Failed to save script","error")}finally{w(!1)}},[p,h,s,v,a]),z=i.useCallback(async K=>{try{await FS(K,a),s("Script deleted","success"),y(null),h===K&&(f(null),g(so)),await v()}catch(Z){s(Ee(Z)||"Failed to delete script","error")}},[h,s,v,a]),U=i.useCallback((K,Z)=>{r&&r(K,Z)},[r]);if(!e)return null;const R=u||h!==null,D=Object.entries(o).map(([K,Z])=>({name:K,command:Z}));return t.jsx("div",{className:"modal-overlay open",...C,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(Gi,{size:18,style:{marginRight:"8px",verticalAlign:"middle"}}),"Scripts"]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"modal-body scripts-modal-body",children:c?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)"},children:[t.jsx(jt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):R?t.jsxs("div",{className:"scripts-modal-form",style:{display:"flex",flexDirection:"column",gap:"16px"},children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-name",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Script Name"}),t.jsx("input",{id:"script-name",type:"text",className:"input",value:p.name,onChange:K=>_(K.target.value),placeholder:"e.g., build, test, lint",disabled:x||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:S?"var(--color-error)":void 0}}),S&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:S}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),t.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:K=>g(Z=>({...Z,command:K.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:x,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:F,disabled:x,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:M,disabled:x||!!S,"data-testid":"script-save-btn",children:x?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:D.length===0?"No scripts defined":`${D.length} script${D.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:N,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(Mn,{size:14}),"Add Script"]})]}),D.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(Gi,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),t.jsx("div",{children:"No scripts defined yet."}),t.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:"Add scripts to quickly run common commands from the dashboard."})]}):t.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:D.map(K=>t.jsx("div",{className:"script-card","data-testid":`script-${K.name}`,style:{padding:"12px 16px",border:"1px solid var(--border)",borderRadius:"8px",background:"var(--card)"},children:t.jsxs("div",{className:"script-card-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:t.jsx("span",{style:{fontWeight:600,fontSize:"14px",fontFamily:"monospace"},children:K.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:K.command,children:C4(K.command)})]}),t.jsxs("div",{className:"script-card-actions",style:{display:"flex",gap:"4px",marginLeft:"8px",flexShrink:0},children:[t.jsxs("button",{className:"btn btn-secondary",onClick:()=>U(K.name,K.command),title:"Run script","aria-label":`Run ${K.name}`,"data-testid":`run-script-${K.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(is,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>I(K.name,K.command),title:"Edit","aria-label":`Edit ${K.name}`,"data-testid":`edit-script-${K.name}`,children:t.jsx(Mn,{size:14,style:{transform:"rotate(45deg)"}})}),b===K.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>z(K.name),title:"Confirm delete","aria-label":`Confirm delete ${K.name}`,"data-testid":`confirm-delete-script-${K.name}`,style:{color:"var(--color-error)"},children:t.jsx(_n,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${K.name}`,children:t.jsx(un,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(K.name),title:"Delete","aria-label":`Delete ${K.name}`,"data-testid":`delete-script-${K.name}`,children:t.jsx(_n,{size:14})})]})]})},K.name))})]})})]})})}function _4(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState("."),[c,d]=i.useState(!1),[u,m]=i.useState(null),[h,f]=i.useState(0),p=i.useCallback(()=>{f(x=>x+1)},[]),g=i.useCallback(x=>{l(x),m(null)},[]);return i.useEffect(()=>{l("."),m(null),r([])},[e]),i.useEffect(()=>{if(!n||!e)return;let x=!1;async function w(){d(!0),m(null);try{const b=await XN(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(Ee(b)||"Failed to load files"),r([]))}finally{x||d(!1)}}return w(),()=>{x=!0}},[e,o,n,h,s]),{entries:a,currentPath:o,setPath:g,loading:c,error:u,refresh:p}}function M4(e,n,s,a){const[r,o]=i.useState(""),[l,c]=i.useState(""),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,x]=i.useState(null),w=i.useCallback(S=>{o(S),x(null)},[]);i.useEffect(()=>{if(!e||!n){o(""),c(""),u(null),x(null);return}let S=!1;async function j(){h(!0),x(null);try{const C=await ZN(e,n,a);S||(o(C.content),c(C.content),u(C.mtime))}catch(C){S||(x(Ee(C)||"Failed to load file"),o(""),c(""),u(null))}finally{S||h(!1)}}return j(),()=>{S=!0}},[e,n,s,a]);const b=r!==l,y=i.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),x(null);try{const S=await eS(e,n,r,a);c(r),u(S.mtime)}catch(S){throw x(Ee(S)||"Failed to save file"),S}finally{p(!1)}}},[e,n,r,b,a]);return{content:r,setContent:w,originalContent:l,loading:m,saving:f,error:g,save:y,hasChanges:b,mtime:d}}const A4=1e4;function R4(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function I4(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function T4(e){const[n,s]=i.useState("Project Root"),[a,r]=i.useState([]),[o,l]=i.useState(!0),[c,d]=i.useState(null);return i.useEffect(()=>{let u=!1;async function m(){try{const f=await QN(e);if(u)return;s(R4(f.project)),r(f.tasks.map(I4)),d(null)}catch(f){u||d(Ee(f)||"Failed to load workspaces")}finally{u||l(!1)}}m();const h=window.setInterval(()=>{m()},A4);return()=>{u=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:a,loading:o,error:c}}function P4(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function $4(e){return e?new Date(e).toLocaleDateString():""}function Of(e,n){return hC(e,n)}const io={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Dd={type:null,entry:null,entryFullPath:""},D4=200,L4=500,Ff=10;function O4({x:e,y:n,entry:s,onAction:a,onClose:r}){const o=i.useRef(null),[l,c]=i.useState({x:e,y:n});i.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),f=window.visualViewport,p=f?.width&&f.width>0?f.width:window.innerWidth,g=f?.height&&f.height>0?f.height:window.innerHeight,x=f?.offsetLeft??0,w=f?.offsetTop??0,b=8;let y=e-x,S=n-w;y+h.width>p-b&&(y=p-b-h.width),S+h.height>g-b&&(S=g-b-h.height),y<b&&(y=b),S<b&&(S=b),c({x:y+x,y:S+w})},[e,n]),i.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const d=s.type==="directory",u=[{id:"copy",label:"Copy",icon:da,disabled:!1},{id:"move",label:"Move",icon:hk,disabled:!1},{id:"rename",label:"Rename",icon:qs,disabled:!1},...d?[{id:"download-zip",label:"Download as ZIP",icon:To,disabled:!1}]:[{id:"download",label:"Download",icon:Zy,disabled:!1}],{id:"divider",label:"",icon:da,disabled:!0},{id:"delete",label:"Delete",icon:_n,disabled:!1}];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsx("div",{ref:o,className:"file-browser-context-menu",role:"menu","aria-label":"File operations",style:{left:l.x,top:l.y},onClick:m=>m.stopPropagation(),children:u.map(m=>m.id==="divider"?t.jsx("div",{className:"file-browser-context-menu__divider",role:"separator"},"divider"):t.jsxs("button",{role:"menuitem",className:`file-browser-context-menu__item ${m.disabled?"file-browser-context-menu__disabled":""} ${m.id==="delete"?"file-browser-context-menu__item--danger":""}`,disabled:m.disabled,onClick:()=>a(m.id),children:[t.jsx(m.icon,{size:14,className:"file-browser-context-menu__item-icon"}),t.jsx("span",{children:m.label})]},m.id))})})}function F4({type:e,entry:n,entryFullPath:s,onConfirm:a,onCancel:r,loading:o,error:l}){const c=i.useRef(null),d=e==="rename"?n.name:"",[u,m]=i.useState(d);i.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),i.useEffect(()=>{if(e==="rename"&&c.current){const g=n.name.lastIndexOf(".");g>0?c.current.setSelectionRange(0,g):c.current.select()}},[e,n.name]);const h=g=>{g.key==="Enter"&&u.trim()&&a(u.trim()),g.key==="Escape"&&r()};if(e==="delete")return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),t.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",t.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(""),disabled:o,children:o?"Deleting...":"Delete"})]})]})});const p={copy:{title:"Copy",placeholder:"Destination path",confirm:"Copy"},move:{title:"Move",placeholder:"Destination path",confirm:"Move"},rename:{title:"Rename",placeholder:"New name",confirm:"Rename"}}[e];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:p.title}),t.jsx("div",{className:"file-browser-dialog-info",children:e==="rename"?n.name:s}),t.jsx("input",{ref:c,className:"file-browser-dialog-input",type:"text",value:u,onChange:g=>m(g.target.value),placeholder:p.placeholder,onKeyDown:h,disabled:o}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>a(u.trim()),disabled:o||!u.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function z4({entries:e,currentPath:n,onSelectFile:s,onNavigate:a,loading:r,error:o,onRetry:l,workspace:c,onRefresh:d,projectId:u}){const[m,h]=i.useState(io),[f,p]=i.useState(Dd),[g,x]=i.useState(!1),[w,b]=i.useState(null),[y,S]=i.useState(!1),[j,C]=i.useState(null),v=i.useRef(null),N=i.useRef(null),I=i.useRef(null),F=i.useRef(!1),_=i.useCallback(()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null),N.current!==null&&(window.clearTimeout(N.current),N.current=null)},[]),M=i.useCallback(()=>{_(),I.current=null,S(!1),C(null)},[_]);i.useEffect(()=>()=>{_()},[_]);const z=i.useCallback((P,$,k,J)=>{h({visible:!0,x:P,y:$,entry:k,entryFullPath:J})},[]),U=i.useCallback((P,$,k)=>{if(P.touches.length!==1)return;const J=P.touches[0];J&&(M(),I.current={x:J.clientX,y:J.clientY},N.current=window.setTimeout(()=>{S(!0),C(k)},D4),v.current=window.setTimeout(()=>{const ce=I.current;ce&&(F.current=!0,S(!1),C(null),_(),z(ce.x,ce.y,$,k))},L4))},[M,_,z]),R=i.useCallback(P=>{const $=I.current,k=P.touches[0];!$||!k||(Math.abs(k.clientX-$.x)>Ff||Math.abs(k.clientY-$.y)>Ff)&&M()},[M]),D=i.useCallback(()=>{M()},[M]);i.useEffect(()=>{if(!m.visible)return;const P=document.querySelector(".file-browser-list"),$=()=>{F.current=!1,M(),h(io)};return P?.addEventListener("scroll",$),()=>P?.removeEventListener("scroll",$)},[M,m.visible]),i.useEffect(()=>{if(!m.visible)return;const P=$=>{$.key==="Escape"&&(F.current=!1,h(io))};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[m.visible]);const K=i.useCallback((P,$)=>{P.preventDefault(),P.stopPropagation(),M(),F.current=!1,z(P.clientX,P.clientY,$,Of(n,$.name))},[M,n,z]),Z=i.useCallback(P=>{if(!m.entry)return;F.current=!1;const $=m.entry,k=m.entryFullPath;if(h(io),P==="download"){if(!c)return;const J=ob(c,k,u);window.open(Di(J),"_blank");return}if(P==="download-zip"){if(!c)return;const J=rS(c,k,u);window.open(Di(J),"_blank");return}p({type:P,entry:$,entryFullPath:k}),b(null)},[m,c,u]),ne=i.useCallback(async P=>{if(!(!f.type||!f.entry||!c)){x(!0),b(null);try{switch(f.type){case"copy":await nS(c,f.entryFullPath,P,u);break;case"move":await sS(c,f.entryFullPath,P,u);break;case"rename":await aS(c,f.entryFullPath,P,u);break;case"delete":await iS(c,f.entryFullPath,u);break}p(Dd),d?.()}catch($){b(Ee($)||"Operation failed")}finally{x(!1)}}},[f,c,d,u]),O=i.useCallback(()=>{p(Dd),b(null)},[]),A=i.useCallback((P,$)=>{if(F.current){F.current=!1;return}m.visible||(P.type==="directory"?a($):s($))},[m.visible,a,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(jt,{className:"spin",size:24}),t.jsx("span",{children:"Loading files..."})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsxs("p",{children:["Error: ",o]}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:"Retry"})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{a(pC(n))},children:[t.jsx(On,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":Dr(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(P=>{const $=Of(n,P.name),k=y&&j===$;return t.jsxs("div",{className:`file-node file-node--${P.type} ${k?"file-node--long-pressing":""}`,onClick:()=>A(P,$),onContextMenu:J=>K(J,P),onTouchStart:J=>U(J,P,$),onTouchMove:R,onTouchEnd:D,onTouchCancel:D,children:[t.jsx("div",{className:"file-node-icon",children:P.type==="directory"?t.jsx(Es,{size:16}):t.jsx(Jg,{size:16})}),t.jsx("div",{className:"file-node-name",children:P.name}),P.type==="file"&&P.size!==void 0&&t.jsx("div",{className:"file-node-size",children:P4(P.size)}),P.mtime&&t.jsx("div",{className:"file-node-time",children:$4(P.mtime)})]},P.name)})}),m.visible&&m.entry&&t.jsx(O4,{x:m.x,y:m.y,entry:m.entry,onAction:Z,onClose:()=>{F.current=!1,h(io)}}),f.type&&f.entry&&t.jsx(F4,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:ne,onCancel:O,loading:g,error:w})]})}function B4(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function U4({content:e,onChange:n,readOnly:s,filePath:a,showLineNumbers:r=!1}){const[o,l]=i.useState(!1),[c,d]=i.useState(!0),u=i.useRef(null),m=B4(a),h=m&&(s?!0:o),f=r&&!s&&!h,p=i.useMemo(()=>f?e.split(`
690
+ `).length:0,[e,f]),g=i.useCallback(()=>{l(!1)},[]),x=i.useCallback(()=>{l(!0)},[]),w=i.useCallback(()=>{d(y=>!y)},[]),b=i.useCallback(y=>{u.current&&(u.current.scrollTop=y.currentTarget.scrollTop)},[]);return t.jsxs("div",{className:"file-editor-container",children:[m?t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsxs("div",{className:"file-editor-mode-toggle",children:[!s&&t.jsxs("button",{className:`btn btn-sm ${h?"":"btn-primary"}`,onClick:g,disabled:!h,"aria-label":"Edit mode",children:[t.jsx(Gg,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${h?"btn-primary":""}`,onClick:x,disabled:h,"aria-label":"Preview mode",children:[t.jsx(Tr,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:w,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(zl,{size:14})})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsx("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:w,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(zl,{size:14})})]}),h?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],children:e})}):t.jsxs("div",{className:`file-editor-textarea-shell ${f?"file-editor-textarea-shell--line-numbers":""}`,children:[f&&t.jsx("div",{className:"file-editor-line-numbers",ref:u,"aria-hidden":"true",children:Array.from({length:p},(y,S)=>t.jsx("div",{className:"file-editor-line-number",children:S+1},`line-${S+1}`))}),t.jsx("textarea",{className:`file-editor-textarea ${c?"file-editor-textarea--wrap":""}`,value:e,onChange:y=>n(y.target.value),onScroll:b,readOnly:s,spellCheck:!1,"aria-label":a?`Editor for ${a}`:"File editor"})]})]})}function H4(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function q4({currentWorkspace:e,projectName:n,workspaces:s,onSelect:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>e==="project"?n||"Project Root":s.find(d=>d.id===e)?.label??e,[e,n,s]);return t.jsxs("div",{className:"workspace-selector",children:[t.jsxs("button",{type:"button",className:"workspace-selector-trigger",onClick:()=>o(c=>!c),"aria-haspopup":"listbox","aria-expanded":r,children:[e==="project"?t.jsx(Mm,{size:14}):t.jsx(Xd,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(pn,{size:14,className:`workspace-selector-trigger-icon${r?" open":""}`})]}),r&&t.jsxs("div",{className:"workspace-selector-menu",role:"listbox","aria-label":"Select workspace",children:[t.jsxs("button",{type:"button",className:`workspace-selector-option${e==="project"?" active":""}`,onClick:()=>{a("project"),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(Mm,{size:14}),t.jsx("span",{children:"Project Root"})]}),t.jsx("span",{className:"workspace-selector-option-meta",children:n})]}),s.length>0&&t.jsxs("div",{className:"workspace-selector-group",children:[t.jsx("div",{className:"workspace-selector-group-label",children:"Task Worktrees"}),s.map(c=>t.jsxs("button",{type:"button",className:`workspace-selector-option${e===c.id?" active":""}`,onClick:()=>{a(c.id),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(Xd,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:H4(c.title)})]},c.id))]})]})]})}const V4=768,W4=280,Cl=180,El=500,zf="fusion:file-browser-sidebar-width",Bf="kb-files-line-numbers",vv=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),K4=new Set([...vv,".exe",".dll",".so",".dylib",".zip",".tar",".gz",".bz2",".xz",".7z",".rar",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".mp3",".mp4",".avi",".mov",".webm",".mkv",".flv",".woff",".woff2",".ttf",".otf",".eot",".wasm",".bin"]);function Ld(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return K4.has(n)}function G4(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return vv.has(n)}function J4({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:a}){const{projectName:r,workspaces:o}=T4(a),l=i.useRef(null);Li(l,!0,"fusion:files-modal-size");const c=Qi(n),[d,u]=i.useState(e),[m,h]=i.useState(null),[f,p]=i.useState(!1),[g,x]=i.useState("list"),[w,b]=i.useState(W4),[y,S]=i.useState(!1),{entries:j,currentPath:C,setPath:v,loading:N,error:I,refresh:F}=_4(d,!0,a),{content:_,setContent:M,originalContent:z,loading:U,saving:R,error:D,save:K,hasChanges:Z,mtime:ne}=M4(d,m,!0,a);i.useEffect(()=>{u(e)},[e]),i.useEffect(()=>{const ie=()=>{p(window.innerWidth<=V4)};return ie(),window.addEventListener("resize",ie),()=>window.removeEventListener("resize",ie)},[]),i.useEffect(()=>{m||x("list")},[m]),i.useEffect(()=>{try{const ie=localStorage.getItem(zf);if(!ie)return;const ee=Number.parseInt(ie,10);if(!Number.isNaN(ee)){const oe=Math.max(Cl,Math.min(El,ee));b(oe)}}catch{}},[]),i.useEffect(()=>{const ie=zn(Bf,a);S(ie==="true")},[a]),i.useEffect(()=>{const ie=ee=>{ee.key==="Escape"&&n(),(ee.metaKey||ee.ctrlKey)&&ee.key==="s"&&(ee.preventDefault(),Z&&!R&&K())};return document.addEventListener("keydown",ie),()=>document.removeEventListener("keydown",ie)},[n,Z,R,K]);const O=i.useCallback(ie=>{h(ie),f&&x("editor")},[f]),A=i.useCallback(()=>{x("list")},[]),P=i.useCallback(()=>{M(z)},[z,M]),$=i.useCallback(ie=>{u(ie),h(null),x("list"),s?.(ie)},[s]),k=i.useCallback(ie=>{try{localStorage.setItem(zf,String(ie))}catch{}},[]),J=i.useCallback(ie=>{if(f)return;ie.preventDefault(),ie.stopPropagation();const ee=ie.currentTarget;typeof ee.setPointerCapture=="function"&&ee.setPointerCapture(ie.pointerId);const oe=ie.clientX,W=w;let L=W;document.body.style.userSelect="none";const pe=B=>{const ve=B.clientX-oe,Fe=Math.max(Cl,Math.min(El,W+ve));L=Fe,b(Fe)},fe=B=>{typeof ee.releasePointerCapture=="function"&&ee.releasePointerCapture(B.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",pe),document.removeEventListener("pointerup",fe),k(L)};document.addEventListener("pointermove",pe),document.addEventListener("pointerup",fe)},[f,k,w]),ce=i.useCallback(ie=>{if(f)return;const ee=20;if(ie.key!=="ArrowLeft"&&ie.key!=="ArrowRight")return;ie.preventDefault();const oe=ie.key==="ArrowLeft"?-ee:ee,W=Math.max(Cl,Math.min(El,w+oe));b(W),k(W)},[f,k,w]),je=i.useCallback(()=>{S(ie=>{const ee=!ie;return us(Bf,String(ee),a),ee})},[a]),xe=`Files — ${i.useMemo(()=>d==="project"?"Project":o.find(ie=>ie.id===d)?.id??d,[d,o])}`,Ne=i.useMemo(()=>!m||!G4(m)?null:ob(d,m,a),[m,d,a]),Y=ie=>{const ee=new Blob([ie]).size;return ee<1024?`${ee} B`:`${(ee/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",...c,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",ref:l,children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(Es,{size:18}),t.jsx("span",{children:xe}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsxs("button",{className:`btn btn-sm file-browser-line-numbers-toggle ${y?"btn-primary":""}`,onClick:je,"aria-label":"Toggle line numbers","aria-pressed":y,title:"Toggle line numbers",children:[t.jsx(Gw,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx(q4,{currentWorkspace:d,projectName:r,workspaces:o,onSelect:$}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(un,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${f?"mobile":""} ${g==="list"?"active":""}`,style:f?void 0:{width:`${w}px`},children:t.jsx(z4,{entries:j,currentPath:C,onSelectFile:O,onNavigate:v,loading:N,error:I,onRetry:F,workspace:d,onRefresh:F,projectId:a})}),!f&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":Cl,"aria-valuemax":El,"aria-valuenow":w,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:J,onKeyDown:ce}),t.jsx("div",{className:`file-browser-content ${f?"mobile":""} ${g==="editor"?"active":""}`,children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[f&&g==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:A,"aria-label":"Back to file list",children:[t.jsx(Ha,{size:16}),t.jsx("span",{children:"Back"})]}),m,Ld(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(bw,{size:12}),"Binary file — read only"]}),ne&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(ne).toLocaleString()]}),U&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!Ne&&Z&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:P,disabled:R,children:[t.jsx(_k,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void K(),disabled:R,children:[t.jsx(eb,{size:14}),R?"Saving...":"Save"]})]})})]}),D&&!Ne&&t.jsx("div",{className:"file-browser-error-banner",children:D}),Ne?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:Ne,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(U4,{content:_,onChange:M,filePath:m,readOnly:Ld(m),showLineNumbers:y&&!Ld(m)})}),!Ne&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:Y(_)}),Z&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(Es,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}const Y4=i.lazy(()=>Sn(()=>import("./TodoView-sS_mT0Y7.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));function Q4({onClose:e,projectId:n,addToast:s,onPlanningMode:a}){const r=Qi(e),l=ri()==="mobile",{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=Zi({enabled:l});Ni(l);const h=m?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{};return i.useEffect(()=>{const f=p=>{p.key==="Escape"&&e()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e]),t.jsx("div",{className:"modal-overlay open",...r,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal todo-modal",style:h,children:[t.jsxs("div",{className:"modal-header todo-modal-header",children:[t.jsxs("div",{className:"todo-modal-header-title",children:[t.jsx(Ww,{size:18}),t.jsxs("div",{children:[t.jsx("h2",{children:"Todos"}),t.jsx("p",{children:"Manage reusable todo lists for your project."})]})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(un,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Y4,{projectId:n,addToast:s,onPlanningMode:a,onClose:e,mobileKeyboardActive:l&&m})})})]})})}function X4(e={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=e,[a,r]=i.useState({providers:[],loading:!0,error:null,lastUpdated:null}),o=i.useRef(null),l=i.useRef(null),c=i.useCallback(async(u=!1)=>{l.current&&l.current.abort(),l.current=new AbortController,u&&r(m=>({...m,loading:!0,error:null}));try{const{providers:m}=await eN();r({providers:m,loading:!1,error:null,lastUpdated:new Date})}catch(m){if(m instanceof Error&&m.name==="AbortError")return;r(h=>({...h,loading:!1,error:Ee(m)||"Failed to fetch usage data"}))}},[]);i.useEffect(()=>{c()},[c]),i.useEffect(()=>{if(s)return o.current=setInterval(()=>{c(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,c]),i.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const d=i.useCallback(()=>c(!0),[c]);return{providers:a.providers,loading:a.loading,error:a.error,lastUpdated:a.lastUpdated,refresh:d}}function Z4(e){const n=new Date(e),s=new Date,a=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return a;const o=new Date(s.getFullYear(),s.getMonth(),s.getDate()),l=new Date(n.getFullYear(),n.getMonth(),n.getDate()),c=Math.round((l.getTime()-o.getTime())/(1440*60*1e3));return c>=1&&c<=7?`${n.toLocaleDateString(void 0,{weekday:"short"})} ${a}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${a}`}function eD(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const yv="kb-usage-hidden-windows",wv="kb-usage-modal-size",kv="kb-usage-provider-order";function Uf(e){const n=zn(wv,e);if(!n)return null;try{const s=JSON.parse(n);if(s&&typeof s.width=="number"&&typeof s.height=="number"&&s.width>0&&s.height>0)return{width:s.width,height:s.height}}catch{}return null}function Hf(e){const n=zn(yv,e);if(!n)return{};try{const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((a,[r,o])=>{if(Array.isArray(o)){const l=o.filter(c=>typeof c=="string");l.length>0&&(a[r]=l)}return a},{})}catch{return{}}}function tD(e,n){us(yv,JSON.stringify(e),n)}function qf(e){const n=zn(kv,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(a=>typeof a=="string"):[]}catch{return[]}}function Vf(e,n){us(kv,JSON.stringify(e),n)}function jv(e,n,s){return s[e]?.includes(n)??!1}function nD({window:e,viewMode:n,isHidden:s,onToggleHidden:a}){const r=eD(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,d=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let u=e.resetText;if(!u&&e.resetAt){const w=new Date(e.resetAt).getTime()-Date.now();if(w>0){const b=Math.floor(w/36e5),y=Math.floor(b/24),S=b%24;y>0&&S>0?u=`resets in ${y}d ${S}h`:y>0?u=`resets in ${y}d`:b>0?u=`resets in ${b}h`:u=`resets in ${Math.floor(w/6e4)}m`}}const m=e.pace,h=m!==void 0;let f=0;h&&(f=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",g=m?.status==="behind",x=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:a,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(Tr,{size:14})})]})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${r}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),h&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${f}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:d}),t.jsxs("span",{className:"usage-window-reset-group",children:[u&&t.jsx("span",{className:"usage-window-reset",children:u}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:Z4(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(Oo,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:m.message})]}),g&&t.jsxs(t.Fragment,{children:[t.jsx(Yk,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),x&&t.jsxs(t.Fragment,{children:[t.jsx(Gn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function sD(e){const n=e.toLowerCase();return n.includes("claude")||n.includes("anthropic")?"anthropic":n.includes("codex")||n.includes("openai")||n.includes("gpt")?"openai":n.includes("gemini")||n.includes("google")||n.includes("antigravity")?"google":n.includes("ollama")?"ollama":n.includes("minimax")?"minimax":n.includes("zai")||n.includes("zhipu")?"zai":n.includes("kimi")||n.includes("moonshot")?"kimi":n.includes("bedrock")||n.includes("amazon")?"bedrock":n.includes("xai")||n.includes("grok")?"xai":n.includes("opencode")?"opencode":n.includes("copilot")||n==="github copilot"?"github-copilot":e}function iD({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:a,onShowAllHidden:r,isDragging:o,isDragOver:l,dragOverPosition:c,onDragStart:d,onDragOver:u,onDragLeave:m,onDrop:h,onDragEnd:f,isTouchReorderMode:p,canMoveUp:g,canMoveDown:x,onMoveUp:w,onMoveDown:b}){const y=s[e.name]?.length??0,S=()=>{switch(e.status){case"ok":return null;case"error":return t.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:"Error"});case"no-auth":default:return t.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:"Not configured"})}};return t.jsxs("div",{className:`usage-provider${o?" usage-provider--dragging":""}${l&&c==="before"?" usage-provider--drag-over-before":""}${l&&c==="after"?" usage-provider--drag-over-after":""}`,"data-provider":e.name,"data-status":e.status,draggable:!p,onDragStart:p?void 0:d,onDragOver:p?void 0:u,onDragLeave:p?void 0:m,onDrop:p?void 0:h,onDragEnd:p?void 0:f,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(Fn,{provider:sD(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),y>0&&t.jsxs("button",{className:"btn btn-sm usage-show-hidden-btn",onClick:()=>r(e.name),"data-testid":"usage-show-hidden-btn",children:["Show hidden (",y,")"]})]}),t.jsxs("div",{className:"usage-provider-actions",children:[p&&t.jsxs("div",{className:"usage-provider-reorder-controls",role:"group","aria-label":`Reorder ${e.name}`,children:[t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:w,disabled:!g,"aria-label":`Move ${e.name} up`,children:t.jsx(Pi,{size:14})}),t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:b,disabled:!x,"aria-label":`Move ${e.name} down`,children:t.jsx(pn,{size:14})})]}),S(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(mc,{size:16})})]})]}),e.error&&t.jsx("div",{className:"usage-provider-error",children:e.error}),e.plan&&t.jsx("div",{className:"usage-provider-meta",children:t.jsx("span",{className:"usage-provider-plan",children:e.plan})}),e.windows.length>0?t.jsx("div",{className:"usage-provider-windows",children:e.windows.map((j,C)=>{const v=jv(e.name,j.label,s);return t.jsx(nD,{window:j,viewMode:n,isHidden:v,onToggleHidden:()=>a(e.name,j.label)},`${e.name}-${j.label}-${C}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function aD(){return t.jsx("div",{className:"usage-skeleton",children:[1,2,3].map(e=>t.jsxs("div",{className:"usage-skeleton-provider",children:[t.jsxs("div",{className:"usage-skeleton-header",children:[t.jsx("div",{className:"usage-skeleton-icon"}),t.jsx("div",{className:"usage-skeleton-name"}),t.jsx("div",{className:"usage-skeleton-badge"})]}),t.jsx("div",{className:"usage-skeleton-bar"}),t.jsx("div",{className:"usage-skeleton-text"})]},e))})}function rD({isOpen:e,onClose:n,projectId:s,anchorRect:a}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:d}=X4({autoRefresh:e}),[u,m]=i.useState(!1),[h,f]=i.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,g]=i.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(pointer: coarse)").matches??!1),[x,w]=i.useState("used"),[b,y]=i.useState(()=>Hf(s)),[S,j]=i.useState(()=>qf(s)),[C,v]=i.useState(null),[N,I]=i.useState(null),[F,_]=i.useState(null),M=i.useRef(null),z=i.useRef(null),U=i.useRef(e),R=i.useRef(!1),[D,K]=i.useState(()=>Uf(s));i.useEffect(()=>{K(Uf(s))},[s]),i.useEffect(()=>{if(!e||!h)return;const B=z.current;if(!B||typeof ResizeObserver>"u")return;let ve=null;const Fe=new ResizeObserver(ae=>{const qe=ae[0];if(!qe)return;const{width:Pe,height:nt}=qe.contentRect;Pe<=0||nt<=0||(ve&&clearTimeout(ve),ve=setTimeout(()=>{us(wv,JSON.stringify({width:Math.round(Pe),height:Math.round(nt)}),s)},250))});return Fe.observe(B),()=>{ve&&clearTimeout(ve),Fe.disconnect()}},[e,h,s]),i.useEffect(()=>{e||(R.current=!1)},[e]),i.useEffect(()=>{r.length>0&&(R.current=!0)},[r.length]),i.useEffect(()=>{if(typeof window>"u")return;const B=window.matchMedia?.("(pointer: coarse)"),ve=()=>{f(window.innerWidth>=769),g(B?.matches??!1)};return ve(),window.addEventListener("resize",ve),B?.addEventListener?.("change",ve),()=>{window.removeEventListener("resize",ve),B?.removeEventListener?.("change",ve)}},[]),i.useEffect(()=>{!U.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&d(),U.current=e},[e,c,d]),i.useEffect(()=>{const B=zn("kb-usage-view-mode",s);if(B==="used"||B==="remaining"){w(B);return}w("used")},[s]);const Z=i.useCallback(B=>{w(B),us("kb-usage-view-mode",B,s)},[s]);i.useEffect(()=>{y(Hf(s)),j(qf(s))},[s]),i.useEffect(()=>{tD(b,s)},[b,s]);const ne=i.useCallback((B,ve)=>{y(Fe=>{if(jv(B,ve,Fe)){const ae=(Fe[B]??[]).filter(qe=>qe!==ve);if(ae.length===0){const{[B]:qe,...Pe}=Fe;return Pe}return{...Fe,[B]:ae}}return{...Fe,[B]:[...Fe[B]??[],ve]}})},[]),O=i.useCallback(B=>{y(ve=>{if(!ve[B])return ve;const{[B]:Fe,...ae}=ve;return ae})},[]),A=i.useCallback(B=>{if(S.length===0)return B;const ve=new Map(B.map(ae=>[ae.name,ae])),Fe=[];for(const ae of S){const qe=ve.get(ae);qe&&(Fe.push(qe),ve.delete(ae))}return[...Fe,...ve.values()]},[S]),P=i.useCallback((B,ve)=>{B.dataTransfer.effectAllowed="move",B.dataTransfer.setData("text/plain",ve),v(ve)},[]),$=i.useCallback((B,ve)=>{if(!C||C===ve)return;B.preventDefault(),B.dataTransfer.dropEffect="move";const{top:Fe,height:ae}=B.currentTarget.getBoundingClientRect(),qe=Fe+ae/2,Pe=B.clientY<qe?"before":"after";I(ve),_(Pe)},[C]),k=i.useCallback((B,ve)=>{B.preventDefault();const Fe=C??B.dataTransfer.getData("text/plain");if(!Fe||Fe===ve){I(null),_(null);return}const qe=A(r).map(Be=>Be.name).filter(Be=>Be!==Fe),Pe=qe.indexOf(ve);if(Pe<0){I(null),_(null);return}const nt=F==="after"?Pe+1:Pe;qe.splice(nt,0,Fe),Vf(qe,s),j(qe),I(null),_(null)},[C,F,s,r,A]),J=i.useCallback(()=>{v(null),I(null),_(null)},[]),ce=i.useCallback((B,ve)=>{const Fe=A(r).map(Be=>Be.name),ae=Fe.indexOf(B),qe=ae+ve;if(ae<0||qe<0||qe>=Fe.length)return;const Pe=[...Fe],[nt]=Pe.splice(ae,1);Pe.splice(qe,0,nt),Vf(Pe,s),j(Pe)},[s,r,A]),je=i.useCallback(async()=>{m(!0),await d(),m(!1)},[d]);i.useEffect(()=>{if(!e)return;const B=ve=>{ve.key==="Escape"&&n()};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[e,n]);const He=i.useCallback(B=>{B.target===B.currentTarget&&n()},[n]);if(!e)return null;const xe=!!(a&&h),Ne=8,Y=12,ee=D?.width??420,oe=xe?Math.min((a?.bottom??0)+Ne,window.innerHeight-Y):void 0,W=xe?Math.max(8,(a?.right??0)-ee):void 0,L=h&&D?{width:D.width,height:D.height}:{},pe=A(r),fe=t.jsxs("div",{ref:z,className:`usage-modal${xe?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:xe?{position:"fixed",top:oe,left:W,...L}:L,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ys,{size:18,className:"usage-header-icon"}),t.jsx("h3",{children:"Usage"})]}),t.jsxs("div",{className:"usage-header-actions",children:[t.jsxs("div",{className:"usage-view-toggle",role:"group","aria-label":"Usage view mode",children:[t.jsx("button",{className:`usage-view-toggle-btn ${x==="used"?"active":""}`,onClick:()=>Z("used"),"aria-pressed":x==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${x==="remaining"?"active":""}`,onClick:()=>Z("remaining"),"aria-pressed":x==="remaining","data-testid":"usage-view-toggle-remaining",children:"Remaining"})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close usage modal","data-testid":"usage-modal-close",children:t.jsx(un,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:M,children:(o||!R.current&&!l)&&r.length===0?t.jsx(aD,{}):l&&r.length===0?t.jsxs("div",{className:"usage-error",children:[t.jsx("p",{children:"Failed to load usage data"}),t.jsx("p",{className:"usage-error-message",children:l}),t.jsx("button",{className:"btn btn-sm",onClick:je,children:"Retry"})]}):r.length===0?t.jsxs("div",{className:"usage-empty",children:[t.jsx("p",{children:"No AI providers configured"}),t.jsx("p",{className:"usage-empty-hint",children:"Configure authentication in Settings to see usage data."})]}):t.jsx("div",{className:"usage-providers",children:pe.map((B,ve)=>t.jsx(iD,{provider:B,viewMode:x,hiddenWindows:b,onToggleWindow:ne,onShowAllHidden:O,isDragging:C===B.name,isDragOver:N===B.name,dragOverPosition:N===B.name?F:null,onDragStart:Fe=>P(Fe,B.name),onDragOver:Fe=>$(Fe,B.name),onDragLeave:()=>{N===B.name&&(I(null),_(null))},onDrop:Fe=>k(Fe,B.name),onDragEnd:J,isTouchReorderMode:p,canMoveUp:ve>0,canMoveDown:ve<pe.length-1,onMoveUp:()=>ce(B.name,-1),onMoveDown:()=>ce(B.name,1)},B.name))})}),t.jsxs("div",{className:"modal-actions usage-actions",children:[t.jsx("div",{className:"modal-actions-left usage-actions-left",children:t.jsx("div",{className:"usage-last-updated",children:c&&t.jsxs("span",{children:["Last updated: ",c.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:je,disabled:o||u,"data-testid":"usage-refresh-btn",children:[t.jsx(bs,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return xe?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),fe]}):t.jsx("div",{className:"modal-overlay open",onClick:He,"data-testid":"usage-modal-overlay",children:fe})}function Nv(e){if(e<1e3)return`${e}ms`;const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60),a=n%60;if(s<60)return a>0?`${s}m ${a}s`:`${s}m`;const r=Math.floor(s/60),o=s%60;return o>0?`${r}h ${o}m`:`${r}h`}function nc(e){const n=Date.now(),s=new Date(e).getTime(),a=n-s;if(a<0){const r=Math.abs(a);return r<6e4?"in a moment":r<36e5?`in ${Math.floor(r/6e4)}m`:r<864e5?`in ${Math.floor(r/36e5)}h`:`in ${Math.floor(r/864e5)}d`}return a<6e4?"just now":a<36e5?`${Math.floor(a/6e4)}m ago`:a<864e5?`${Math.floor(a/36e5)}h ago`:`${Math.floor(a/864e5)}d ago`}const oD={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},Sv={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},lD={cron:qg,webhook:tb,api:Vg,manual:as},cD={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},dD={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function uD({result:e}){const n=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("span",{className:`schedule-run-badge ${e.success?"success":"failure"}`,children:[e.success?t.jsx(Gn,{size:12}):t.jsx(Do,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:Nv(n)})]})}function mD({result:e,index:n}){const[s,a]=i.useState(!1),r=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("div",{className:"schedule-history-item",children:[t.jsxs("button",{className:"schedule-history-header",onClick:()=>a(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${e.success?"succeeded":"failed"} ${nc(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Gn,{size:12}):t.jsx(Do,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:nc(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:Sv[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:Nv(r)}),s?t.jsx(Pi,{size:12}):t.jsx(pn,{size:12})]}),s&&t.jsxs("div",{className:"schedule-history-detail",children:[e.output&&t.jsx("pre",{className:"schedule-history-output",children:e.output}),e.error&&t.jsx("div",{className:"schedule-history-error",children:e.error})]})]})}function hD({routine:e,onEdit:n,onDelete:s,onRun:a,onToggle:r,running:o,lastRunOutput:l}){const[c,d]=i.useState(!1),{confirm:u}=pi(),m=i.useCallback(async()=>{await u({title:"Delete Routine",message:`Delete routine "${e.name}"? This cannot be undone.`,danger:!0})&&s(e)},[e,s,u]),h=oD[e.trigger.type],f=lD[e.trigger.type],p=e.trigger.type==="cron"?("cronExpression"in e.trigger?e.trigger.cronExpression:void 0)||e.cronExpression||"":e.cronExpression||"";return t.jsxs("div",{className:`routine-card${e.enabled?"":" disabled"}${o?" running":""}`,children:[t.jsxs("div",{className:"routine-card-header",children:[t.jsxs("div",{className:"routine-card-info",children:[t.jsxs("div",{className:"routine-card-name-row",children:[t.jsx("span",{className:"routine-card-name",children:e.name}),t.jsxs("span",{className:"routine-trigger-badge",style:{borderColor:h,color:h},children:[t.jsx(f,{size:10}),Sv[e.trigger.type]]}),e.scope&&t.jsxs("span",{className:`routine-scope-badge${e.scope==="global"?" global":" project"}`,title:`${e.scope==="global"?"Global":"Project"}-scoped routine`,children:[e.scope==="global"?t.jsx(dc,{size:10}):t.jsx(Es,{size:10}),e.scope]})]}),e.description&&t.jsx("p",{className:"routine-card-description",children:e.description})]}),t.jsxs("div",{className:"routine-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>a(e),disabled:o,title:o?"Running…":"Run now","aria-label":o?"Running…":`Run ${e.name} now`,children:o?t.jsx(jt,{className:"spinner"}):t.jsx(is,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>r(e),title:e.enabled?"Disable":"Enable","aria-label":e.enabled?`Disable ${e.name}`:`Enable ${e.name}`,"aria-pressed":e.enabled,children:e.enabled?t.jsx(vi,{}):t.jsx(is,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(qs,{})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(_n,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx($a,{size:12}),t.jsxs("span",{className:"routine-policy-badge",children:[e.steps.length," step",e.steps.length===1?"":"s"]})]}):e.command?t.jsx("div",{className:"routine-meta-item routine-meta-command-preview",title:e.command,children:t.jsx("code",{className:"routine-cron",children:e.command})}):null,e.trigger.type==="cron"&&p&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Ji,{size:12}),t.jsx("code",{className:"routine-cron",children:p})]}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${e.executionPolicy}`,children:cD[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:dD[e.catchUpPolicy]})}),e.nextRunAt&&e.enabled&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Next:"}),t.jsx("span",{title:e.nextRunAt,children:nc(e.nextRunAt)})]}),e.lastRunAt&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Last:"}),t.jsx("span",{title:e.lastRunAt,children:nc(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(uD,{result:e.lastRunResult}),t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Runs:"}),t.jsx("span",{children:e.runCount})]})]}),l&&t.jsxs("div",{className:`routine-run-output ${l.success?"success":"failure"}`,children:[l.output&&t.jsx("pre",{className:"routine-run-output-text",children:l.output}),l.error&&t.jsx("div",{className:"routine-run-output-error",children:l.error})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>d(g=>!g),"aria-expanded":c,children:[c?t.jsx(Pi,{size:12}):t.jsx(pn,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),c&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((g,x)=>t.jsx(mD,{result:g,index:x},`${g.startedAt}-${x}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function pD({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Gi,{size:n}),t.jsx("span",{children:"Command"})]}):e==="create-task"?t.jsxs("span",{className:"step-type-badge step-type-create-task",title:"Create Task step",children:[t.jsx(Yw,{size:n}),t.jsx("span",{children:"Create Task"})]}):t.jsxs("span",{className:"step-type-badge step-type-ai-prompt",title:"AI Prompt step",children:[t.jsx(gs,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function Od(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function fD(e){return e==="command"?{id:Od(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:Od(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:Od(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function gD({step:e,onSave:n,onCancel:s}){const[a,r]=i.useState(e.name),[o,l]=i.useState(e.type),[c,d]=i.useState(e.command??""),[u,m]=i.useState(e.prompt??""),[h,f]=i.useState(e.modelProvider??""),[p,g]=i.useState(e.modelId??""),[x,w]=i.useState(e.taskTitle??""),[b,y]=i.useState(e.taskDescription??""),[S,j]=i.useState(e.taskColumn??"triage"),[C,v]=i.useState(e.timeoutMs),[N,I]=i.useState(e.continueOnFailure??!1),[F,_]=i.useState({}),[M,z]=i.useState([]),[U,R]=i.useState(!1),[D,K]=i.useState(null);i.useEffect(()=>{let P=!1;return R(!0),K(null),Ks().then($=>{P||z($.models)}).catch($=>{P||K($ instanceof Error?$.message:"Failed to load models")}).finally(()=>{P||R(!1)}),()=>{P=!0}},[]);const Z=i.useCallback(()=>{const P={};return a.trim()||(P.name="Step name is required"),o==="command"&&!c.trim()&&(P.command="Command is required"),o==="ai-prompt"&&!u.trim()&&(P.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(P.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(P.modelProvider="Both model provider and model ID must be set together"),C!==void 0&&C<1e3&&(P.timeoutMs="Timeout must be at least 1 second (1000ms)"),_(P),Object.keys(P).length===0},[a,o,c,u,b,h,p,C]),ne=h&&p?`${h}/${p}`:"",O=i.useCallback(P=>{if(!P)f(""),g("");else{const $=P.indexOf("/");$!==-1&&(f(P.slice(0,$)),g(P.slice($+1)))}},[]),A=i.useCallback(()=>{if(!Z())return;const P={...e,name:a.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?u.trim():void 0,taskTitle:o==="create-task"&&x.trim()?x.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?S:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:C||void 0,continueOnFailure:N};o!=="ai-prompt"&&delete P.prompt,o!=="create-task"&&(delete P.taskTitle,delete P.taskDescription,delete P.taskColumn),n(P)},[Z,n,e,a,o,c,u,x,b,S,h,p,C,N]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:a,onChange:P=>r(P.target.value),"aria-invalid":!!F.name}),F.name&&t.jsx("small",{className:"field-error",children:F.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:P=>l(P.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:P=>d(P.target.value),rows:2,"aria-invalid":!!F.command}),F.command&&t.jsx("small",{className:"field-error",children:F.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:u,onChange:P=>m(P.target.value),rows:3,"aria-invalid":!!F.prompt}),F.prompt&&t.jsx("small",{className:"field-error",children:F.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(Is,{id:`step-model-${e.id}`,label:"Model",models:M,value:ne,onChange:O,placeholder:"Use default",disabled:U}),D&&t.jsx("small",{className:"field-error",children:D}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:x,onChange:P=>w(P.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:b,onChange:P=>y(P.target.value),rows:4,"aria-invalid":!!F.taskDescription}),F.taskDescription&&t.jsx("small",{className:"field-error",children:F.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:"Target Column"}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:S,onChange:P=>j(P.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]}),t.jsx("small",{children:"Column where the new task will be created"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-model-${e.id}`,children:"Executor Model (optional)"}),t.jsx(Is,{id:`step-task-model-${e.id}`,label:"Model",models:M,value:ne,onChange:O,placeholder:"Use default",disabled:U}),D&&t.jsx("small",{className:"field-error",children:D}),F.modelProvider&&t.jsx("small",{className:"field-error",children:F.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:C??"",onChange:P=>v(P.target.value?Number(P.target.value):void 0),"aria-invalid":!!F.timeoutMs}),F.timeoutMs&&t.jsx("small",{className:"field-error",children:F.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:N,onChange:P=>I(P.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:A,children:"Save Step"})]})]})}function bD({steps:e,onChange:n,onEditingChange:s}){const[a,r]=i.useState(null);i.useEffect(()=>{s?.(a!==null)},[a,s]);const o=i.useCallback(u=>{const m=fD(u);n([...e,m]),r(m.id)},[e,n]),l=i.useCallback(u=>{n(e.filter(m=>m.id!==u)),a===u&&r(null)},[e,n,a]),c=i.useCallback((u,m)=>{const h=e.findIndex(g=>g.id===u);if(h<0)return;const f=m==="up"?h-1:h+1;if(f<0||f>=e.length)return;const p=[...e];[p[h],p[f]]=[p[f],p[h]],n(p)},[e,n]),d=i.useCallback(u=>{n(e.map(m=>m.id===u.id?u:m)),r(null)},[e,n]);return t.jsxs("div",{className:"steps-editor",children:[t.jsx("div",{className:"steps-editor-header",children:t.jsxs("span",{className:"steps-editor-title",children:["Steps (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),t.jsx("div",{className:"steps-list",children:e.map((u,m)=>t.jsx("div",{className:"step-card",children:a===u.id?t.jsx(gD,{step:u,onSave:d,onCancel:()=>r(null)}):t.jsxs("div",{className:"step-card-row",children:[t.jsx("div",{className:"step-card-drag",children:t.jsx(mc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(pD,{type:u.type}),t.jsx("span",{className:"step-card-name",children:u.name}),u.continueOnFailure&&t.jsx("span",{className:"step-card-flag",title:"Continues on failure",children:"⚡"}),t.jsxs("div",{className:"step-card-actions",children:[t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"up"),disabled:m===0,title:"Move up","aria-label":`Move ${u.name} up`,children:t.jsx(Pi,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"down"),disabled:m===e.length-1,title:"Move down","aria-label":`Move ${u.name} down`,children:t.jsx(pn,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(u.id),title:"Edit","aria-label":`Edit ${u.name}`,children:t.jsx(qs,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(u.id),title:"Delete","aria-label":`Delete ${u.name}`,children:t.jsx(_n,{})})]})]})},u.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("command"),children:[t.jsx(Mn,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(Mn,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(Mn,{size:14}),"Add Create Task Step"]})]})]})}const Cv={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},xD={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function vD(e){const n=e.trim();for(const[s,a]of Object.entries(Cv))if(a===n)return s;return"custom"}function yD(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function wD(e,n,s,a,r){switch(e){case"cron":return{type:"cron",cronExpression:n};case"webhook":return{type:"webhook",webhookPath:s||"/trigger/"+Math.random().toString(36).slice(2,10),secret:a||void 0};case"api":return{type:"api",endpoint:r||"/api/routine/"+Math.random().toString(36).slice(2,10)};case"manual":return{type:"manual"}}}function kD(e){const n=e.trigger;switch(n.type){case"cron":return{triggerType:"cron",cronExpression:n.cronExpression,webhookPath:"",webhookSecret:"",endpoint:""};case"webhook":return{triggerType:"webhook",cronExpression:"",webhookPath:n.webhookPath,webhookSecret:n.secret||"",endpoint:""};case"api":return{triggerType:"api",cronExpression:"",webhookPath:"",webhookSecret:"",endpoint:n.endpoint};case"manual":return{triggerType:"manual",cronExpression:"",webhookPath:"",webhookSecret:"",endpoint:""}}}const jD=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],ND=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function Wf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Kf({routine:e,onSubmit:n,onCancel:s,scope:a,projectId:r,onScopeChange:o}){const l=!!e,c=e?kD(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[d,u]=i.useState(e?.name??""),[m,h]=i.useState(e?.description??""),[f,p]=i.useState(c.triggerType),[g,x]=i.useState(c.cronExpression),[w,b]=i.useState(()=>c.triggerType!=="cron"?"custom":vD(c.cronExpression)),[y,S]=i.useState(c.webhookPath),[j,C]=i.useState(c.webhookSecret),[v,N]=i.useState(c.endpoint),[I,F]=i.useState(e?.executionPolicy??"queue"),[_,M]=i.useState(e?.catchUpPolicy??"run_one"),[z,U]=i.useState(e?.enabled??!0),R=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,D=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[K,Z]=i.useState(e?.steps&&e.steps.length>0&&!R&&!D?"advanced":"simple"),[ne,O]=i.useState(()=>R?"ai-prompt":D?"create-task":"command"),[A,P]=i.useState(e?.command??""),[$,k]=i.useState(e?.steps??[]),[J,ce]=i.useState(!1),[je,He]=i.useState(e?.timeoutMs??3e5),[xe,Ne]=i.useState(R?e.steps?.[0]?.prompt??"":""),[Y,ie]=i.useState(D?e.steps?.[0]?.taskTitle??"":""),[ee,oe]=i.useState(D?e.steps?.[0]?.taskDescription??"":""),[W,L]=i.useState(D?e.steps?.[0]?.taskColumn??"triage":"triage"),[pe,fe]=i.useState(R||D?e.steps?.[0]?.modelProvider??"":""),[B,ve]=i.useState(R||D?e.steps?.[0]?.modelId??"":""),[Fe,ae]=i.useState([]),[qe,Pe]=i.useState(!1),[nt,Be]=i.useState(null),[de,Ie]=i.useState(a??"global"),[$e,st]=i.useState({}),[Ue,me]=i.useState(!1),re=i.useRef(!0);i.useEffect(()=>()=>{re.current=!1},[]),i.useEffect(()=>{a&&Ie(a)},[a]),i.useEffect(()=>{let ke=!1;return Pe(!0),Be(null),Ks().then(tt=>{ke||ae(tt.models)}).catch(tt=>{ke||Be(tt instanceof Error?tt.message:"Failed to load models")}).finally(()=>{ke||Pe(!1)}),()=>{ke=!0}},[]);const _e=pe&&B?`${pe}/${B}`:"",xt=i.useCallback(ke=>{if(!ke){fe(""),ve("");return}const tt=ke.indexOf("/");tt!==-1&&(fe(ke.slice(0,tt)),ve(ke.slice(tt+1)))},[]),ut=i.useCallback(()=>{const ke={};if(d.trim()||(ke.name="Name is required"),de==="project"&&!r&&(ke.scope="Project-specific entries require an active project."),f==="cron"&&w==="custom"&&(g.trim()?yD(g)||(ke.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):ke.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(ke.webhookPath="Webhook path is required"),f==="api"&&!v.trim()&&(ke.endpoint="API endpoint is required"),K==="simple")ne==="command"&&!A.trim()&&(ke.command="Command is required"),ne==="ai-prompt"&&!xe.trim()&&(ke.prompt="Prompt is required"),ne==="create-task"&&!ee.trim()&&(ke.taskDescription="Task description is required"),(pe.trim()&&!B.trim()||!pe.trim()&&B.trim())&&(ke.model="Both model provider and model ID must be set, or both must be empty");else{$.length===0&&(ke.steps="At least one step is required"),J&&(ke.stepsEditing="Please save or cancel all step edits before saving the routine");const tt=[];$.forEach((Rt,Re)=>{Rt.name?.trim()||tt.push(`Step ${Re+1}: Name is required`),Rt.type==="command"&&!Rt.command?.trim()&&tt.push(`Step ${Re+1}: Command is required`),Rt.type==="ai-prompt"&&!Rt.prompt?.trim()&&tt.push(`Step ${Re+1}: Prompt is required`),Rt.type==="create-task"&&!Rt.taskDescription?.trim()&&tt.push(`Step ${Re+1}: Task description is required`)}),tt.length>0&&(ke.steps=tt.join("; "))}return je<1e3&&(ke.timeoutMs="Timeout must be at least 1 second (1000ms)"),st(ke),Object.keys(ke).length===0},[d,f,g,w,y,v,de,r,K,ne,A,xe,ee,pe,B,$,J,je]),Qe=i.useCallback(async ke=>{if(ke.preventDefault(),!!ut()){me(!0);try{let tt=e?.scope??de??(r?"project":"global");tt==="project"&&!r&&(tt="global");const Rt=wD(f,g,y,j,v);let Re,be;K==="simple"?ne==="command"?Re=A.trim()||void 0:ne==="ai-prompt"?be=[{id:Wf(),type:"ai-prompt",name:d.trim(),prompt:xe.trim(),modelProvider:pe.trim()||void 0,modelId:B.trim()||void 0}]:be=[{id:Wf(),type:"create-task",name:d.trim(),taskTitle:Y.trim()||void 0,taskDescription:ee.trim(),taskColumn:W,modelProvider:pe.trim()||void 0,modelId:B.trim()||void 0}]:be=$;const rt={name:d.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:Rt,command:Re,steps:be,timeoutMs:je,executionPolicy:I,catchUpPolicy:_,enabled:z,scope:tt};await n(rt)}finally{re.current&&me(!1)}}},[ut,n,d,m,f,g,y,j,v,K,ne,A,xe,pe,B,Y,ee,W,$,je,I,_,z,de,r,e?.scope,e?.agentId]),vt="routine-name-error",Ae="routine-cron-error",Je="routine-webhook-error",dt="routine-endpoint-error",Nt="routine-command-error",yt="routine-prompt-error",Se="routine-task-description-error",G="routine-model-error",ge="routine-timeout-error",pt=i.useCallback(ke=>{b(ke),ke!=="custom"&&x(Cv[ke])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:Qe,noValidate:!0,children:[t.jsx("h4",{className:"settings-section-heading",children:l?"Edit Routine":"New Routine"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-name",children:"Name"}),t.jsx("input",{id:"routine-name",type:"text",placeholder:"e.g. Daily standup reminder",value:d,onChange:ke=>u(ke.target.value),"aria-invalid":!!$e.name,"aria-describedby":$e.name?vt:void 0}),$e.name&&t.jsx("small",{id:vt,className:"field-error",children:$e.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-description",children:"Description (optional)"}),t.jsx("textarea",{id:"routine-description",placeholder:"What does this routine do?",value:m,onChange:ke=>h(ke.target.value),rows:2})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Scope"}),t.jsxs("div",{className:"routine-scope-toggle",role:"radiogroup","aria-label":"Routine scope",children:[t.jsxs("button",{type:"button",className:`routine-scope-btn${de==="global"?" active":""}`,onClick:()=>{Ie("global"),o?.("global")},role:"radio","aria-checked":de==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(dc,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${de==="project"?" active":""}`,onClick:()=>{Ie("project"),o?.("project")},role:"radio","aria-checked":de==="project"?"true":"false",disabled:!!e?.scope||!r,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:r?"Project scope":"Select a project to enable project scope",children:[t.jsx(Es,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":de==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),$e.scope&&t.jsx("small",{className:"field-error",children:$e.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Trigger Type"}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":f==="cron",children:[t.jsx(qg,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":f==="webhook",children:[t.jsx(tb,{size:14}),"Webhook"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":f==="api",children:[t.jsx(Vg,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":f==="manual",children:[t.jsx(as,{size:14}),"Manual"]})]})]}),f==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:w,onChange:ke=>pt(ke.target.value),children:Object.entries(xD).map(([ke,tt])=>t.jsx("option",{value:ke,children:tt},ke))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:ke=>x(ke.target.value),disabled:w!=="custom","aria-invalid":!!$e.cronExpression,"aria-describedby":$e.cronExpression?Ae:void 0}),$e.cronExpression?t.jsx("small",{id:Ae,className:"field-error",children:$e.cronExpression}):t.jsx("small",{children:w==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${g}`})]}),f==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:ke=>S(ke.target.value),"aria-invalid":!!$e.webhookPath,"aria-describedby":$e.webhookPath?Je:void 0}),$e.webhookPath?t.jsx("small",{id:Je,className:"field-error",children:$e.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:j,onChange:ke=>C(ke.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),f==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:v,onChange:ke=>N(ke.target.value),"aria-invalid":!!$e.endpoint,"aria-describedby":$e.endpoint?dt:void 0}),$e.endpoint?t.jsx("small",{id:dt,className:"field-error",children:$e.endpoint}):t.jsx("small",{children:"API endpoint path that triggers this routine"})]}),f==="manual"&&t.jsx("div",{className:"form-group",children:t.jsx("small",{className:"routine-trigger-info",children:"This routine will be triggered manually via the dashboard or API."})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Mode"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action mode",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${K==="simple"?" active":""}`,onClick:()=>Z("simple"),role:"radio","aria-checked":K==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${K==="advanced"?" active":""}`,onClick:()=>Z("advanced"),role:"radio","aria-checked":K==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:K==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),K==="simple"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Type"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action type",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${ne==="command"?" active":""}`,onClick:()=>O("command"),role:"radio","aria-checked":ne==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${ne==="ai-prompt"?" active":""}`,onClick:()=>O("ai-prompt"),role:"radio","aria-checked":ne==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${ne==="create-task"?" active":""}`,onClick:()=>O("create-task"),role:"radio","aria-checked":ne==="create-task",children:"Create Task"})]})]}),ne==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:"Command"}),t.jsx("input",{id:"routine-command",type:"text",placeholder:"e.g. npx runfusion.ai backup --create",value:A,onChange:ke=>P(ke.target.value),"aria-invalid":!!$e.command,"aria-describedby":$e.command?Nt:void 0}),$e.command?t.jsx("small",{id:Nt,className:"field-error",children:$e.command}):t.jsx("small",{children:"Shell command to execute."})]}):ne==="ai-prompt"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-prompt",children:"Prompt"}),t.jsx("textarea",{id:"routine-prompt",placeholder:"e.g. Summarize recent activity and create action items",value:xe,onChange:ke=>Ne(ke.target.value),rows:3,"aria-invalid":!!$e.prompt,"aria-describedby":$e.prompt?yt:void 0}),$e.prompt?t.jsx("small",{id:yt,className:"field-error",children:$e.prompt}):t.jsx("small",{children:"AI prompt to execute."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-model",children:"Model (optional)"}),t.jsx(Is,{id:"routine-model",label:"Model",models:Fe,value:_e,onChange:xt,placeholder:"Use default",disabled:qe}),nt&&t.jsx("small",{className:"field-error",children:nt}),$e.model&&t.jsx("small",{id:G,className:"field-error",children:$e.model})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-title",children:"Task Title (optional)"}),t.jsx("input",{id:"routine-task-title",type:"text",placeholder:"e.g. Review weekly dependencies",value:Y,onChange:ke=>ie(ke.target.value)})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-description",children:"Task Description"}),t.jsx("textarea",{id:"routine-task-description",placeholder:"e.g. Check npm dependencies for security vulnerabilities",value:ee,onChange:ke=>oe(ke.target.value),rows:4,"aria-invalid":!!$e.taskDescription,"aria-describedby":$e.taskDescription?Se:void 0}),$e.taskDescription?t.jsx("small",{id:Se,className:"field-error",children:$e.taskDescription}):t.jsx("small",{children:"Describes the task that will be created."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-column",children:"Target Column"}),t.jsxs("select",{id:"routine-task-column",value:W,onChange:ke=>L(ke.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-model",children:"Executor Model (optional)"}),t.jsx(Is,{id:"routine-task-model",label:"Executor Model",models:Fe,value:_e,onChange:xt,placeholder:"Use default",disabled:qe}),nt&&t.jsx("small",{className:"field-error",children:nt}),$e.model&&t.jsx("small",{id:G,className:"field-error",children:$e.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(bD,{steps:$,onChange:k,onEditingChange:ce}),$e.steps&&t.jsx("small",{className:"field-error",children:$e.steps}),$e.stepsEditing&&t.jsx("small",{className:"field-error",children:$e.stepsEditing})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-timeout",children:"Timeout (ms)"}),t.jsx("input",{id:"routine-timeout",type:"number",min:1e3,step:1e3,value:je,onChange:ke=>He(Number(ke.target.value)),"aria-invalid":!!$e.timeoutMs,"aria-describedby":$e.timeoutMs?ge:void 0}),$e.timeoutMs?t.jsx("small",{id:ge,className:"field-error",children:$e.timeoutMs}):t.jsx("small",{children:"Maximum execution time in milliseconds."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:"Execution Policy"}),t.jsx("select",{id:"routine-execution-policy",value:I,onChange:ke=>F(ke.target.value),children:jD.map(ke=>t.jsx("option",{value:ke.value,children:ke.label},ke.value))}),t.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),t.jsx("select",{id:"routine-catchup-policy",value:_,onChange:ke=>M(ke.target.value),children:ND.map(ke=>t.jsx("option",{value:ke.value,children:ke.label},ke.value))}),t.jsx("small",{children:"What to do when a scheduled run is missed"})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"routine-enabled",className:"checkbox-label",children:[t.jsx("input",{id:"routine-enabled",type:"checkbox",checked:z,onChange:ke=>U(ke.target.checked)}),"Enabled"]}),t.jsx("small",{children:"When disabled, the routine will not run automatically"})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:Ue,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Ue,children:Ue?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const SD=3e4;function CD({onClose:e,addToast:n,projectId:s}){const[a,r]=i.useState(()=>s?"project":"global"),[o,l]=i.useState([]),[c,d]=i.useState("list"),[u,m]=i.useState(),[h,f]=i.useState(null),[p,g]=i.useState({}),x=i.useRef(null);Li(x,!0,"fusion:automation-modal-size");const w=i.useMemo(()=>({scope:a,projectId:a==="project"?s:void 0}),[a,s]),b=i.useCallback(async()=>{try{const R=await ES(w);l(R),g(D=>{const K={...D};for(const Z of R){const ne=K[Z.id];if(!ne||!Z.lastRunResult)continue;const O=Z.lastRunResult;O.success===ne.success&&(O.output||"")===ne.output&&(O.error||"")===(ne.error||"")&&delete K[Z.id]}return K})}catch(R){n(Ee(R)||"Failed to load routines","error")}},[n,w]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const R=setInterval(()=>{b()},SD);return()=>clearInterval(R)},[b]),i.useEffect(()=>{const R=D=>{D.key==="Escape"&&(c!=="list"?(d("list"),m(void 0)):e())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[e,c]);const y=Qi(e),S=i.useCallback(async R=>{try{await _S(R,w),n("Routine created","success"),d("list"),await b()}catch(D){n(Ee(D)||"Failed to create routine","error")}},[n,b,w]),j=i.useCallback(R=>{m(R),d("edit")},[]),C=i.useCallback(async R=>{if(u)try{await Km(u.id,R,w),n("Routine updated","success"),d("list"),m(void 0),await b()}catch(D){n(Ee(D)||"Failed to update routine","error")}},[u,n,b,w]),v=i.useCallback(async R=>{try{await MS(R.id,w),n(`Deleted "${R.name}"`,"success"),await b()}catch(D){n(Ee(D)||"Failed to delete routine","error")}},[n,b,w]),N=i.useCallback(async R=>{f(R.id);try{const{result:D}=await AS(R.id,w);g(K=>({...K,[R.id]:{output:D.output||"",error:D.error,success:D.success}})),D.success?n(`"${R.name}" completed successfully`,"success"):n(`"${R.name}" failed: ${D.error||"Unknown error"}`,"error"),await b()}catch(D){n(Ee(D)||"Failed to run routine","error")}finally{f(null)}},[n,b,w]),I=i.useCallback(async R=>{try{await Km(R.id,{enabled:!R.enabled},w),n(`"${R.name}" ${R.enabled?"disabled":"enabled"}`,"success"),await b()}catch(D){n(Ee(D)||"Failed to toggle routine","error")}},[n,b,w]),F=i.useCallback(()=>{d("list"),m(void 0)},[]);i.useEffect(()=>{c!=="list"&&g({})},[c]);const _=i.useCallback(R=>{r(R),d("list"),m(void 0),g({})},[]),M=()=>c==="create"?t.jsx(Kf,{onSubmit:S,onCancel:F,scope:a,projectId:s}):c==="edit"&&u?t.jsx(Kf,{routine:u,onSubmit:C,onCancel:F,scope:a,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(as,{size:48,strokeWidth:1}),t.jsx("h4",{children:"No automations yet"}),t.jsx("p",{children:"Create an automation with a schedule, webhook, API, or manual trigger."}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),children:[t.jsx(Mn,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(R=>t.jsx(hD,{routine:R,onEdit:j,onDelete:v,onRun:N,onToggle:I,running:h===R.id,lastRunOutput:p[R.id]??null},R.id))}),z=()=>M(),U=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:x,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(as,{size:20,className:"icon-triage"}),t.jsx("h3",{id:"schedules-modal-title",children:"Automations"})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(un,{size:20})})]}),t.jsxs("div",{className:"scheduling-toolbar","aria-live":"polite",children:[t.jsxs("div",{className:"scheduling-toolbar-left",role:"group","aria-label":"Scheduling scope",children:[t.jsxs("div",{className:"scheduling-scope-selector",children:[t.jsxs("button",{type:"button",className:`scope-btn${a==="global"?" active":""}`,onClick:()=>_("global"),"aria-pressed":a==="global",title:"Global (user-level) automations",children:[t.jsx(dc,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${a==="project"?" active":""}`,onClick:()=>_("project"),"aria-pressed":a==="project",title:"Project-scoped automations",children:[t.jsx(Es,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(as,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:U&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),"aria-label":"Create new automation",children:[t.jsx(Mn,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:z()})]})})}const ED=3e4,Cu=new Map,Fd=new Map;function Gf(e){return e??"default"}function Jf(e){const n=Cu.get(e);return n?Date.now()>=n.expiresAt?(Cu.delete(e),null):n:null}function _D(e,n){const s=e.some(r=>r.id!=="github"&&r.authenticated),a=e.some(r=>r.id==="github"&&r.authenticated)||(n?.authenticated??!1);return{hasAiProvider:s,hasGithub:a}}async function MD(e){const n=Fd.get(e);if(n)return n;const s=Eo().then(({providers:a,ghCli:r})=>{const l={..._D(a,r),ghCli:r,expiresAt:Date.now()+ED};return Cu.set(e,l),l}).finally(()=>{Fd.delete(e)});return Fd.set(e,s),s}function Ev(e){const n=Gf(e),s=Jf(n),[a,r]=i.useState(s?.hasAiProvider??!1),[o,l]=i.useState(s?.hasGithub??!1),[,c]=i.useState(s?.ghCli),[d,u]=i.useState(s==null),m=i.useRef(!!s);return i.useEffect(()=>{let h=!1;const f=Gf(e),p=Jf(f);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),u(!1),m.current=!0,()=>{h=!0};m.current=!1;async function g(){!m.current&&u(!0);try{const w=await MD(f);if(h)return;r(w.hasAiProvider),l(w.hasGithub),c(w.ghCli)}catch{}finally{h||(m.current=!0,u(!1))}}return g(),()=>{h=!0}},[e]),i.useMemo(()=>({hasAiProvider:a,hasGithub:o,loading:d,hasWarnings:!a||!o}),[a,o,d])}function _v({hasAiProvider:e,hasGithub:n,compact:s=!1,onDismiss:a}){if(e&&n)return null;const r=a?t.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":"Dismiss setup warning",onClick:a,children:t.jsx(un,{size:16,"aria-hidden":"true"})}):null;if(s)return t.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${a?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[t.jsx("p",{className:"setup-warning-banner__compact-text",children:"⚠ Setup incomplete — AI and/or GitHub features will be limited."}),r]});const o=[];return e||o.push({key:"ai",title:"No AI provider connected",description:"AI agents won't be able to work on tasks until you connect a provider. Set one up in Settings → AI Setup."}),n||o.push({key:"github",title:"GitHub not connected",description:"You won't be able to import issues from GitHub, but you can still create tasks manually."}),t.jsxs("div",{className:`setup-warning-banner${a?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[r,o.map(l=>t.jsxs("div",{className:"setup-warning-banner__item",children:[t.jsx("strong",{className:"setup-warning-banner__title",children:l.title}),t.jsx("p",{className:"setup-warning-banner__description",children:l.description})]},l.key))]})}function AD({isOpen:e,onClose:n,projectId:s,tasks:a,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:d}=pi(),u=ri();Ni(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=Zi({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[x,w]=i.useState(""),[b,y]=i.useState([]),[S,j]=i.useState(""),[C,v]=i.useState(""),[N,I]=i.useState([]),[F,_]=i.useState(!1),[M,z]=i.useState(""),[U,R]=i.useState(""),[D,K]=i.useState(""),[Z,ne]=i.useState(""),[O,A]=i.useState(""),[P,$]=i.useState("default"),[k,J]=i.useState(!1),[ce,je]=i.useState([]),[He,xe]=i.useState(!1),[Ne,Y]=i.useState(void 0),[ie,ee]=i.useState(Ls),[oe,W]=i.useState(void 0),[L,pe]=i.useState(!1),[fe,B]=i.useState(""),[ve,Fe]=i.useState(null),[ae,qe]=i.useState([]),[Pe,nt]=i.useState(!1),[Be,de]=i.useState(!1),Ie=i.useRef(null),[$e,st]=i.useState(!1),[Ue,me]=i.useState(""),re=i.useRef(null),{hasAiProvider:_e,hasGithub:xt,loading:ut}=Ev(s),{nodes:Qe}=yc(),vt=i.useCallback(be=>{xe(!0),je(be)},[]),Ae=i.useCallback(()=>{xe(!1)},[]),Je=i.useCallback(async()=>{if(ae.length>0){nt(!0);return}de(!0);try{const be=await $r(void 0,s);qe(be),nt(!0)}catch(be){const rt=Ee(be);o(rt?`Failed to load agents: ${rt}`:"Failed to load agents","error"),nt(!1)}finally{de(!1)}},[ae.length,s,o]);i.useEffect(()=>{if(!Pe)return;const be=rt=>{Ie.current&&!Ie.current.contains(rt.target)&&nt(!1)};return document.addEventListener("mousedown",be),()=>document.removeEventListener("mousedown",be)},[Pe]),i.useEffect(()=>{if(!$e)return;const be=rt=>{re.current&&!re.current.contains(rt.target)&&(st(!1),me(""))};return document.addEventListener("mousedown",be),()=>document.removeEventListener("mousedown",be)},[$e]);const dt=a.filter(be=>!b.includes(be.id)).sort((be,rt)=>{const lt=rt.createdAt.localeCompare(be.createdAt);if(lt!==0)return lt;const gt=parseInt(be.id.slice(be.id.lastIndexOf("-")+1),10)||0;return(parseInt(rt.id.slice(rt.id.lastIndexOf("-")+1),10)||0)-gt}),Nt=Ue?dt.filter(be=>be.id.toLowerCase().includes(Ue.toLowerCase())||be.title&&be.title.toLowerCase().includes(Ue.toLowerCase())||be.description&&be.description.toLowerCase().includes(Ue.toLowerCase())):dt,yt=(be,rt)=>be.length>rt?be.slice(0,rt)+"…":be,Se=fe.trim(),G=Se.length>0&&!vc.test(Se);i.useEffect(()=>{const be=x.trim()!==""||b.length>0||N.length>0||M!==""||U!==""||D!==""||Z!==""||ce.length>0||ve!==null||Ne!==void 0||ie!==Ls||oe!==void 0||S!==""||C!==""||L||Se!=="";J(be)},[x,b,N,M,U,D,Z,ce,ve,Ne,ie,oe,S,C,L,Se]);const ge=i.useCallback(async()=>{k&&!await d({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(N.forEach(be=>URL.revokeObjectURL(be.previewUrl)),I([]),w(""),y([]),z(""),R(""),K(""),ne(""),A(""),$("default"),je([]),xe(!1),Fe(null),nt(!1),Y(void 0),ee(Ls),W(void 0),j(""),v(""),J(!1),pe(!1),B(""),n())},[k,n,N,d]),pt=i.useCallback(async()=>{const be=x.trim();if(!(!be||F||G)){_(!0);try{const rt=M.indexOf("/"),lt=U.indexOf("/"),gt=D.indexOf("/"),St=await r({title:void 0,description:be,column:"triage",dependencies:b.length?b:void 0,enabledWorkflowSteps:He?ce.length>0?ce:[]:void 0,...ve?{assignedAgentId:ve}:{},modelPresetId:P==="preset"&&O||void 0,modelProvider:M&&rt!==-1?M.slice(0,rt):void 0,modelId:M&&rt!==-1?M.slice(rt+1):void 0,validatorModelProvider:U&&lt!==-1?U.slice(0,lt):void 0,validatorModelId:U&&lt!==-1?U.slice(lt+1):void 0,planningModelProvider:D&&gt!==-1?D.slice(0,gt):void 0,planningModelId:D&&gt!==-1?D.slice(gt+1):void 0,thinkingLevel:Z!==""?Z:void 0,reviewLevel:Ne,priority:ie,nodeId:oe,branch:S.trim()===""?void 0:S.trim(),baseBranch:C.trim()===""?void 0:C.trim(),...L||Se!==""?{githubTracking:{enabled:L,...Se!==""?{repoOverride:Se}:{}}}:{}});if(N.length>0){const Lt=[];for(const Yt of N)try{await bc(St.id,Yt.file,s)}catch{Lt.push(Yt.file.name)}Lt.length>0&&o(`Failed to upload: ${Lt.join(", ")}`,"error")}N.forEach(Lt=>URL.revokeObjectURL(Lt.previewUrl)),I([]),w(""),y([]),z(""),R(""),K(""),ne(""),A(""),$("default"),je([]),xe(!1),Fe(null),nt(!1),Y(void 0),ee(Ls),W(void 0),j(""),v(""),o(`Created ${St.id}`,"success"),n()}catch(rt){o(Ee(rt)||"Failed to create task","error")}finally{_(!1)}}},[x,b,N,M,U,D,Z,F,r,o,n,s,P,O,ce,He,ve,Ne,ie,oe,S,C]),ke=i.useCallback(be=>{be.key==="Escape"&&(be.preventDefault(),ge())},[ge]),Rt=(ve?ae.find(be=>be.id===ve):void 0)?.name??ve,Re=t.jsxs("div",{className:"new-task-quick-fields",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"dep-trigger-wrap",ref:re,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>st(be=>!be),disabled:F,"data-testid":"dep-trigger",children:b.length>0?`${b.length} selected`:"Add dependencies"}),$e&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ue,onChange:be=>me(be.target.value),onClick:be=>be.stopPropagation()}),Nt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Nt.map(be=>t.jsxs("div",{className:`dep-dropdown-item${b.includes(be.id)?" selected":""}`,onClick:()=>{y(b.includes(be.id)?b.filter(rt=>rt!==be.id):[...b,be.id]),st(!1),me("")},onMouseDown:rt=>rt.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:be.id}),t.jsx("span",{className:"dep-dropdown-title",children:yt(be.title||be.description||be.id,30)})]},be.id))]})]}),b.length>0&&t.jsx("div",{className:"selected-deps",children:b.map(be=>t.jsxs("span",{className:"dep-chip",children:[be,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>y(b.filter(rt=>rt!==be)),disabled:F,children:"×"})]},be))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:Ie,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{Pe?nt(!1):Je()},disabled:F,"data-testid":"new-task-agent-button",children:[t.jsx(Kn,{size:12,style:{verticalAlign:"middle"}}),Rt?` ${Rt}`:" Assign agent"]}),Pe&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:be=>be.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Be&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Be&&ae.map(be=>t.jsxs("div",{className:`dep-dropdown-item${ve===be.id?" selected":""}`,onMouseDown:rt=>rt.preventDefault(),onClick:()=>{Fe(be.id===ve?null:be.id),nt(!1)},"data-testid":`agent-option-${be.id}`,children:[t.jsx(Kn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:be.role}),t.jsx("span",{className:"dep-dropdown-title",children:be.name})]},be.id)),!Be&&ae.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),ve&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:be=>be.preventDefault(),onClick:()=>{Fe(null),nt(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:ge,onKeyDown:ke,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:be=>be.stopPropagation(),style:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:ge,disabled:F,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!ut&&t.jsx(_v,{hasAiProvider:_e,hasGithub:xt}),t.jsx(lv,{mode:"create",description:x,onDescriptionChange:w,dependencies:b,onDependenciesChange:y,executorModel:M,onExecutorModelChange:z,validatorModel:U,onValidatorModelChange:R,presetMode:P,onPresetModeChange:$,selectedPresetId:O,onSelectedPresetIdChange:A,selectedWorkflowSteps:ce,onWorkflowStepsChange:vt,onDefaultOnApplied:Ae,pendingImages:N,onImagesChange:I,tasks:a,projectId:s,disabled:F,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:ge,planningModel:D,onPlanningModelChange:K,thinkingLevel:Z,onThinkingLevelChange:ne,reviewLevel:Ne,onReviewLevelChange:Y,priority:ie,onPriorityChange:ee,branch:S,onBranchChange:j,baseBranch:C,onBaseBranchChange:v,nodeId:oe,onNodeIdChange:W,nodeOptions:Qe,githubTrackingEnabled:L,onGithubTrackingEnabledChange:pe,githubRepoOverride:fe,onGithubRepoOverrideChange:B,renderBelowPrimary:Re,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:ge,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:pt,disabled:!x.trim()||F||G,children:F?"Creating...":"Create Task"})]})]})}):null}function bi(e){if(!Number.isFinite(e)||e<0)return"—";const n=e/(1024*1024);return n<1024?`${n.toFixed(0)} MB`:`${(n/1024).toFixed(2)} GB`}function Yf(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function RD(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function ID(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function TD(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function PD(e,n){if(e===null||!Number.isFinite(e)||e<0)return"normal";const s=n>0?e/n:e;return s>=80?"critical":s>=50?"warning":"normal"}function _l(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function $D(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function DD({isOpen:e,onClose:n,projectId:s}){const[a,r]=i.useState(null),[o,l]=i.useState(!1),[c,d]=i.useState(null),[u,m]=i.useState(!0),[h,f]=i.useState(90),[p,g]=i.useState(!1),[x,w]=i.useState(!1),[b,y]=i.useState(null),[S,j]=i.useState(null),[C,v]=i.useState(null),N=i.useCallback(async Y=>{l(!0);try{const ie=await u1(s);r(ie),d(null),v(Date.now()),Y?.preserveKillResult||y(null)}catch(ie){d(ie instanceof Error?ie.message:"Failed to load system stats")}finally{l(!1)}},[s]);i.useEffect(()=>{if(!e)return;N();const Y=window.setInterval(()=>{N()},5e3);return()=>{window.clearInterval(Y)}},[e,N]),i.useEffect(()=>{if(!e)return;(async()=>{try{const ie=await Yi();m(ie.vitestAutoKillEnabled??!0),f(ie.vitestKillThresholdPct??90),j(null)}catch(ie){j(ie instanceof Error?ie.message:"Failed to load vitest settings")}})()},[e]),i.useEffect(()=>{if(!e)return;const Y=ie=>{ie.key==="Escape"&&n()};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[e,n]);const I=i.useMemo(()=>{if(!a)return[];const Y=a.systemStats,ie=_l(RD(Y.heapUsed,Y.heapLimit)),ee=_l(ID(Y.rss,Y.systemTotalMem));return[{label:"RSS",value:bi(Y.rss),detail:Yf(Y.rss,Y.systemTotalMem),className:ee},{label:"Heap Used",value:bi(Y.heapUsed),detail:`of ${bi(Y.heapTotal)}`,className:ie},{label:"Heap Limit",value:bi(Y.heapLimit),detail:"V8 limit"},{label:"External",value:bi(Y.external)},{label:"Array Buffers",value:bi(Y.arrayBuffers)}]},[a]),F=i.useCallback(async Y=>{m(Y);try{await Dn({vitestAutoKillEnabled:Y}),j(null)}catch(ie){j(ie instanceof Error?ie.message:"Failed to save vitest settings")}},[]),_=i.useCallback(async Y=>{const ie=Math.min(99,Math.max(50,Number.isFinite(Y)?Math.round(Y):90));f(ie);try{await Dn({vitestKillThresholdPct:ie}),j(null)}catch(ee){j(ee instanceof Error?ee.message:"Failed to save vitest settings")}},[]),M=i.useCallback(async()=>{if(!p){if(!x){w(!0);return}g(!0);try{const Y=await m1(s);y(Y),w(!1),await N({preserveKillResult:!0})}catch(Y){d(Y instanceof Error?Y.message:"Failed to kill vitest processes")}finally{g(!1)}}},[x,p,N,s]);if(!e)return null;const z=a?.systemStats,U=o&&!!a,R=C?`Updated ${new Date(C).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",D=a?.taskStats,K=z?z.systemTotalMem-z.systemFreeMem:0,Z=z?TD(K,z.systemTotalMem):"normal",ne=z?_l(Z):"",O=z&&Number.isFinite(z.systemTotalMem)&&z.systemTotalMem>0?Math.max(0,Math.min(100,K/z.systemTotalMem*100)):0,A=z?`System memory used: ${O.toFixed(1)}% (${bi(K)} of ${bi(z.systemTotalMem)})`:"System memory usage unavailable",P=a?.vitestProcessCount,$=PD(z?.cpuPercent??null,z?.cpuCount??0),k=_l($),J=z?.cpuPercent??null,ce=J===null?0:Math.max(0,Math.min(100,J)),je=J===null?"Sampling…":`${J.toFixed(1)}%`,He=J===null?"App CPU usage unavailable: waiting for another sample":`App CPU usage: ${J.toFixed(1)}%`,xe=b?b.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",Ne=$D(a?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:Y=>{Y.target===Y.currentTarget&&n()},"data-testid":"system-stats-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg system-stats-modal","data-testid":"system-stats-modal",children:[t.jsxs("div",{className:"modal-header system-stats-modal__header",children:[t.jsxs("h2",{id:"system-stats-modal-title",className:"system-stats-modal__title",children:[t.jsx(yr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("div",{className:"system-stats-modal__header-actions",children:[t.jsxs("span",{className:"system-stats-modal__auto-refresh","aria-live":"polite",children:[t.jsx("span",{children:"Auto-refresh · 5s"}),t.jsx("span",{className:"system-stats-modal__auto-refresh-time",children:R})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void N(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(bs,{size:16,className:U?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(un,{})})]})]}),o&&!a&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!a&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),a&&t.jsxs("div",{className:"system-stats-modal__content",children:[t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Process stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Process"}),t.jsx("dl",{className:"system-stats-modal__grid",children:I.map(Y=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:Y.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${Y.className}`.trim(),children:Y.value}),Y.detail?t.jsx("span",{className:"system-stats-modal__detail",children:Y.detail}):null]})]},Y.label))})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"CPU and load stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"CPU & Load"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--cpu-used",children:[t.jsx("dt",{children:"App CPU"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${k}`.trim(),children:je}),t.jsx("span",{className:"system-stats-modal__detail",children:J===null?"First sample pending":"process usage"})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${$}`,role:"progressbar","aria-valuenow":Math.round(ce),"aria-valuemin":0,"aria-valuemax":100,"aria-label":He,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${$}`,style:{width:`${ce}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:z?.loadAvg.map(Y=>Y.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:z?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:z?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:z?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:z?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"System memory stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"System"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--memory-used",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${ne}`.trim(),children:z?bi(K):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:z?`${Yf(K,z.systemTotalMem)} of ${bi(z.systemTotalMem)}`:""})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${Z}`,role:"progressbar","aria-valuenow":Math.round(O),"aria-valuemin":0,"aria-valuemax":100,"aria-label":A,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${Z}`,style:{width:`${O}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:z?bi(z.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Task stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Tasks"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Total"}),t.jsx("dd",{children:D?.total??0})]}),Object.entries(D?.byColumn??{}).map(([Y,ie])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:Y}),t.jsx("dd",{children:ie})]},Y))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Agent stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Agents"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"idle"}),t.jsx("dd",{children:D?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:D?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:D?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:D?.agents.error??0})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Vitest controls",children:[t.jsxs("h3",{className:"system-stats-modal__section-title system-stats-modal__section-title--with-icon",children:[t.jsx(Lk,{}),t.jsx("span",{children:"Vitest Controls"})]}),t.jsx("dl",{className:"system-stats-modal__grid system-stats-modal__vitest-controls",children:t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Vitest Processes"}),t.jsx("dd",{children:P??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void M(),disabled:p||P===0,children:[t.jsx(Bk,{}),t.jsx("span",{children:x?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:u,onChange:Y=>{F(Y.target.checked)}}),t.jsx("span",{children:"Auto-kill vitest on memory pressure"})]}),t.jsxs("div",{className:"system-stats-modal__threshold-row",children:[t.jsx("label",{htmlFor:"vitest-threshold-number",children:"Kill threshold (%)"}),t.jsxs("div",{className:"system-stats-modal__threshold-controls",children:[t.jsx("input",{id:"vitest-threshold-range",type:"range",min:50,max:99,value:h,"aria-label":"Kill threshold slider (%)",onChange:Y=>{const ie=Number.parseInt(Y.target.value,10);_(Number.isNaN(ie)?90:ie)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:Y=>{const ie=Number.parseInt(Y.target.value,10);_(Number.isNaN(ie)?90:ie)},onBlur:()=>{_(h)}})]})]}),b&&t.jsxs("p",{className:xe,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",Ne]}),S&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:S})]})]})]}),c&&a&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const LD=5e3;function OD(e={}){const{projectId:n,type:s,limit:a=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=i.useState([]),[d,u]=i.useState(!1),[m,h]=i.useState(null),[f,p]=i.useState(!1),g=i.useRef(null),x=i.useRef(void 0),w=i.useCallback(async()=>{try{u(!0),h(null);let S;o?S=await th({limit:a,projectId:n,type:s}):S=(await Gm({limit:a,type:s,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(S),p(S.length===a),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load activity log")}finally{u(!1)}},[a,n,s,o]),b=i.useCallback(async()=>{if(x.current)try{u(!0);let S;o?S=await th({limit:a,projectId:n,type:s,since:x.current}):S=(await Gm({limit:a,type:s,since:x.current,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(j=>[...j,...S]),p(S.length===a),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load more entries")}finally{u(!1)}},[a,n,s,o]),y=i.useCallback(()=>{c([]),p(!1),x.current=void 0},[]);return i.useEffect(()=>{w()},[w]),i.useEffect(()=>{if(r)return g.current=setInterval(()=>{w()},LD),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,w]),{entries:l,loading:d,error:m,refresh:w,clear:y,hasMore:f,loadMore:b}}const zd={"task:created":"Task Created","task:moved":"Task Moved","task:updated":"Task Updated","task:deleted":"Task Deleted","task:merged":"Task Merged","task:failed":"Task Failed","settings:updated":"Settings Updated"},FD={"task:created":t.jsx(Mn,{size:14,className:"activity-icon created"}),"task:moved":t.jsx($o,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(bs,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(un,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Gn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Do,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(vo,{size:14,className:"activity-icon settings"})};function zD(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function BD({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:a,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[d,u]=i.useState("all"),[m,h]=i.useState(r||"all"),[f,p]=i.useState(!1);i.useEffect(()=>{h(r||"all")},[r]);const g=d==="all"?void 0:d,x=m==="all"?void 0:m,w=!c&&o.length>0,{entries:b,loading:y,error:S,refresh:j,hasMore:C}=OD({projectId:x,type:g,limit:100,autoRefresh:e,useCentralFeed:w}),v=b.map(M=>({id:M.id,timestamp:M.timestamp,type:M.type,taskId:M.taskId,taskTitle:M.taskTitle,details:M.details,metadata:M.metadata,projectId:M.projectId,projectName:M.projectName})),N=async()=>{try{await RS(),j(),p(!1)}catch{p(!1)}},I=M=>{a&&a(M)},F=M=>{h(M),l?.(M==="all"?void 0:M)};i.useEffect(()=>{if(!e)return;const M=z=>{z.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",M),()=>document.removeEventListener("keydown",M)},[e,n,f]);const _=d!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:M=>{M.target===M.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(Pa,{size:18}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("div",{className:"activity-log-actions",children:[o.length>0&&t.jsxs("div",{className:"activity-log-filter activity-log-filter--project",children:[t.jsx(Es,{size:14}),t.jsxs("select",{value:m,onChange:M=>F(M.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(M=>t.jsx("option",{value:M.id,children:M.name},M.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(Fl,{size:14}),t.jsxs("select",{value:d,onChange:M=>u(M.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(zd).map(([M,z])=>t.jsx("option",{value:M,children:z},M))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>j(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(jt,{size:14,className:"spin"}):t.jsx(bs,{size:14})}),v.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(_n,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),_&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(M=>M.id===m)?.name||m]}),d!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",zd[d]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear all"})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[S&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(Ws,{size:16}),t.jsx("span",{children:S})]}),v.length===0&&!y&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Pa,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:_?"No activity matches the current filters":"No activity recorded yet"}),_&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:v.map(M=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:FD[M.type]}),t.jsxs("div",{className:"activity-log-entry-content",children:[t.jsxs("div",{className:"activity-log-entry-header",children:[t.jsx("span",{className:"activity-log-entry-type",children:zd[M.type]}),t.jsx("span",{className:"activity-log-entry-time",children:zD(M.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[M.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>I(M.taskId),"data-testid":"activity-task-link",children:M.taskId}),M.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:M.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:M.details})]}),M.metadata&&Object.keys(M.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof M.metadata.from=="string"&&typeof M.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[M.metadata.from," → ",M.metadata.to]}),typeof M.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${M.metadata.merged?"success":"error"}`,children:M.metadata.merged?"Merged":"Not merged"})]})]})]},M.id))}),C&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:j,"data-testid":"activity-load-more",children:"Load More"}),y&&v.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(jt,{size:20,className:"spin"})})]}),f&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:N,children:"Clear Log"})]})]})})]})}):null}const ao=[{id:"status",label:"Status",icon:Zg},{id:"changes",label:"Changes",icon:Qd},{id:"commits",label:"Commits",icon:xr},{id:"branches",label:"Branches",icon:Fs},{id:"worktrees",label:"Worktrees",icon:Tw},{id:"stashes",label:"Stashes",icon:To},{id:"remotes",label:"Remotes",icon:Yg}];function Qf({status:e}){switch(e){case"added":case"untracked":return t.jsx(mw,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Gg,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(cw,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(ua,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(pw,{size:14,className:"gm-file-icon"})}}function Xf({status:e}){const n=e==="untracked"?"U":e==="added"?"A":e==="modified"?"M":e==="deleted"?"D":e==="renamed"?"R":e==="copied"?"C":"?";return t.jsx("span",{className:`gm-file-badge gm-file-badge-${e}`,children:n})}function UD(e){return i.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),e(`Copied ${s||"to clipboard"}`,"success")}catch{e("Failed to copy","error")}},[e])}function Er(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const o=Math.floor(r/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);return l<30?`${l}d ago`:n.toLocaleDateString()}function HD({isOpen:e,onClose:n,tasks:s,addToast:a,projectId:r}){const o=pi(),l=ri();Ni(e);const{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=Zi({enabled:l==="mobile"}),h=m?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{},f=i.useCallback(()=>{if(l==="mobile"){const te=document.activeElement;te instanceof HTMLElement&&te.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})}n()},[n,l]),[p,g]=i.useState("status"),[x,w]=i.useState(!1),[b,y]=i.useState(null),S=i.useRef(null);Li(S,e,"fusion:git-modal-size");const j=Qi(f),C=UD(a),[v,N]=i.useState(null),[I,F]=i.useState([]),[_,M]=i.useState(new Set),[z,U]=i.useState(""),[R,D]=i.useState(!1),[K,Z]=i.useState(null),[ne,O]=i.useState(!1),[A,P]=i.useState(null),[$,k]=i.useState(null),J=i.useRef(0),[ce,je]=i.useState([]),[He,xe]=i.useState(null),[Ne,Y]=i.useState(null),[ie,ee]=i.useState(!1),[oe,W]=i.useState(20),[L,pe]=i.useState(""),[fe,B]=i.useState([]),[ve,Fe]=i.useState(""),[ae,qe]=i.useState(""),[Pe,nt]=i.useState(""),[Be,de]=i.useState(null),[Ie,$e]=i.useState([]),[st,Ue]=i.useState(!1),[me,re]=i.useState(null),[_e,xt]=i.useState(null),[ut,Qe]=i.useState(!1),[vt,Ae]=i.useState([]),[Je,dt]=i.useState([]),[Nt,yt]=i.useState(""),[Se,G]=i.useState(null),[ge,pt]=i.useState(null),[ke,tt]=i.useState(null),[Rt,Re]=i.useState(!1),[be,rt]=i.useState(null),lt=i.useRef(0),[gt,St]=i.useState(null),[Lt,Yt]=i.useState(null),tn=i.useCallback(async()=>{if(e){w(!0),y(null);try{switch(p){case"status":{const te=await gi(r);N(te);break}case"changes":{const[te,De]=await Promise.all([gi(r),sr(r)]);N(te),F(De),M(new Set),k(null),Z(null),P(null);break}case"commits":{const te=await PN(oe,r);je(te);break}case"branches":{const[te,De]=await Promise.all([Vr(r),gi(r)]);B(te),N(De);break}case"worktrees":{const te=await ON(r);Ae(te);break}case"stashes":{const te=await el(r);dt(te),pt(null),tt(null),rt(null),lt.current+=1;break}case"remotes":{const te=await gi(r);N(te);break}}}catch(te){y(Ee(te)||"Failed to fetch git data"),a(Ee(te)||"Failed to fetch git data","error")}finally{w(!1)}}},[p,e,oe,a,r]);i.useEffect(()=>{e&&tn()},[tn,e]),i.useEffect(()=>{if(!e)return;const te=De=>{if(De.key==="Escape"){f();return}if((De.key==="ArrowUp"||De.key==="ArrowDown")&&De.altKey){De.preventDefault();const ft=ao.findIndex(qt=>qt.id===p);De.key==="ArrowUp"&&ft>0?g(ao[ft-1].id):De.key==="ArrowDown"&&ft<ao.length-1&&g(ao[ft+1].id)}};return document.addEventListener("keydown",te),()=>document.removeEventListener("keydown",te)},[e,f,p]);const mn=i.useCallback(async te=>{try{await Um(te,r),a(`Staged ${te.length} file(s)`,"success");const De=await sr(r);F(De),M(new Set),k(null),Z(null),P(null)}catch(De){a(Ee(De)||"Failed to stage files","error")}},[a,r]),Qt=i.useCallback(async te=>{try{await JN(te,r),a(`Unstaged ${te.length} file(s)`,"success");const De=await sr(r);F(De),M(new Set),k(null),Z(null),P(null)}catch(De){a(Ee(De)||"Failed to unstage files","error")}},[a,r]),yn=i.useCallback(async te=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${te.length} file(s)? This cannot be undone.`,danger:!0}))try{await YN(te,r),a(`Discarded changes to ${te.length} file(s)`,"success");const[ft,qt]=await Promise.all([sr(r),gi(r)]);F(ft),N(qt),M(new Set),k(null),Z(null),P(null)}catch(ft){a(Ee(ft)||"Failed to discard changes","error")}},[a,r,o]),Gt=i.useCallback(async te=>{if(te.preventDefault(),!!z.trim()){D(!0);try{const De=await Hm(z.trim(),r);a(`Committed: ${De.hash}`,"success"),U("");const[ft,qt]=await Promise.all([sr(r),gi(r)]);F(ft),N(qt),k(null),Z(null),P(null)}catch(De){a(Ee(De)||"Failed to commit","error")}finally{D(!1)}}},[z,a,r]),on=i.useCallback(async()=>{if(z.trim()){D(!0);try{const te=I.filter(zt=>!zt.staged).map(zt=>zt.file);te.length>0&&await Um(te,r);const De=await Hm(z.trim(),r);a(`Committed: ${De.hash}`,"success"),U("");const[ft,qt]=await Promise.all([sr(r),gi(r)]);F(ft),N(qt),k(null),Z(null),P(null)}catch(te){a(Ee(te)||"Failed to commit","error")}finally{D(!1)}}},[z,I,a,r]),sn=i.useCallback(async(te,De)=>{k({file:te,staged:De}),O(!0),P(null);const ft=J.current+1;J.current=ft;try{const qt=await GN(te,De,r);if(J.current!==ft)return;Z(qt)}catch(qt){if(J.current!==ft)return;const zt=Ee(qt)||"Failed to load file diff";Z(null),P(zt),a(zt,"error")}finally{J.current===ft&&O(!1)}},[a,r]),ln=i.useCallback(te=>{M(De=>{const ft=new Set(De);return ft.has(te)?ft.delete(te):ft.add(te),ft})},[]),Wt=i.useCallback(async te=>{if(He===te){xe(null),Y(null);return}xe(te),ee(!0);try{const De=await Hl(te,r);Y(De)}catch(De){a(Ee(De)||"Failed to load diff","error"),Y(null)}finally{ee(!1)}},[He,a,r]),ye=i.useCallback(()=>{W(te=>Math.min(te+20,100))},[]),Le=i.useMemo(()=>{if(!L.trim())return ce;const te=L.toLowerCase();return ce.filter(De=>De.message.toLowerCase().includes(te)||De.author.toLowerCase().includes(te)||De.shortHash.toLowerCase().includes(te))},[ce,L]),Ke=i.useCallback(async te=>{if(te.preventDefault(),!!ve.trim()){w(!0);try{await FN(ve.trim(),ae.trim()||void 0,r),a(`Created branch ${ve}`,"success"),Fe(""),qe("");const De=await Vr(r);B(De)}catch(De){a(Ee(De)||"Failed to create branch","error")}finally{w(!1)}}},[ve,ae,a,r]),mt=i.useCallback(async te=>{w(!0);try{await zN(te,r),a(`Switched to ${te}`,"success");const[De,ft]=await Promise.all([gi(r),Vr(r)]);N(De),B(ft)}catch(De){a(Ee(De)||"Failed to checkout branch","error")}finally{w(!1)}},[a,r]),Ve=i.useCallback(async te=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${te}"?`,danger:!0})){w(!0);try{await Bm(te,void 0,r),a(`Deleted branch ${te}`,"success");const ft=await Vr(r);B(ft)}catch(ft){if(Ee(ft).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Bm(te,!0,r),a(`Force deleted branch ${te}`,"success");const zt=await Vr(r);B(zt)}catch(zt){a(Ee(zt)||"Failed to delete branch","error")}}else a(Ee(ft)||"Failed to delete branch","error")}finally{w(!1)}}},[a,r,o]),Pt=i.useMemo(()=>{if(!Pe.trim())return fe;const te=Pe.toLowerCase();return fe.filter(De=>De.name.toLowerCase().includes(te))},[fe,Pe]),Ot=i.useCallback(async te=>{if(Be===te){de(null),$e([]),re(null),xt(null);return}de(te),$e([]),re(null),xt(null),Ue(!0);try{const De=await LN(te,10,r);$e(De)}catch{$e([])}finally{Ue(!1)}},[Be,r]),bt=i.useCallback(async te=>{if(me===te){re(null),xt(null);return}re(te),xt(null),Qe(!0);try{const De=await Hl(te,r);xt(De)}catch{xt(null)}finally{Qe(!1)}},[me,r]),Dt=i.useCallback(()=>{de(null),$e([]),re(null),xt(null)},[]),Ft=i.useCallback(()=>{lt.current+=1,pt(null),tt(null),rt(null),Re(!1)},[]),Ht=i.useCallback(async te=>{te.preventDefault(),G("create"),Ft();try{await qN(Nt.trim()||void 0,r),a("Changes stashed","success"),yt("");const De=await el(r);dt(De)}catch(De){a(Ee(De)||"Failed to stash changes","error")}finally{G(null)}},[Nt,a,r,Ft]),rn=i.useCallback(async(te,De=!1)=>{G(`apply-${te}`),Ft();try{await VN(te,De,r),a(De?"Stash popped":"Stash applied","success");const ft=await el(r);dt(ft)}catch(ft){a(Ee(ft)||"Failed to apply stash","error")}finally{G(null)}},[a,r,Ft]),Xt=i.useCallback(async te=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${te}}? This cannot be undone.`,danger:!0})){G(`drop-${te}`),Ft();try{await WN(te,r),a("Stash dropped","success");const ft=await el(r);dt(ft)}catch(ft){a(Ee(ft)||"Failed to drop stash","error")}finally{G(null)}}},[a,r,o,Ft]),an=i.useCallback(async te=>{if(ge===te){Ft();return}const De=lt.current+1;lt.current=De,pt(te),tt(null),rt(null),Re(!0);try{const ft=await KN(te,r);if(lt.current!==De)return;tt(ft)}catch(ft){if(lt.current!==De)return;tt(null),rt(Ee(ft)||"Failed to load stash diff")}finally{lt.current===De&&Re(!1)}},[ge,r,Ft]),Me=i.useCallback(async()=>{St("fetch");try{const te=await BN(void 0,r);Yt(te),a(te.message||"Fetch completed",te.fetched?"success":"info");const De=await gi(r);N(De)}catch(te){a(Ee(te)||"Fetch failed","error")}finally{St(null)}},[a,r]),it=i.useCallback(async te=>{St("pull");try{const De=await UN(te,r);if(Yt(De),De.conflict)a("Merge conflict detected. Resolve manually.","error");else{const qt=te?.rebase?"Pull --rebase completed":"Pull completed";a(De.message||qt,"success")}const ft=await gi(r);N(ft)}catch(De){a(Ee(De)||"Pull failed","error")}finally{St(null)}},[a,r]),kt=i.useCallback(async()=>{St("push");try{const te=await HN(r);Yt(te),a(te.message||"Push completed","success");const De=await gi(r);N(De)}catch(te){a(Ee(te)||"Push failed","error")}finally{St(null)}},[a,r]),$t=i.useMemo(()=>I.filter(te=>te.staged),[I]),se=i.useMemo(()=>I.filter(te=>!te.staged),[I]);return e?t.jsx("div",{className:"modal-overlay open git-manager-modal-overlay",...j,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:S,style:h,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(Xd,{size:18,style:{marginRight:8,verticalAlign:"middle"}}),"Git Manager"]}),t.jsxs("div",{className:"gm-header-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:tn,disabled:x,title:"Refresh",children:t.jsx(bs,{size:14,className:x?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:f,"aria-label":"Close",children:t.jsx(un,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:ao.map(te=>{const De=te.icon;return t.jsxs("button",{role:"tab","aria-selected":p===te.id,className:`gm-nav-item${p===te.id?" active":""}`,onClick:()=>g(te.id),children:[t.jsx(De,{size:16}),t.jsx("span",{className:"gm-nav-label",children:te.label})]},te.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[x&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),b&&!x&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Ws,{size:18}),t.jsx("span",{children:b}),t.jsx("button",{className:"btn btn-sm",onClick:tn,children:"Retry"})]}),p==="status"&&!x&&v&&t.jsx(qD,{status:v,copyToClipboard:C}),p==="changes"&&!x&&t.jsx(VD,{status:v,stagedFiles:$t,unstagedFiles:se,selectedFiles:_,toggleFileSelection:ln,onStageFiles:mn,onUnstageFiles:Qt,onDiscardChanges:yn,onSelectDiffFile:sn,selectedDiffTarget:$,changeDiff:K,loadingChangeDiff:ne,changeDiffError:A,commitMessage:z,setCommitMessage:U,onCommit:Gt,onStageAllAndCommit:on,committing:R}),p==="commits"&&!x&&t.jsx(WD,{commits:Le,commitSearch:L,setCommitSearch:pe,selectedCommit:He,commitDiff:Ne,loadingDiff:ie,onCommitClick:Wt,onLoadMore:ye,canLoadMore:ce.length>=oe&&oe<100,copyToClipboard:C}),p==="branches"&&!x&&t.jsx(KD,{branches:Pt,branchSearch:Pe,setBranchSearch:nt,newBranchName:ve,setNewBranchName:Fe,branchBase:ae,setBranchBase:qe,onCreateBranch:Ke,onCheckoutBranch:mt,onDeleteBranch:Ve,loading:x,allBranches:fe,selectedBranch:Be,branchCommits:Ie,loadingBranchCommits:st,expandedBranchCommit:me,branchCommitDiff:_e,loadingBranchCommitDiff:ut,onSelectBranch:Ot,onBranchCommitClick:bt,onCloseBranchDetails:Dt}),p==="worktrees"&&!x&&t.jsx(GD,{worktrees:vt}),p==="stashes"&&!x&&t.jsx(JD,{stashes:Je,stashMessage:Nt,setStashMessage:yt,onCreateStash:Ht,onApplyStash:rn,onDropStash:Xt,onToggleStashDiff:an,stashLoading:Se,expandedStashIndex:ge,stashDiff:ke,loadingStashDiff:Rt,stashDiffError:be}),p==="remotes"&&!x&&t.jsx(YD,{status:v,remoteLoading:gt,lastRemoteResult:Lt,onFetch:Me,onPull:it,onPush:kt,addToast:a,projectId:r,copyToClipboard:C})]})]})]})}):null}function qD({status:e,copyToClipboard:n}){return t.jsxs("div",{className:"gm-panel","data-testid":"status-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Repository Status"})}),t.jsxs("div",{className:"gm-status-grid",children:[t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Branch"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx(Fs,{size:14}),t.jsx("span",{children:e.branch})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Commit"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx("code",{className:"gm-hash",children:e.commit}),t.jsx("button",{className:"gm-icon-btn",onClick:()=>n(e.commit,"commit hash"),title:"Copy commit hash",children:t.jsx(da,{size:12})})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Working Tree"}),t.jsx("span",{className:`gm-status-badge ${e.isDirty?"dirty":"clean"}`,children:e.isDirty?t.jsxs(t.Fragment,{children:[t.jsx(Ws,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(Gn,{size:12}),"Clean"]})})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Remote Sync"}),t.jsxs("span",{className:"gm-status-value",children:[e.ahead>0&&t.jsxs("span",{className:"gm-ahead",title:`${e.ahead} commit(s) ahead`,children:[t.jsx(Ta,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(Po,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Gn,{size:12}),"Up to date"]})]})]})]})]})}function VD({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:a,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:d,selectedDiffTarget:u,changeDiff:m,loadingChangeDiff:h,changeDiffError:f,commitMessage:p,setCommitMessage:g,onCommit:x,onStageAllAndCommit:w,committing:b}){const y=s.filter(j=>a.has(`unstaged:${j.file}`)),S=n.filter(j=>a.has(`staged:${j.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Fs,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-changes-split",children:[t.jsxs("div",{className:"gm-changes-lists",children:[t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(j=>j.file)),title:"Stage selected",children:[t.jsx(Mn,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(j=>j.file)),title:"Discard selected",children:t.jsx(Do,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(j=>j.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list gm-file-list-unstaged","data-testid":"gm-file-list-unstaged",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(j=>{const C=u?.file===j.file&&u.staged===!1;return t.jsxs("div",{className:`gm-file-item${C?" active":""}`,onClick:()=>d(j.file,!1),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),d(j.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:v=>v.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`unstaged:${j.file}`),onChange:()=>r(`unstaged:${j.file}`)})}),t.jsx(Qf,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(Xf,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:v=>{v.stopPropagation(),o([j.file])},title:"Stage file",children:t.jsx(Mn,{size:12})})]},`unstaged:${j.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[S.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(S.map(j=>j.file)),title:"Unstage selected",children:["Unstage (",S.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(j=>j.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list gm-file-list-staged","data-testid":"gm-file-list-staged",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(j=>{const C=u?.file===j.file&&u.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${C?" active":""}`,onClick:()=>d(j.file,!0),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),d(j.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:v=>v.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`staged:${j.file}`),onChange:()=>r(`staged:${j.file}`)})}),t.jsx(Qf,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(Xf,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:v=>{v.stopPropagation(),l([j.file])},title:"Unstage file",children:t.jsx(un,{size:12})})]},`staged:${j.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:u||h||m||f?t.jsxs("div",{className:"gm-diff-section",children:[u&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(Qd,{size:14}),t.jsxs("span",{children:[u.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:u.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}),f&&!h&&t.jsx("div",{className:"gm-diff-error",children:f}),m&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[m.stat&&t.jsx("pre",{className:"gm-diff-stat",children:m.stat}),t.jsx("pre",{className:"gm-diff-patch",children:m.patch})]})]}):t.jsxs("div",{className:"gm-diff-empty",children:[t.jsx(Qd,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:x,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:j=>g(j.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(jt,{size:14,className:"spin"}):t.jsx(Ia,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:w,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function WD({commits:e,commitSearch:n,setCommitSearch:s,selectedCommit:a,commitDiff:r,loadingDiff:o,onCommitClick:l,onLoadMore:c,canLoadMore:d,copyToClipboard:u}){return t.jsxs("div",{className:"gm-panel","data-testid":"commits-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Commits"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Wi,{size:14}),t.jsx("input",{type:"text",placeholder:"Search commits...",value:n,onChange:m=>s(m.target.value)})]})]}),t.jsx("div",{className:"gm-commits-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching commits":"No commits found"}):e.map((m,h)=>t.jsxs("div",{className:"gm-commit-item",children:[t.jsxs("div",{className:"gm-commit-graph",children:[t.jsx("div",{className:"gm-commit-dot"}),h<e.length-1&&t.jsx("div",{className:"gm-commit-line"})]}),t.jsxs("div",{className:"gm-commit-body",children:[t.jsxs("button",{className:"gm-commit-header",onClick:()=>l(m.hash),children:[t.jsxs("div",{className:"gm-commit-top-row",children:[t.jsx("code",{className:"gm-hash",children:m.shortHash}),t.jsx("span",{className:"gm-commit-message",title:m.message,children:m.message})]}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:m.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Er(m.date)}),m.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),t.jsx("div",{className:"gm-commit-actions-row",children:t.jsx("button",{className:"gm-icon-btn",onClick:()=>u(m.hash,"commit hash"),title:"Copy full hash",children:t.jsx(da,{size:12})})}),a===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[m.body&&t.jsx("div",{className:"gm-commit-message-full",children:m.body}),r.stat&&t.jsx("pre",{className:"gm-diff-stat",children:r.stat}),t.jsx("pre",{className:"gm-diff-patch",children:r.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]})]},m.hash))}),d&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function KD({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:a,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:d,onDeleteBranch:u,loading:m,allBranches:h,selectedBranch:f,branchCommits:p,loadingBranchCommits:g,expandedBranchCommit:x,branchCommitDiff:w,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:S,onCloseBranchDetails:j}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Wi,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:C=>s(C.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:a,onChange:C=>r(C.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:C=>l(C.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(C=>t.jsx("option",{value:C.name,children:C.name},C.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!a.trim(),children:[t.jsx(Mn,{size:14}),"Create"]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching branches":"No branches found"}):e.map(C=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${C.isCurrent?" current":""}${f===C.name?" selected":""}`,onClick:()=>y(C.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[C.isCurrent&&t.jsx(js,{size:14,className:"gm-current-icon"}),C.name]}),C.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",C.remote]}),C.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:Er(C.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!C.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:v=>{v.stopPropagation(),d(C.name)},disabled:m,title:"Checkout",children:t.jsx(Fs,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:v=>{v.stopPropagation(),u(C.name)},disabled:m,title:"Delete",children:t.jsx(_n,{size:14})})]})})]}),f===C.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(xr,{size:14}),"Commits on ",C.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:j,title:"Close","data-testid":"close-branch-details",children:t.jsx(un,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(v=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>S(v.hash),"data-testid":`branch-commit-${v.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:v.shortHash}),t.jsx("span",{className:"gm-commit-message",title:v.message,children:v.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:v.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Er(v.date)}),v.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),x===v.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):w?t.jsxs(t.Fragment,{children:[(v.body||v.message)&&t.jsx("div",{className:"gm-commit-message-full",children:v.body||v.message}),w.stat&&t.jsx("pre",{className:"gm-diff-stat",children:w.stat}),t.jsx("pre",{className:"gm-diff-patch",children:w.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},v.hash))})]})]},C.name))})]})}function GD({worktrees:e}){return t.jsxs("div",{className:"gm-panel","data-testid":"worktrees-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Worktrees"}),t.jsxs("div",{className:"gm-worktree-stats",children:[t.jsxs("span",{children:[e.length," total"]}),t.jsx("span",{className:"gm-stat-separator",children:"•"}),t.jsxs("span",{children:[e.filter(n=>n.taskId).length," in use"]})]})]}),t.jsx("div",{className:"gm-worktrees-list",children:e.map(n=>t.jsx("div",{className:`gm-worktree-item${n.isMain?" main":""}`,children:t.jsxs("div",{className:"gm-worktree-info",children:[t.jsxs("div",{className:"gm-worktree-path-row",children:[n.isMain&&t.jsx("span",{className:"gm-badge main",children:"main"}),n.isBare&&t.jsx("span",{className:"gm-badge bare",children:"bare"}),t.jsx("span",{className:"gm-worktree-path",title:n.path,children:Hu(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Fs,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function JD({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:a,onApplyStash:r,onDropStash:o,onToggleStashDiff:l,stashLoading:c,expandedStashIndex:d,stashDiff:u,loadingStashDiff:m,stashDiffError:h}){return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Stashes"})}),t.jsxs("form",{className:"gm-create-form",onSubmit:a,children:[t.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:f=>s(f.target.value),disabled:c!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:c!==null,children:[c==="create"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(To,{size:14}),"Stash"]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:"No stashes"}):e.map(f=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-header",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${f.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:f.message}),t.jsxs("div",{className:"gm-stash-meta",children:[f.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Fs,{size:12}),f.branch]}),t.jsx("span",{children:Er(f.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>l(f.index),disabled:c!==null,children:d===f.index?"Hide":"View"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(f.index,!1),disabled:c!==null,title:"Apply stash (keep)",children:c===`apply-${f.index}`?t.jsx(jt,{size:14,className:"spin"}):"Apply"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(f.index,!0),disabled:c!==null,title:"Pop stash (apply and drop)",children:"Pop"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(f.index),disabled:c!==null,title:"Drop stash",children:c===`drop-${f.index}`?t.jsx(jt,{size:14,className:"spin"}):t.jsx(_n,{size:14})})]})]}),d===f.index&&t.jsx("div",{className:"gm-stash-diff",children:m?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading stash diff…"]}):h?t.jsx("div",{className:"gm-diff-error",children:h}):u?t.jsxs("div",{className:"gm-diff-viewer",children:[u.stat&&t.jsx("pre",{className:"gm-diff-stat",children:u.stat}),t.jsx("pre",{className:"gm-diff-patch",children:u.patch})]}):null})]},f.index))})]})}function YD({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:a,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:d}){const u=re=>{try{return new URL(re).hostname}catch{return re.replace(/^git@/,"").split(":")[0]||re}},[m,h]=i.useState([]),[f,p]=i.useState(!1),[g,x]=i.useState(null),[w,b]=i.useState(""),[y,S]=i.useState(""),[j,C]=i.useState(null),[v,N]=i.useState(""),[I,F]=i.useState(""),[_,M]=i.useState(!1),[z,U]=i.useState(!1),R=i.useRef(null),[D,K]=i.useState([]),[Z,ne]=i.useState(!1),[O,A]=i.useState(null),[P,$]=i.useState([]),[k,J]=i.useState(!1),[ce,je]=i.useState(null),He=i.useRef(0),xe=m.find(re=>re.name===O);i.useEffect(()=>{(n!==null||f)&&U(!1)},[n,f]),i.useEffect(()=>{if(!z)return;const re=xt=>{R.current?.contains(xt.target)||U(!1)},_e=xt=>{xt.key==="Escape"&&U(!1)};return document.addEventListener("mousedown",re),document.addEventListener("keydown",_e),()=>{document.removeEventListener("mousedown",re),document.removeEventListener("keydown",_e)}},[z]);const[Ne,Y]=i.useState(null),[ie,ee]=i.useState(null),[oe,W]=i.useState(!1),[L,pe]=i.useState(null),[fe,B]=i.useState(null),[ve,Fe]=i.useState(!1);i.useEffect(()=>{ae()},[]),i.useEffect(()=>{e&&e.ahead>0?qe():e&&e.ahead===0&&K([])},[e?.ahead]),i.useEffect(()=>{m.length>0&&!O&&A(m[0].name)},[m]),i.useEffect(()=>{O?Pe(O):($([]),je(null))},[O]),i.useEffect(()=>{!O||!s||Pe(O)},[O,s]),i.useEffect(()=>{O&&!m.find(re=>re.name===O)&&A(m.length>0?m[0].name:null)},[m,O]);const ae=async()=>{p(!0);try{const re=await SN(c);h(re)}catch(re){l(Ee(re)||"Failed to load remotes","error")}finally{p(!1)}},qe=async()=>{ne(!0);try{const re=await $N(c);K(re)}catch{K([])}finally{ne(!1)}},Pe=async re=>{const _e=He.current+1;He.current=_e,J(!0),je(null);try{const xt=await DN(re,void 0,10,c);if(He.current!==_e)return;$(xt)}catch(xt){if(He.current!==_e)return;je(Ee(xt)||"Failed to load remote commits"),$([])}finally{He.current===_e&&J(!1)}},nt=pi(),Be=async re=>{if(re.preventDefault(),!(!w.trim()||!y.trim())){x("add");try{await CN(w.trim(),y.trim(),c),l(`Remote '${w}' added successfully`,"success"),b(""),S(""),M(!1),await ae()}catch(_e){l(Ee(_e)||"Failed to add remote","error")}finally{x(null)}}},de=async re=>{if(await nt.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${re}'?`,danger:!0})){x(`remove-${re}`);try{await EN(re,c),l(`Remote '${re}' removed`,"success"),await ae()}catch(xt){l(Ee(xt)||"Failed to remove remote","error")}finally{x(null)}}},Ie=async re=>{if(I.trim()){x(`rename-${re}`);try{await _N(re,I.trim(),c),l(`Remote renamed to '${I.trim()}'`,"success"),C(null),F(""),await ae()}catch(_e){l(Ee(_e)||"Failed to rename remote","error")}finally{x(null)}}},$e=async re=>{if(v.trim()){x(`url-${re}`);try{await MN(re,v.trim(),c),l("Remote URL updated","success"),C(null),N(""),await ae()}catch(_e){l(Ee(_e)||"Failed to update remote URL","error")}finally{x(null)}}},st=i.useCallback(async(re,_e)=>{if(_e==="ahead"){if(Ne===re){Y(null),ee(null);return}Y(re),ee(null),W(!0);try{const xt=await Hl(re);ee(xt)}catch{ee(null)}finally{W(!1)}}else{if(L===re){pe(null),B(null);return}pe(re),B(null),Fe(!0);try{const xt=await Hl(re);B(xt)}catch{B(null)}finally{Fe(!1)}}},[Ne,L]),Ue=re=>{C(`url-${re.name}`),N(re.pushUrl||re.fetchUrl)},me=re=>{C(`name-${re.name}`),F(re.name)};return t.jsx("div",{className:"gm-panel gm-remotes-panel","data-testid":"remotes-panel",children:t.jsxs("div",{className:"gm-remotes-layout",children:[t.jsxs("div",{className:"gm-remote-selector","data-testid":"remote-selector",children:[t.jsxs("div",{className:"gm-remote-selector-header",children:[t.jsx("span",{className:"gm-remote-selector-title",children:"Remotes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>M(!_),disabled:g!==null,title:_?"Cancel":"Add Remote",children:_?t.jsx(un,{size:14}):t.jsx(Mn,{size:14})})]}),_&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Be,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:w,onChange:re=>b(re.target.value),disabled:g==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:re=>S(re.target.value),disabled:g==="add",className:"input gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!w.trim()||!y.trim()||g==="add",children:[g==="add"?t.jsx(jt,{size:12,className:"spin"}):t.jsx(Mn,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(re=>t.jsxs("div",{className:`gm-remote-selector-item${O===re.name?" selected":""}`,onClick:()=>A(re.name),role:"button",tabIndex:0,onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),A(re.name))},children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[t.jsx("span",{className:"gm-remote-selector-name-text",children:re.name}),re.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",title:re.fetchUrl,children:u(re.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:_e=>{_e.stopPropagation(),de(re.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(_n,{size:14})})]},re.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[O&&xe?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"gm-remote-sync-card","data-testid":"remote-sync-card",children:[t.jsxs("div",{className:"gm-remote-sync-card-header",children:[t.jsx("span",{className:"gm-remote-sync-card-title",children:O}),e&&(e.ahead>0||e.behind>0)&&t.jsxs("div",{className:"gm-remote-status",children:[e.ahead>0&&t.jsxs("div",{className:"gm-remote-indicator ahead",children:[t.jsx("span",{className:"status-dot status-dot--online","aria-hidden":"true"}),t.jsx(Ta,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx("span",{className:"status-dot status-dot--pending","aria-hidden":"true"}),t.jsx(Po,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:a,disabled:n!==null||f,children:[n==="fetch"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(bs,{size:14}),"Fetch"]}),t.jsxs("div",{className:"gm-pull-split",ref:R,children:[t.jsxs("button",{className:"btn btn-primary gm-pull-split-main",onClick:()=>{U(!1),r({rebase:!1})},disabled:n!==null||f,children:[n==="pull"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(si,{size:14}),"Pull"]}),t.jsx("button",{className:"btn btn-primary btn-icon gm-pull-split-toggle",onClick:()=>U(re=>!re),disabled:n!==null||f,"aria-label":"Pull options","aria-haspopup":"menu","aria-expanded":z,children:t.jsx(pn,{size:14})}),z?t.jsxs("div",{className:"gm-pull-menu",role:"menu","aria-label":"Pull options menu",children:[t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{U(!1),r({rebase:!1})},children:"Pull"}),t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{U(!1),r({rebase:!0})},children:"Pull --rebase"})]}):null]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(Ta,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),j===`url-${O}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:v,onChange:re=>N(re.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>$e(O),disabled:g===`url-${O}`,children:g===`url-${O}`?t.jsx(jt,{size:12,className:"spin"}):t.jsx(js,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),N("")},title:"Cancel",children:t.jsx(un,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:xe.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:xe.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(xe.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(da,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Ue(xe),disabled:g!==null,title:"Edit remote URL",children:t.jsx(qs,{size:14})})]})]})]}),xe.pushUrl&&xe.pushUrl!==xe.fetchUrl&&t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Push:"}),t.jsx("span",{className:"gm-url-value",title:xe.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:xe.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(xe.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(da,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:j===`name-${O}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:I,onChange:re=>F(re.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Ie(O),disabled:g===`rename-${O}`,children:g===`rename-${O}`?t.jsx(jt,{size:12,className:"spin"}):t.jsx(js,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),F("")},title:"Cancel",children:t.jsx(un,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>me(xe),disabled:g!==null,title:"Edit remote name",children:t.jsx(qs,{size:14})})})]}),e&&e.ahead>0&&t.jsxs("div",{className:"gm-remote-section","data-testid":"commits-to-push",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(Ta,{size:14}),"Commits to Push (",e.ahead,")"]})}),Z?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading..."]}):D.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:D.map(re=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>st(re.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),st(re.hash,"ahead"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:re.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:re.message,children:re.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:re.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Er(re.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Ne===re.hash?t.jsx(pn,{size:14}):t.jsx(On,{size:14})})]}),Ne===re.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:oe?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):ie?t.jsxs(t.Fragment,{children:[(re.body||re.message)&&t.jsx("div",{className:"gm-commit-message-full",children:re.body||re.message}),ie.stat&&t.jsx("pre",{className:"gm-diff-stat",children:ie.stat}),t.jsx("pre",{className:"gm-diff-patch",children:ie.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},re.hash))}):t.jsx("div",{className:"gm-empty",children:"No ahead commits found (may need to fetch first)"})]}),t.jsxs("div",{className:"gm-remote-section","data-testid":"remote-commits-section",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(Zg,{size:14}),"Recent commits on ",O]})}),k?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading commits..."]}):ce?t.jsxs("div",{className:"gm-error",children:[t.jsx(Ws,{size:14}),ce]}):P.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",O,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:P.map(re=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>st(re.hash,"remote"),role:"button",tabIndex:0,onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),st(re.hash,"remote"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:re.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:re.message,children:re.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:re.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Er(re.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:L===re.hash?t.jsx(pn,{size:14}):t.jsx(On,{size:14})})]}),L===re.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ve?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):fe?t.jsxs(t.Fragment,{children:[(re.body||re.message)&&t.jsx("div",{className:"gm-commit-message-full",children:re.body||re.message}),fe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:fe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:fe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},re.hash))})]})]}):t.jsx("div",{className:"gm-empty",children:"Select a remote to view details"}),s&&t.jsx("div",{className:"gm-remote-result",children:s.message})]})]})})}const lr={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function QD(e,n){return e&&n?`${e}/${n}`:""}function XD(e){if(!e)return{provider:"",modelId:""};const n=e.indexOf("/");return n===-1?{provider:"",modelId:""}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Zf(e){switch(e){case"file-text":return ua;case"check-circle":return Gn;case"shield":return Fk;case"zap":return as;case"eye":return Tr;case"globe":return dc;case"layout-grid":return ma;case"puzzle":return jk;default:return Gn}}function eg(e){switch(e.toLowerCase()){case"quality":return"wfm-badge-category wfm-badge-category-quality";case"security":return"wfm-badge-category wfm-badge-category-security";default:return"wfm-badge-category"}}function ZD({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState({}),[m,h]=i.useState(!0),[f,p]=i.useState(!0),[g,x]=i.useState("my-steps"),[w,b]=i.useState(null),[y,S]=i.useState(!1),[j,C]=i.useState(!1),[v,N]=i.useState(lr),[I,F]=i.useState(!1),[_,M]=i.useState(!1),[z,U]=i.useState(null),[R,D]=i.useState(null),[K,Z]=i.useState({}),[ne,O]=i.useState([]),A=i.useRef(null);Li(A,e,"fusion:workflow-steps-modal-size");const P=i.useCallback(async()=>{try{h(!0);const L=await Uo(a);o(L)}catch(L){s(Ee(L)||"Failed to load workflow steps","error")}finally{h(!1)}},[s,a]),$=i.useCallback(async()=>{try{const L=await _o(a);Z(L||{})}catch{}},[a]),k=i.useCallback(async()=>{try{const L=await Ks();O(L.models||[])}catch{}},[]),J=i.useCallback(async()=>{try{p(!0);const[L,pe]=await Promise.all([$S(),DS()]);c(L.templates);const fe=Object.fromEntries(pe.templates.map(({pluginId:B,template:ve})=>[ve.id,B]));u(fe)}catch(L){s(Ee(L)||"Failed to load templates","error")}finally{p(!1)}},[s]);i.useEffect(()=>{e&&(P(),J(),$(),k())},[e,P,J,$,k]);const ce=i.useCallback(()=>{C(!0),S(!1),b(null),N(lr)},[]),je=i.useCallback(()=>{C(!1),S(!0),b(null),N(lr)},[]),He=i.useCallback(L=>{b(L.id),S(!1),N({name:L.name,description:L.description,mode:L.mode||"prompt",phase:L.phase||"pre-merge",prompt:L.prompt,scriptName:L.scriptName||"",enabled:L.enabled,defaultOn:L.defaultOn||!1,modelProvider:L.modelProvider||"",modelId:L.modelId||""})},[]),xe=i.useCallback(()=>{b(null),S(!1),C(!1),N(lr)},[]),Ne=i.useCallback(async()=>{if(!v.name.trim()||!v.description.trim()){s("Name and description are required","error");return}F(!0);try{const L=v.mode==="prompt"&&v.modelProvider&&v.modelId?{modelProvider:v.modelProvider,modelId:v.modelId}:v.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(y){const pe={name:v.name.trim(),description:v.description.trim(),mode:v.mode,phase:v.phase,prompt:v.mode==="prompt"&&v.prompt.trim()||void 0,scriptName:v.mode==="script"?v.scriptName.trim():void 0,enabled:v.enabled,defaultOn:v.defaultOn||void 0,...L};await Jm(pe,a),s("Workflow step created","success")}else w&&(await IS(w,{name:v.name.trim(),description:v.description.trim(),mode:v.mode,phase:v.phase,prompt:v.mode==="prompt"?v.prompt:"",scriptName:v.mode==="script"?v.scriptName.trim():void 0,enabled:v.enabled,defaultOn:v.defaultOn,...L},a),s("Workflow step updated","success"));S(!1),b(null),N(lr),await P()}catch(L){s(Ee(L)||"Failed to save workflow step","error")}finally{F(!1)}},[v,y,w,s,P]),Y=i.useCallback(async L=>{try{await TS(L,a),s("Workflow step deleted","success"),U(null),w===L&&(b(null),N(lr)),await P()}catch(pe){s(Ee(pe)||"Failed to delete workflow step","error")}},[w,s,P]),ie=i.useCallback(async()=>{if(!(!w&&!y)&&v.mode==="prompt"){if(y){if(!v.name.trim()||!v.description.trim()){s("Name and description are required before refining","error");return}F(!0);try{const L=v.modelProvider&&v.modelId?{modelProvider:v.modelProvider,modelId:v.modelId}:{},pe={name:v.name.trim(),description:v.description.trim(),mode:"prompt",prompt:v.prompt.trim()||void 0,enabled:v.enabled,defaultOn:v.defaultOn||void 0,...L},fe=await Jm(pe,a);S(!1),b(fe.id),M(!0);const B=await Ym(fe.id,a);N(ve=>({...ve,prompt:B.prompt})),s("Prompt refined with AI","success"),await P()}catch(L){s(Ee(L)||"Failed to refine prompt","error")}finally{F(!1),M(!1)}return}if(w){M(!0);try{const L=await Ym(w,a);N(pe=>({...pe,prompt:L.prompt})),s("Prompt refined with AI","success"),await P()}catch(L){s(Ee(L)||"Failed to refine prompt","error")}finally{M(!1)}}}},[w,y,v,s,P]),ee=i.useCallback(async L=>{D(L.id);try{await LS(L.id,a),s(`Added ${L.name} workflow step`,"success"),await P(),x("my-steps"),C(!1)}catch(pe){const fe=Ee(pe);fe?.includes("already exists")?s(`A workflow step named '${L.name}' already exists`,"error"):s(fe||"Failed to add workflow step from template","error")}finally{D(null)}},[s,P]),oe=Qi(n);if(!e)return null;const W=y||w!==null;return t.jsx("div",{className:"modal-overlay open",...oe,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:A,className:"modal workflow-step-manager-modal",role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Workflow Steps"}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"wfm-body",children:m?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!W&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>x("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(Ey,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>x("templates"),"data-testid":"tab-templates",children:[t.jsx(ma,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!W&&!j&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(L=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${L.id}`,children:t.jsxs("div",{className:"wfm-step-card-top",children:[t.jsxs("div",{className:"wfm-step-card-info",children:[t.jsxs("div",{className:"wfm-step-card-title-row",children:[t.jsx("span",{className:"wfm-step-card-name",children:L.name}),t.jsx("span",{className:`wfm-badge ${L.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:L.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(L.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(L.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(L.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(L.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),L.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:L.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>He(L),title:"Edit","aria-label":`Edit ${L.name}`,children:t.jsx(qs,{size:14})}),z===L.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>Y(L.id),title:"Confirm delete","aria-label":`Confirm delete ${L.name}`,children:t.jsx(js,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>U(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(un,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>U(L.id),title:"Delete","aria-label":`Delete ${L.name}`,children:t.jsx(_n,{size:14})})]})]})},L.id))})]}),g==="templates"&&!W&&!j&&t.jsx(t.Fragment,{children:f?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(jt,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(L=>{const pe=Zf(L.icon),fe=eg(L.category),B=R===L.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${L.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(pe,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:L.name}),t.jsx("span",{className:fe,children:L.category}),d[L.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[L.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:L.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>ee(L),disabled:B,"data-testid":`add-template-${L.id}`,children:B?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Mn,{size:12}),"Add"]})})]})]})},L.id)})})}),j&&!W&&t.jsxs("div",{className:"wfm-create-chooser","data-testid":"workflow-step-create-chooser",children:[t.jsx("h3",{className:"wfm-form-title",children:"How would you like to create this workflow step?"}),t.jsx("p",{className:"wfm-create-chooser-hint",children:"Start from a built-in template or create a fully custom workflow step."}),t.jsxs("button",{className:"btn wfm-create-custom-btn",onClick:je,"data-testid":"create-custom-step",children:[t.jsx(Mn,{size:14}),"Custom workflow step"]}),f?t.jsxs("div",{className:"wfm-loading","data-testid":"create-chooser-template-loading",children:[t.jsx(jt,{size:24,className:"spin wfm-spinner"}),"Loading built-in templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"create-chooser-no-templates",children:"No built-in templates are available right now. You can still create a custom step."}):t.jsx("div",{className:"wfm-template-list","data-testid":"create-chooser-templates",children:l.map(L=>{const pe=Zf(L.icon),fe=eg(L.category),B=R===L.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`chooser-template-${L.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(pe,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:L.name}),t.jsx("span",{className:fe,children:L.category}),d[L.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[L.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:L.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>ee(L),disabled:B,"data-testid":`chooser-add-template-${L.id}`,children:B?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Mn,{size:12}),"Add template"]})})]})]})},L.id)})})]}),W&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:y?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:v.name,onChange:L=>N(pe=>({...pe,name:L.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:v.description,onChange:L=>N(pe=>({...pe,description:L.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${v.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Ki,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${v.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Gi,{size:14}),"Run Script"]})]})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Phase"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-phase-selector",children:[t.jsx("button",{className:`btn ${v.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${v.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:v.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),v.mode==="prompt"&&t.jsxs("div",{className:"wfm-field",children:[t.jsxs("div",{className:"wfm-prompt-header",children:[t.jsx("label",{children:"Agent Prompt"}),t.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:ie,disabled:!v.description.trim()||_,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[_?t.jsx(jt,{size:12,className:"spin"}):t.jsx(gs,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:v.prompt,onChange:L=>N(pe=>({...pe,prompt:L.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),v.mode==="prompt"&&t.jsxs("div",{className:"wfm-field","data-testid":"workflow-step-model-field",children:[t.jsxs("div",{className:"wfm-model-header",children:[t.jsx("label",{children:"Model Override"}),v.modelProvider&&v.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>N(L=>({...L,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(un,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:v.modelProvider&&v.modelId?`Using ${v.modelProvider}/${v.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(Is,{models:ne,value:QD(v.modelProvider,v.modelId),onChange:L=>{const pe=XD(L);N(fe=>({...fe,modelProvider:pe.provider,modelId:pe.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),v.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(K).length===0?t.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):t.jsxs("select",{value:v.scriptName,onChange:L=>N(pe=>({...pe,scriptName:L.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(K).map(([L,pe])=>t.jsxs("option",{value:L,children:[L," (",pe,")"]},L))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:v.enabled,onChange:L=>N(pe=>({...pe,enabled:L.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:v.defaultOn,onChange:L=>N(pe=>({...pe,defaultOn:L.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),t.jsxs("div",{className:"wfm-form-actions",children:[t.jsx("button",{className:"btn btn-secondary",onClick:xe,disabled:I,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:Ne,disabled:I||!v.name.trim()||!v.description.trim()||v.mode==="script"&&!v.scriptName.trim(),"data-testid":"save-workflow-step",children:I?"Saving...":y?"Create":"Save"})]})]})]})]})}),!W&&!j&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:ce,"data-testid":"add-workflow-step",children:[t.jsx(Mn,{size:14}),"Add Workflow Step"]})})]})})}const eL=36e5,tL=3e5,Bd=[{value:3e5,label:"5m"},{value:9e5,label:"15m"},{value:18e5,label:"30m"},{value:36e5,label:"1h"},{value:108e5,label:"3h"},{value:216e5,label:"6h"},{value:432e5,label:"12h"},{value:864e5,label:"24h"},{value:1728e5,label:"48h"},{value:2592e5,label:"72h"},{value:6048e5,label:"1w"}];function nL(e){return e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:e<864e5?`${Math.round(e/36e5)}h`:e<6048e5?`${Math.round(e/864e5)}d`:`${Math.round(e/6048e5)}w`}function sL(e){return typeof e!="number"||!Number.isFinite(e)?eL:Math.max(tL,Math.round(e))}function a8(e){if(Bd.some(s=>s.value===e))return[...Bd];const n={value:e,label:`${nL(e)} (custom)`};return[...Bd,n].sort((s,a)=>s.value-a.value)}const iL=4,aL=5*6e4;function rL(e){const n=sL(e?.heartbeatIntervalMs);return Math.max(n*iL,aL)}function tg(e){const n=Math.floor(e/6e4);if(n<1)return"<1m";const s=Math.floor(n/60),a=n%60;return s>0&&a>0?`${s}h ${a}m`:s>0?`${s}h`:`${a}m`}function oL(e){const n=e.metadata;return n&&(n.agentKind==="task-worker"||n.taskWorker===!0||n.managedBy==="task-executor")?!0:!!(e.role==="executor"&&e.name?.startsWith("executor-")&&e.taskId)}function lL(e){const s=e.metadata?.heartbeatTimerRepair;if(!s||typeof s!="object")return{};const a=s;return{repairedAt:typeof a.repairedAt=="string"?a.repairedAt:void 0,staleAtRepair:typeof a.staleAtRepair=="boolean"?a.staleAtRepair:void 0,staleRepairReason:typeof a.staleRepairReason=="string"?a.staleRepairReason:void 0}}function cL(e){const{state:n,lastHeartbeatAt:s,lastError:a,pauseReason:r,runtimeConfig:o}=e,l=oL(e),c=l||o?.enabled!==!1;if(n==="error")return{label:a??"Error",icon:t.jsx(Ys,{size:14}),color:"var(--state-error-text)",stateDerived:!a};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(vi,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Ys,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(vi,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Kn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=lL(e);if(d.staleAtRepair&&d.repairedAt){const f=Date.parse(d.repairedAt),p=Date.parse(s);if(Number.isFinite(f)&&Number.isFinite(p)&&p<f)return{label:"Unresponsive",icon:t.jsx(Ys,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:d.staleRepairReason??"Heartbeat scheduler repaired a missing timer; waiting for recovery heartbeat"}}const u=new Date(s).getTime(),m=Date.now()-u,h=rL(o);if(m>h){const f=`No heartbeat for ${tg(m)} (threshold: ${tg(h)})`;return{label:"Unresponsive",icon:t.jsx(Ys,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:f}}return{label:"Healthy",icon:t.jsx($w,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}function sc({agent:e,size:n=36,className:s}){const[a,r]=i.useState(!1);i.useEffect(()=>{r(!1)},[e.imageUrl]);const o=i.useMemo(()=>{if(!e.imageUrl)return;const l=encodeURIComponent(e.updatedAt??""),c=e.imageUrl.includes("?")?"&":"?";return`${e.imageUrl}${c}t=${l}`},[e.imageUrl,e.updatedAt]);return t.jsx("span",{className:`agent-avatar${s?` ${s}`:""}`,style:{width:`${n}px`,height:`${n}px`},"aria-label":`${e.name} avatar`,children:o&&!a?t.jsx("img",{src:o,alt:`${e.name} avatar`,onError:()=>r(!0)}):e.icon?.trim()?t.jsx("span",{className:"agent-avatar-emoji",style:{fontSize:`calc(${n}px * 0.58)`},"aria-hidden":"true",children:e.icon}):t.jsx(Kn,{size:Math.max(14,Math.round(n*.55)),"aria-hidden":"true"})})}const dL="https://github.com/Runfusion/Fusion/issues/new";function uL(e,n){const s=`[Agent Error] ${n.surface}${n.agentName?` - ${n.agentName}`:""}`,a=["## Agent Error Report","",`- Surface: ${n.surface}`,`- Agent ID: ${n.agentId??"unknown"}`,`- Agent Name: ${n.agentName??"unknown"}`,`- Agent State: ${n.agentState??"unknown"}`,`- Run ID: ${n.runId??"n/a"}`,`- Task ID: ${n.taskId??"n/a"}`,`- Timestamp: ${n.timestamp??new Date().toISOString()}`,"","## Error","```text",e,"```"],r=new URLSearchParams({title:s,body:a.join(`
691
+ `)});return`${dL}?${r.toString()}`}function mL({open:e,onClose:n,errorText:s,issueContext:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>uL(s,a),[s,a]);return e?t.jsx("div",{className:"modal-overlay open",onClick:c=>c.target===c.currentTarget&&n(),role:"dialog","aria-modal":"true","aria-label":"Agent error details",children:t.jsxs("div",{className:"modal agent-error-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(Ws,{size:16}),"Agent Error Details"]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"agent-error-modal__content",children:t.jsx("pre",{className:"agent-error-modal__error",children:s})}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>{navigator.clipboard.writeText(s).then(()=>{o(!0),setTimeout(()=>o(!1),1500)})},"aria-label":r?"Copied error to clipboard":"Copy error to clipboard",children:[r?t.jsx(js,{size:14}):t.jsx(da,{size:14}),r?"Copied":"Copy"]}),t.jsxs("a",{className:"btn btn-sm btn-warning",href:l,target:"_blank",rel:"noreferrer",onClick:c=>{c.preventDefault(),window.open(l,"_blank","noopener,noreferrer")},children:[t.jsx(Kg,{size:14}),"Report on GitHub"]})]})]})}):null}function hL({errorText:e,issueContext:n,summaryPrefix:s="Error"}){const[a,r]=i.useState(!1);return t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:"agent-error-indicator",onClick:()=>r(!0),"aria-label":"Open error details",children:[t.jsx(Ws,{size:14}),t.jsx("span",{className:"agent-error-indicator__label",children:s})]}),t.jsx(mL,{open:a,onClose:()=>r(!1),errorText:e,issueContext:n})]})}const Ml=[{value:"triage",label:"Triage",icon:"⊕"},{value:"executor",label:"Executor",icon:"▶"},{value:"reviewer",label:"Reviewer",icon:"⊙"},{value:"merger",label:"Merger",icon:"⊞"},{value:"scheduler",label:"Scheduler",icon:"◷"},{value:"engineer",label:"Engineer",icon:"⎔"},{value:"custom",label:"Custom",icon:"✦"}];function pL({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState(""),[f,p]=i.useState("custom"),[g,x]=i.useState("all"),[w,b]=i.useState(()=>{if(typeof window>"u")return"list";const $=zn("fn-agent-view",a);return $==="board"||$==="list"?$:"list"});i.useEffect(()=>{const $=zn("fn-agent-view",a);if($==="board"||$==="list"){b($);return}b("list")},[a]),i.useEffect(()=>{us("fn-agent-view",w,a)},[a,w]);const[y,S]=i.useState(null),j=i.useRef(null),[C,v]=i.useState(new Set),[N,I]=i.useState(new Map),{confirm:F}=pi(),_=i.useMemo(()=>N.size===0?r:r.map($=>{const k=N.get($.id);return k?{...$,state:k}:$}),[r,N]),M=i.useMemo(()=>g!=="all"?_:[..._].sort(($,k)=>{const J=$.state==="paused"?1:0,ce=k.state==="paused"?1:0;return J!==ce?J-ce:(k.updatedAt??"").localeCompare($.updatedAt??"")}),[_,g]),z=i.useCallback(async()=>{c(!0);try{const k=await $r(g!=="all"?{state:g}:void 0,a);o(k)}catch($){s(`Failed to load agents: ${Ee($)}`,"error")}finally{c(!1)}},[g,s,a]);i.useEffect(()=>{e&&z()},[e,z]),i.useEffect(()=>{if(!e)return;const $=setInterval(()=>{z()},3e4);return()=>{clearInterval($)}},[e,z]);const U=async()=>{if(m.trim())try{await WS({name:m.trim(),role:f},a),s(`Agent "${m}" created`,"success"),h(""),u(!1),z()}catch($){s(`Failed to create agent: ${Ee($)}`,"error")}},R=async($,k)=>{if(!C.has($)){v(J=>new Set(J).add($)),I(J=>{const ce=new Map(J);return ce.set($,k),ce});try{await GS($,k,a),s(`Agent state updated to ${k}`,"success"),await z(),I(J=>{const ce=new Map(J);return ce.delete($),ce})}catch(J){I(ce=>{const je=new Map(ce);return je.delete($),je}),s(`Failed to update state: ${Ee(J)}`,"error")}finally{v(J=>{const ce=new Set(J);return ce.delete($),ce})}}},D=async($,k)=>{if(await F({title:"Delete Agent",message:`Delete agent "${k}"? This cannot be undone.`,danger:!0}))try{await JS($,a),s(`Agent "${k}" deleted`,"success"),z()}catch(ce){s(`Failed to delete agent: ${Ee(ce)}`,"error")}},K=async($,k)=>{const J=r.find(ce=>ce.id===$);if(J){if(J.role===k){S(null);return}try{await KS($,{role:k},a),s(`Agent role updated to ${Ml.find(ce=>ce.value===k)?.label??k}`,"success"),S(null),z()}catch(ce){s(`Failed to update role: ${Ee(ce)}`,"error")}}},Z=($,k)=>{$.key==="Escape"&&S(null)},ne=$=>Ml.find(k=>k.value===$)?.label??$,O=$=>cL($),A=$=>$.color==="var(--state-active-text)"?"active":$.color==="var(--state-paused-text)"?"paused":$.color==="var(--state-error-text)"?"error":"muted",P=($,k)=>$.state==="error"?{title:void 0,label:"Error"}:{title:k.reason??k.label,label:k.stateDerived?null:k.label};return e?t.jsx("div",{className:"modal-overlay open",onClick:$=>$.target===$.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(Kn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${w==="board"?" active":""}`,onClick:()=>b("board"),title:"Board view","aria-label":"Board view","aria-pressed":w==="board",children:t.jsx(ma,{size:16})}),t.jsx("button",{className:`view-toggle-btn${w==="list"?" active":""}`,onClick:()=>b("list"),title:"List view","aria-label":"List view","aria-pressed":w==="list",children:t.jsx(Zd,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void z(),title:"Refresh",disabled:l,children:t.jsx(bs,{size:16,className:l?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:"modal-content agent-modal-content",children:[t.jsxs("div",{className:"agent-controls",children:[t.jsxs("div",{className:"agent-state-filter",children:[t.jsx(Fl,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:$=>x($.target.value),"aria-label":"Filter agents by state",children:[t.jsx("option",{value:"all",children:"All States"}),t.jsx("option",{value:"idle",children:"Idle"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"running",children:"Running"}),t.jsx("option",{value:"paused",children:"Paused"}),t.jsx("option",{value:"error",children:"Error"})]})]}),t.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>u(!d),children:[t.jsx(Mn,{size:16}),d?"Cancel":"New Agent"]})]}),d&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:$=>h($.target.value),onKeyDown:$=>$.key==="Enter"&&U(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:$=>p($.target.value),children:Ml.map($=>t.jsxs("option",{value:$.value,children:[$.icon," ",$.label]},$.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void U(),children:"Create"})]}),t.jsx("div",{className:w==="board"?"agent-board":"agent-list",children:M.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Kn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):w==="board"?M.map($=>{const k=O($),J=P($,k),ce=A(k);return t.jsxs("div",{className:"agent-board-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:t.jsx(sc,{agent:$,size:20})}),t.jsx("span",{className:"agent-board-badge","data-state":$.state,children:$.state}),t.jsx("span",{className:"agent-board-health","data-health":ce,title:J.title,children:k.icon})]}),t.jsx("div",{className:"agent-board-name",title:$.name,children:$.name}),t.jsx("div",{className:"agent-board-id",children:$.id}),t.jsxs("div",{className:"agent-board-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:C.has($.id),title:"Activate",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D($.id,$.name),title:"Delete",children:t.jsx(_n,{size:14})})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"paused"),disabled:C.has($.id),title:"Pause",children:t.jsx(vi,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx(Ii,{size:14})})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:C.has($.id),title:"Resume",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D($.id,$.name),title:"Delete",children:t.jsx(_n,{size:14})})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"paused"),disabled:C.has($.id),title:"Pause",children:t.jsx(vi,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx(Ii,{size:14})})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:C.has($.id),title:"Retry",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx(Ii,{size:14})})]})]})]},$.id)}):M.map($=>{const k=O($),J=P($,k),ce=A(k);return t.jsxs("div",{className:"agent-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===$.id?t.jsx("select",{ref:j,className:"select agent-role-select",value:$.role,onChange:je=>void K($.id,je.target.value),onKeyDown:je=>Z(je,$.id),onBlur:()=>S(null),autoFocus:!0,children:Ml.map(je=>t.jsxs("option",{value:je.value,children:[je.icon," ",je.label]},je.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>S($.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:je=>{(je.key==="Enter"||je.key===" ")&&S($.id)},children:t.jsx(sc,{agent:$,size:20})}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:$.name}),t.jsx("span",{className:"agent-id text-secondary",children:$.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":$.state,children:$.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":ce,title:J.title,children:[k.icon,J.label?` ${J.label}`:""]}),t.jsx("span",{className:"badge text-secondary",children:ne($.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[$.state==="error"&&$.lastError?t.jsx(hL,{errorText:$.lastError,issueContext:{surface:"AgentListModal list",agentId:$.id,agentName:$.name,agentState:$.state,taskId:$.taskId}}):null,$.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:$.taskId})]}),$.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date($.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:C.has($.id),title:"Activate",children:[t.jsx(is,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D($.id,$.name),title:"Delete",children:[t.jsx(_n,{size:14})," Delete"]})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"paused"),disabled:C.has($.id),title:"Pause",children:[t.jsx(vi,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx(Ii,{size:14})," Stop"]})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:C.has($.id),title:"Resume",children:[t.jsx(is,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D($.id,$.name),title:"Delete",children:[t.jsx(_n,{size:14})," Delete"]})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"paused"),disabled:C.has($.id),title:"Pause",children:[t.jsx(vi,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx(Ii,{size:14})," Stop"]})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:C.has($.id),title:"Retry",children:[t.jsx(is,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx(Ii,{size:14})," Stop"]})]})]})]},$.id)})})]})]})}):null}function fL({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),u=i.useRef(!0);i.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const m=i.useCallback(async()=>{try{const b=await tN();return u.current&&r(b),b}catch(b){return u.current&&d({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);i.useEffect(()=>{m()},[m]);const h=i.useCallback(async()=>{l("testing"),d(null),await m(),u.current&&l(null)},[m]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await oN(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,m]),p=a?.binary.available??!1,g=a?.enabled??e,x=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),w=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(Fn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(gL,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:w})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[x,t.jsx(ng,{status:a,authenticated:e}),c&&t.jsx(sg,{action:c})]})]})]}):t.jsxs("div",{className:`onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(Fn,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),x,t.jsx(ng,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:w}),c&&t.jsx(sg,{action:c})]})}function gL({status:e,authenticated:n}){const s=e?.enabled??n,a=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!a&&e?t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not installed"}):t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not connected"})}function ng({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(jt,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:a,extension:r,ready:o}=e;return s.available?a?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"claude"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`claude` not found on PATH"]})}function sg({action:e}){if(e.kind==="error")return t.jsx("p",{className:"onboarding-helper-text onboarding-helper-text--error",children:e.message});const n=e.kind==="enabled"?"Enabled":"Disabled";return t.jsxs("p",{className:"onboarding-helper-text",children:[n,"."," ",e.kind==="enabled"?"Claude-CLI-routed models are now visible in the model picker.":"Claude-CLI-routed models are hidden from the model picker."]})}function bL({authenticated:e,compact:n=!1,onToggled:s}){const[a,r]=i.useState(null),[o,l]=i.useState(null),c=i.useRef(!0);i.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const d=i.useCallback(async()=>{try{const g=await aN();return c.current&&r(g),g}catch{return null}},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async g=>{l(g?"enabling":"disabling");try{const x=await cN(g);s?.(x.enabled),await d()}finally{c.current&&l(null)}},[s,d]),m=a?.enabled??e,h=a?.binary.available??!1,f=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l("testing"),d().finally(()=>{c.current&&l(null)})},disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"animate-spin"})," Testing…"]}):"Test"}),m?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void u(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void u(!0),disabled:o!==null||!h,children:o==="enabling"?"Enabling…":"Enable"})]}),p=a?a.binary.available?m?`Connected${a.binary.version?` — ${a.binary.version}`:""}`:"Detected. Click Enable to route calls through Cursor CLI.":a.binary.reason??"`cursor-agent` not found on PATH":"Probing local CLI…";return n?t.jsxs("div",{className:`cursor-cli-provider-card auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"cursor-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(Fn,{provider:"cursor-cli",size:"sm"}),t.jsx("strong",{children:"Cursor — via Cursor CLI"}),t.jsx("span",{className:`auth-status-badge ${m?"authenticated":"not-authenticated"}`,children:m?"✓ Active":"✗ Not connected"})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:f})]}),t.jsx("small",{className:"settings-muted",children:p})]}):t.jsxs("div",{className:`cursor-cli-provider-card onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"cursor-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(Fn,{provider:"cursor-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Cursor — via Cursor CLI"}),t.jsx("span",{className:"onboarding-provider-card__description",children:"Route AI calls through your local Cursor agent runtime."}),t.jsx("small",{className:"settings-muted",children:p})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:f})]})}function xL({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),c=i.useRef(!0);i.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const d=i.useCallback(async()=>{const x=await rN();return c.current&&r(x),x},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async x=>{l(x?"enabling":"disabling");try{const w=await dN(x);n?.(w.enabled),await d()}finally{c.current&&l(null)}},[n,d]),m=i.useCallback(async()=>{l("testing");try{await d()}finally{c.current&&l(null)}},[d]),h=a?.enabled??e,f=a?.server.available??!1,p=a?a.server.available?`Server reachable at ${a.server.url}`:`Server unavailable: ${a.server.reason??"not reachable"}`:"Probing llama.cpp server…",g=t.jsxs("div",{className:"auth-provider-cli-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void m(),disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),h?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void u(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void u(!0),disabled:o!==null||!f,children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli llama-cpp-provider-card llama-cpp-provider-card--compact${h?" auth-provider-card--authenticated":""}`,"data-testid":"llama-cpp-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(Fn,{provider:"llama-cpp",size:"sm"}),t.jsx("strong",{children:"llama.cpp — via HTTP server"})]}),g]}),t.jsx("small",{className:`auth-hint llama-cpp-status${a?.ready?" llama-cpp-status--ok":""}`,children:p})]}):t.jsxs("div",{className:"onboarding-provider-card llama-cpp-provider-card llama-cpp-provider-card--full","data-testid":"llama-cpp-provider-card",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(Fn,{provider:"llama-cpp",size:"md"}),t.jsx("strong",{children:"llama.cpp — via HTTP server"})]}),t.jsx("small",{className:`llama-cpp-status${a?.ready?" llama-cpp-status--ok":""}`,children:p}),g]})}function vL(e){const n="([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+|[A-Z0-9]{6,9})",s=new RegExp(`\\b(?:device\\s+code|your\\s+code|code)\\s*(?:is|:)?\\s*${n}\\b`,"i"),a=new RegExp(`\\b(?:enter|use)\\s+${n}\\b`,"i"),r=/\b([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+)\b/,o=e.match(s);if(o?.[1])return o[1];const l=e.match(a);if(l?.[1])return l[1];const c=e.match(r);return c?.[1]?c[1]:null}function Ud({instructions:e,"data-testid":n}){const[s,a]=i.useState(!1),r=vL(e),o=i.useRef(null),l=i.useCallback(()=>{a(!0),setTimeout(()=>a(!1),2e3)},[]),c=i.useCallback(async()=>{const d=r??e;try{await navigator.clipboard.writeText(d),l()}catch{}},[r,e,l]);return i.useEffect(()=>{const d=o.current===null&&r!==null;if(o.current=r,!d)return;(async()=>{try{await navigator.clipboard.writeText(r),l()}catch{}})()},[r,l]),t.jsx("p",{className:"auth-login-instructions","data-testid":n,children:r?t.jsx(t.Fragment,{children:e.split(r).map((d,u,m)=>t.jsxs("span",{children:[d,u<m.length-1&&t.jsxs("span",{className:"device-code-wrapper",children:[t.jsx("code",{className:"device-code",children:r}),t.jsx("button",{className:"device-code-copy-btn",onClick:c,title:s?"Copied!":"Copy code","aria-label":s?"Copied to clipboard":"Copy device code",type:"button",children:s?t.jsx(js,{size:12}):t.jsx(da,{size:12})})]})]},u))}):e})}function yL({value:e,onChange:n,onSubmit:s,prompt:a,placeholder:r,helpText:o,disabled:l=!1,submitLabel:c="Submit code","data-testid":d}){const u=i.useRef(null),m=i.useRef(null),[h,f]=i.useState(!1),p=i.useCallback(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return!1;const w=window.matchMedia("(max-width: 768px)").matches,b=window.matchMedia("(pointer: coarse)").matches;return w||b},[]),g=i.useCallback(()=>typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth",[]),x=i.useCallback(()=>{if(!p())return;const w=m.current??u.current;if(!w||typeof w.scrollIntoView!="function")return;const b=g();requestAnimationFrame(()=>{w.scrollIntoView({block:"center",behavior:b,inline:"nearest"}),window.setTimeout(()=>{w.scrollIntoView({block:"center",behavior:b,inline:"nearest"})},120)})},[g,p]);return i.useEffect(()=>{if(!h||!p())return;x();const w=window.visualViewport;if(!w)return;const b=()=>{document.activeElement===m.current&&x()};return w.addEventListener("resize",b),w.addEventListener("scroll",b),()=>{w.removeEventListener("resize",b),w.removeEventListener("scroll",b)}},[h,x,p]),t.jsxs("div",{ref:u,className:"oauth-manual-code","data-testid":d,children:[t.jsx("p",{className:"oauth-manual-code__prompt",children:a}),t.jsx("textarea",{ref:m,className:"form-input oauth-manual-code__input",value:e,onChange:w=>n(w.target.value),onFocus:()=>{f(!0),x()},onBlur:()=>f(!1),placeholder:r,rows:3,spellCheck:!1,disabled:l}),t.jsx("div",{className:"oauth-manual-code__actions",children:t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:l,children:c})}),o&&t.jsx("p",{className:"oauth-manual-code__help",children:o})]})}const wL=new Set(["anthropic","claude-cli","pi-claude-cli","openai","openai-codex","google","gemini","google-antigravity","antigravity","google-vertex","vertex","google-cloud-code","cloud-code","google-gemini-cli","google-generative-ai","ollama","github","github-copilot","openrouter","minimax","minimax-cn","zai","kimi","moonshot","kimi-coding","bedrock","amazon-bedrock","xai","grok","opencode","opencode-go","qwen","qwen-ai","qwen-coder","alibaba","tongyi","lmstudio","lm-studio","huggingface","hugging-face","hf","mistral","mistral-ai","azure","azure-openai","azure-openai-responses","fireworks","fireworks-ai","fireworksai","cerebras","groq","vercel","vercel-ai-gateway","hermes","hermes-agent","hermesagent","openclaw","open-claw","paperclip","paperclipai","paperclip-ai"]),kL=/^[a-z][a-z0-9-]*$/,ig=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function ag(){return{id:"",name:"",reasoning:!1}}function jL({initialConfig:e,onSave:n,onCancel:s,saving:a=!1,error:r}){const o=!!e,[l,c]=i.useState(e?.id??""),[d,u]=i.useState(e?.name??""),[m,h]=i.useState(e?.baseUrl??""),[f,p]=i.useState(e?.api??"openai-completions"),[g,x]=i.useState(e?.apiKey??""),[w,b]=i.useState(e?.models?.length?e.models:[ag()]),[y,S]=i.useState(null),j=w.length>1,C=i.useMemo(()=>y??r??null,[y,r]);function v(_,M){b(z=>z.map((U,R)=>R===_?{...U,...M}:U))}function N(_){b(M=>M.length<=1?M:M.filter((z,U)=>U!==_))}function I(){if(!l.trim())return"Provider ID is required.";if(!kL.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&wL.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const _=new URL(m.trim());if(_.protocol!=="http:"&&_.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return ig.includes(f)?w.length===0?"At least one model is required.":w.some(_=>!_.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function F(_){_.preventDefault();const M=I();S(M),!M&&await n({id:l.trim(),name:d.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:w.map(z=>({id:z.id.trim(),name:z.name?.trim()||void 0,reasoning:!!z.reasoning,contextWindow:z.contextWindow,maxTokens:z.maxTokens}))})}return t.jsxs("form",{onSubmit:F,className:"custom-provider-form","aria-label":"custom-provider-form",children:[t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-id",children:"Provider ID"}),t.jsx("input",{id:"custom-provider-id",className:"input",value:l,onChange:_=>c(_.target.value),disabled:o||a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-name",children:"Display Name"}),t.jsx("input",{id:"custom-provider-name",className:"input",value:d,onChange:_=>u(_.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-base-url",children:"Base URL"}),t.jsx("input",{id:"custom-provider-base-url",className:"input",value:m,onChange:_=>h(_.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api",children:"API Type"}),t.jsx("select",{id:"custom-provider-api",className:"select",value:f,onChange:_=>p(_.target.value),disabled:a,children:ig.map(_=>t.jsx("option",{value:_,children:_},_))})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api-key",children:"API Key"}),t.jsx("input",{id:"custom-provider-api-key",className:"input",placeholder:"sk-..., MY_API_KEY, or !command",value:g,onChange:_=>x(_.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{children:"Models"}),t.jsx("div",{className:"custom-provider-form__models",children:w.map((_,M)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${M+1}`,placeholder:"Model ID",value:_.id,onChange:z=>v(M,{id:z.target.value}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Model name ${M+1}`,placeholder:"Display name",value:_.name??"",onChange:z=>v(M,{name:z.target.value}),disabled:a}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!_.reasoning,onChange:z=>v(M,{reasoning:z.target.checked}),disabled:a}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${M+1}`,placeholder:"Context window",type:"number",value:_.contextWindow??"",onChange:z=>v(M,{contextWindow:z.target.value?Number(z.target.value):void 0}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Max tokens ${M+1}`,placeholder:"Max tokens",type:"number",value:_.maxTokens??"",onChange:z=>v(M,{maxTokens:z.target.value?Number(z.target.value):void 0}),disabled:a}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>N(M),disabled:a||!j,"aria-label":`Remove model ${M+1}`,children:"×"})]},`${M}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>b(_=>[..._,ag()]),disabled:a,children:"+ Add model"})]}),C?t.jsx("div",{className:"form-error",children:C}):null,t.jsxs("div",{className:"custom-provider-form__actions",children:[s?t.jsx("button",{type:"button",className:"btn",onClick:s,disabled:a,children:"Cancel"}):null,t.jsx("button",{type:"submit",className:"btn btn-primary",disabled:a,children:a?"Saving...":"Save Provider"})]})]})}const NL=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function SL(e){return!NL.has(e)}function rg(e){return e.filter(n=>SL(n.id))}const Mv={host:"web",activeProfileId:null,profiles:[]},Av=i.createContext({shellApi:null,state:Mv,ready:!0,openConnectionManagerSignal:0});function CL({children:e}){const n=i.useMemo(()=>typeof window<"u"?window.fusionShell??null:null,[]),[s,a]=i.useState(Mv),[r,o]=i.useState(!n),[l,c]=i.useState(0);return i.useEffect(()=>{if(!n)return;let d=!1;n.getState().then(h=>{d||(a(h),o(!0))});const u=n.subscribe(h=>{a(h)}),m=()=>{c(h=>h+1)};return window.addEventListener("shell:open-connection-manager",m),()=>{d=!0,u(),window.removeEventListener("shell:open-connection-manager",m)}},[n]),t.jsx(Av.Provider,{value:{shellApi:n,state:s,ready:r,openConnectionManagerSignal:l},children:e})}function EL(){return i.useContext(Av)}const _L={host:"web",activeProfileId:null,profiles:[]};function ML(e){if(!e)return _L;const n=Array.isArray(e.profiles)?e.profiles.filter(a=>!!(a&&a.id&&a.serverUrl)):[],s=e.activeProfileId&&n.some(a=>a.id===e.activeProfileId)?e.activeProfileId:null;return{...e,activeProfileId:s,profiles:n}}function ym(e){return new Error(`${e} is only available in native shell mode`)}async function AL(e,n){if(!e)throw ym("Saving connection profiles");return e.saveProfile(n)}async function RL(e,n){if(!e)throw ym("Deleting connection profiles");await e.deleteProfile(n)}async function IL(e,n){if(!e)throw ym("Switching connection profiles");return e.setActiveProfile(n)}function Rv(){const e=EL(),n=i.useMemo(()=>ML(e.state),[e.state]),s=i.useCallback(o=>AL(e.shellApi,o),[e.shellApi]),a=i.useCallback(o=>RL(e.shellApi,o),[e.shellApi]),r=i.useCallback(o=>IL(e.shellApi,o),[e.shellApi]);return{...e,state:n,saveProfile:s,removeProfile:a,setActiveProfile:r}}const Ua="fusion_model_onboarding_state",_r=[],Mr=[],ic=!1,ac=!1,Ar={},TL=void 0,aa=["ai-setup","github","project-setup","first-task"],PL={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function ai(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Ua);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?$L(n):null}catch{return null}}function $L(e){const n=e.postOnboardingDismissedAt??TL;return{...e,completedSteps:e.completedSteps??_r,skippedSteps:e.skippedSteps??Mr,dismissed:e.dismissed??ic,completed:e.completed??ac,stepData:e.stepData??Ar,...n?{postOnboardingDismissedAt:n}:{}}}function Al(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:_r,skippedSteps:Mr,dismissed:ic,completed:ac,stepData:Ar};try{localStorage.setItem(Ua,JSON.stringify(s))}catch{}return}try{const s=ai(),a=new Date().toISOString(),r=n.completed??ac;let o=n.dismissed??ic;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??_r,c=n.skippedSteps??s?.skippedSteps??Mr,d={...s?.stepData??Ar};if(n.stepData)for(const[m,h]of Object.entries(n.stepData))h!==void 0&&(d[m]={...d[m]??{},...h});const u={currentStep:e,updatedAt:a,completedSteps:l,skippedSteps:c,dismissed:o,completed:r,stepData:d};localStorage.setItem(Ua,JSON.stringify(u))}catch{}}}function DL(e){if(!(typeof window>"u"))try{const n=ai(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:_r,skippedSteps:[e],dismissed:ic,completed:ac,stepData:Ar};localStorage.setItem(Ua,JSON.stringify(o));return}const a=n.skippedSteps.includes(e)?n.skippedSteps:[...n.skippedSteps,e],r={...n,skippedSteps:a,completedSteps:n.completedSteps.filter(o=>o!==e),updatedAt:s};localStorage.setItem(Ua,JSON.stringify(r))}catch{}}function og(){if(!(typeof window>"u"))try{const e=ai(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:_r,skippedSteps:Mr,dismissed:!1,completed:!0,stepData:Ar};localStorage.setItem(Ua,JSON.stringify(s))}catch{}}function Rr(){const e=ai();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function LL(){if(!(typeof window>"u"))try{const e=ai(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:_r,skippedSteps:Mr,dismissed:!1,completed:!1,stepData:Ar,postOnboardingDismissedAt:n};localStorage.setItem(Ua,JSON.stringify(s))}catch{}}function Iv(){const e=ai();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function OL(){const e=ai();return!e||Rr()?!1:e.currentStep!=="complete"}function FL(){const e=ai();if(!e||Rr()||e.currentStep==="complete")return null;const n=e.currentStep,s=PL[n]??UL(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function zL(){const e=ai();return e?e.skippedSteps:Mr}function BL(e){const n=ai();return!n||!n.stepData?null:n.stepData[e]??null}function UL(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const Tv="fusion_onboarding_events",lg="fusion_onboarding_session_id",HL=200,qL=50;function ci(e,n={}){if(!(typeof window>"u"))try{const s=WL(),a=JL(n.step),r={type:e,timestamp:new Date().toISOString(),...a?{step:a}:{},metadata:n,sessionId:VL()},o=GL([...s,r]);KL(o)}catch{}}function VL(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(lg);if(e)return e;const n=cg();return sessionStorage.setItem(lg,n),n}catch{return cg()}}function cg(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function WL(){try{const e=localStorage.getItem(Tv);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(YL):[]}catch{return[]}}function KL(e){try{localStorage.setItem(Tv,JSON.stringify(e))}catch{}}function GL(e){const n=[...e];for(;n.length>HL;)n.splice(0,qL);return n}function JL(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function YL(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.type=="string"&&typeof n.timestamp=="string"&&typeof n.sessionId=="string"&&!!n.metadata&&typeof n.metadata=="object"}const QL=e=>({id:e.id,name:e.name,baseUrl:e.baseUrl,api:"api"in e?e.api:e.apiType==="anthropic-compatible"?"anthropic-messages":"openai-responses",apiKey:e.apiKey,models:e.models?.map(n=>({id:n.id,name:n.name}))??[]}),XL={anthropic:{description:"Claude models — strong at reasoning, analysis, and code"},openai:{description:"GPT models — versatile for a wide range of tasks",apiKeyInfo:{fieldLabel:"OpenAI API Key",setupInstructions:"Create an API key from your OpenAI dashboard under API keys.",dashboardUrl:"https://platform.openai.com/api-keys",inputPlaceholder:"sk-...",usageDescription:"Used for GPT models in task execution and planning"}},"openai-codex":{description:"Codex models by OpenAI — optimized for coding tasks"},google:{description:"Gemini models — multimodal with strong reasoning"},gemini:{description:"Gemini models — multimodal with strong reasoning"},ollama:{description:"Run open-source models locally on your machine",apiKeyInfo:{fieldLabel:"Ollama Endpoint",setupInstructions:"Enter your Ollama endpoint URL (for example http://localhost:11434).",inputPlaceholder:"http://localhost:11434",usageDescription:"Connects to your local Ollama instance"}},minimax:{description:"MiniMax models — cost-effective for high-volume usage",apiKeyInfo:{fieldLabel:"MiniMax API Key",setupInstructions:"Generate an API key from the MiniMax platform developer console.",dashboardUrl:"https://platform.minimaxi.com/",inputPlaceholder:"Enter your MiniMax API key",usageDescription:"Used for MiniMax models in task execution"}},zai:{description:"GLM models by Zhipu AI — strong multilingual support",apiKeyInfo:{fieldLabel:"Zhipu AI API Key",setupInstructions:"Create an API key in the Zhipu AI open platform account settings.",dashboardUrl:"https://open.bigmodel.cn/",inputPlaceholder:"Enter your Zhipu AI API key",usageDescription:"Used for GLM models in task execution"}},kimi:{description:"Kimi by Moonshot AI — long-context capabilities"},moonshot:{description:"Kimi by Moonshot AI — long-context capabilities"},"kimi-coding":{description:"Kimi by Moonshot AI — long-context capabilities",apiKeyInfo:{fieldLabel:"Kimi API Key",setupInstructions:"Create your API key in the Moonshot platform account settings.",dashboardUrl:"https://platform.moonshot.cn/",inputPlaceholder:"Enter your Kimi API key",usageDescription:"Used for Kimi/Moonshot AI models in task execution and planning"}},openrouter:{description:"OpenRouter — route requests across multiple AI providers",apiKeyInfo:{fieldLabel:"OpenRouter API Key",setupInstructions:"Create an API key from your OpenRouter account key management page.",dashboardUrl:"https://openrouter.ai/keys",inputPlaceholder:"sk-or-v1-...",usageDescription:"Routes to multiple AI model providers through a single key"}}},Pv={anthropic:{pattern:/^sk-ant-/,hint:"Starts with sk-ant-",example:"sk-ant-api03-..."},openai:{pattern:/^sk-/,hint:"Starts with sk-",example:"sk-..."},"openai-codex":{pattern:/^sk-/,hint:"Starts with sk-",example:"sk-..."},openrouter:{pattern:/^sk-or-/,hint:"Starts with sk-or-",example:"sk-or-v1-..."},google:{pattern:/^AIza/,hint:"Starts with AIza",example:"AIza..."},gemini:{pattern:/^AIza/,hint:"Starts with AIza",example:"AIza..."},minimax:{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},ollama:{pattern:/^.+$/,hint:"Any non-empty value",example:"ollama"},zai:{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},kimi:{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},"kimi-coding":{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},moonshot:{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."}},ZL={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},dg={anthropic:"Anthropic",openai:"OpenAI","openai-codex":"OpenAI Codex",openrouter:"OpenRouter",google:"Google",gemini:"Gemini",minimax:"MiniMax",ollama:"Ollama",zai:"Zhipu AI",kimi:"Kimi","kimi-coding":"Kimi Coding",moonshot:"Moonshot"};function Eu(e){if(dg[e])return dg[e];const n=e.trim();return n?n.split(/[-_\s]+/).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"This provider"}const Hd=["anthropic","openai","google","gemini","ollama"],eO=["anthropic","claude-cli","droid-cli","cursor-cli","llama-cpp","openai-codex","gemini","minimax","kimi","zai"],tO={anthropic:"anthropic","claude-cli":"claude-cli","droid-cli":"droid-cli","llama-cpp":"llama-cpp","openai-codex":"openai-codex",google:"gemini",gemini:"gemini",minimax:"minimax",kimi:"kimi",moonshot:"kimi","kimi-coding":"kimi",zai:"zai"},nO={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function _u(e){return tO[e]??e}function ug(e){const n=_u(e),s=eO.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function mg(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=ug(e.id),a=ug(n.id);if(s!==a)return s-a;const r=_u(e.id),o=_u(n.id);if(r!==o)return r.localeCompare(o);const l=nO[r];if(l){const d=l.indexOf(e.id),u=l.indexOf(n.id);if(d!==u)return(d===-1?Number.POSITIVE_INFINITY:d)-(u===-1?Number.POSITIVE_INFINITY:u)}const c=e.name.localeCompare(n.name);return c!==0?c:e.id.localeCompare(n.id)}function sO(e,n){const s=n.trim();if(!s)return"API key is required";const a=Pv[e]??ZL;return a.pattern.test(s)?null:`${Eu(e)} keys should follow this format: ${a.hint} (e.g. ${a.example})`}const $v={fieldLabel:"API Key",setupInstructions:"Enter your API key for this provider.",inputPlaceholder:"Enter API key",usageDescription:"Used by Fusion to authenticate requests to this provider"},iO={description:"AI provider — connect to start using AI models",apiKeyInfo:$v};function Mu(e){return XL[e]??iO}function aO(e){return Mu(e.id).apiKeyInfo??$v}function rO({items:e}){return e.some(s=>s.status!=="connected")?t.jsxs("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:[t.jsx("p",{className:"onboarding-readiness-header",children:"Setup Summary"}),e.map(s=>{const a=s.status==="connected"?"✓":s.status==="missing"?"⚠":"○";return t.jsxs("div",{className:`onboarding-readiness-item onboarding-readiness-item--${s.status}`,"data-status":s.status,children:[t.jsx("span",{className:"onboarding-readiness-icon","aria-hidden":"true",children:a}),t.jsxs("span",{className:"onboarding-readiness-content",children:[t.jsx("span",{className:"onboarding-readiness-label",children:s.label}),s.detail&&t.jsx("span",{className:"onboarding-readiness-detail",children:s.detail})]})]},s.label)})]}):t.jsx("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:t.jsx("p",{className:"onboarding-readiness-all-connected",children:"✓ All integrations connected"})})}function oO({provider:e,apiKeyInfo:n,inputValue:s,isSaving:a,error:r,success:o,isConnected:l,onInputChange:c,onSave:d,onClear:u}){const m=`onboarding-apikey-input-${e.id}`,h=a||!s.trim(),f=Pv[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,g=t.jsxs(t.Fragment,{children:[f&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",f.hint]}),t.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&t.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),t.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return l?t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsxs("div",{className:"onboarding-apikey-connected-header",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),t.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),t.jsx("button",{className:"btn btn-sm",onClick:()=>u(e.id),disabled:a,children:a?"Removing…":"Remove Key"}),t.jsx(di,{summary:"Advanced setup details",children:g}),r&&t.jsx("small",{className:"field-error",children:r})]}):t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsx("label",{htmlFor:m,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:m,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:x=>c(e.id,x.target.value),onKeyDown:x=>{x.key==="Enter"&&d(e.id,s)},"data-testid":m}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>d(e.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${e.id}`,children:a?"Saving…":"Save"})]}),r&&t.jsx("small",{className:"field-error",children:r}),o&&!r&&t.jsx("small",{className:"onboarding-apikey-success","data-testid":`onboarding-apikey-success-${e.id}`,children:o}),t.jsx(di,{summary:"Advanced setup details",children:g})]})}const lO=150;function cO({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:a,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const d=ai(),u=d?.currentStep,m=u==="complete"?"ai-setup":aa.includes(u)?u:"ai-setup",h=d?.completedSteps??[],f=d?.skippedSteps??zL(),[p,g]=i.useState(!0),[x,w]=i.useState(m),[b,y]=i.useState(h),[S,j]=i.useState(f),[C,v]=i.useState(!1),[N,I]=i.useState(""),[F,_]=i.useState(!1),[M,z]=i.useState(null),[U,R]=i.useState(null),[D,K]=i.useState([]),[Z,ne]=i.useState(void 0),[O,A]=i.useState(!0),[P,$]=i.useState(null),[k,J]=i.useState({}),[ce,je]=i.useState({}),[He,xe]=i.useState({}),[Ne,Y]=i.useState(null),[ie,ee]=i.useState([]),[oe,W]=i.useState(""),[L,pe]=i.useState(!1),[fe,B]=i.useState({}),[ve,Fe]=i.useState({}),[ae,qe]=i.useState({}),[Pe,nt]=i.useState([]),[Be,de]=i.useState(!1),[Ie,$e]=i.useState(!1),[st,Ue]=i.useState(),[me,re]=i.useState("Remote Server"),[_e,xt]=i.useState(""),[ut,Qe]=i.useState(""),[vt,Ae]=i.useState(!1),[Je,dt]=i.useState(null),Nt=i.useRef({}),yt=i.useRef(null),Se=i.useRef(null),G=i.useRef(null),[ge,pt]=i.useState({}),[ke,tt]=i.useState(()=>ai()?.stepData?.github?.skipped===!0),Rt=i.useRef(0),Re=i.useRef(l),{shellApi:be,state:rt}=Rv(),lt=i.useRef(!1),gt=d?.currentStep,St=!!d&&d.currentStep!=="complete";Li(Se,p,"fusion:model-onboarding-modal-size"),i.useEffect(()=>{const E=yt.current;E&&(E.scrollTop=0)},[x]);const[Lt,Yt]=i.useState(()=>ai()?.stepData?.["ai-setup"]?.skippedProviders??{}),tn=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],mn=tn.findIndex(E=>E.key===x),Qt=x==="complete"?tn.length:mn;i.useEffect(()=>{x!=="complete"&&Al(x,{completedSteps:b,skippedSteps:S})},[x,b,S]),i.useEffect(()=>{lt.current||(lt.current=!0,ci("onboarding:wizard-opened",{source:St?"resume":"initial",resumedFromStep:gt}))},[St,gt]),i.useEffect(()=>{const E=Re.current!=null,ue=l!=null;!E&&ue&&v(!0),ue||v(!1),Re.current=l},[l]);const yn=i.useRef(m);i.useEffect(()=>{if(yn.current==="ai-setup"&&x!=="ai-setup"&&!D.some(ue=>ue.id!=="github"&&ue.authenticated)){const ue={};for(const Ce of D)Ce.id!=="github"&&!Ce.authenticated&&!Lt[Ce.id]&&(ue[Ce.id]=!0);if(Object.keys(ue).length>0){const Ce={...Lt,...ue};Yt(Ce),Al(x,{stepData:{"ai-setup":{skippedProviders:Ce}}})}}yn.current=x},[x,D,Lt]);const Gt=i.useCallback(async()=>{try{const{providers:E,ghCli:ue}=await Eo(),Ce=rg(E);K(Ce),ne(ue),J(We=>{const At={};for(const[q,we]of Object.entries(We)){const Oe=Ce.find(It=>It.id===q);Oe&&!Oe.authenticated&&Oe.loginInProgress&&(At[q]=we)}return Object.keys(At).length===Object.keys(We).length?We:At}),pt(We=>{let At=!1;const q={...We};for(const[we,Oe]of Object.entries(We)){if(Oe!=="pending")continue;Ce.find(Kt=>Kt.id===we)?.loginInProgress||(delete q[we],At=!0)}return At?q:We}),Yt(We=>{const At={...We};for(const q of Ce)q.authenticated&&At[q.id]&&delete At[q.id];return Object.keys(At).length===Object.keys(We).length?We:At})}catch{}},[]),on=i.useCallback(async()=>{try{const E=await uN();nt((E.providers??[]).map(QL))}catch{}},[]),sn=i.useCallback(async E=>{$e(!0),Ue(void 0);try{await hN(E),await on(),await Ks().then(ue=>ee(ue.models??[])),de(!1)}catch(ue){Ue(Ee(ue)||"Failed to create custom provider")}finally{$e(!1)}},[on]),ln=i.useRef(!1);i.useEffect(()=>{x==="ai-setup"&&on(),ln.current&&Gt(),ln.current=x!=="ai-setup"},[x,Gt,on]),i.useEffect(()=>{if(!D.some(Ce=>Ce.loginInProgress))return;const ue=setInterval(()=>{Gt()},2e3);return()=>clearInterval(ue)},[D,Gt]);const Wt=D.find(E=>E.id==="github"),ye=!!Wt,Le=Wt?.authenticated??!1,Ke=Wt?.loginInProgress??!1,mt=Z?.authenticated??!1,Ve=Le||mt,Pt=!Le&&mt,Ot=i.useCallback(E=>{if(E.authenticated)return"connected";const ue=ge?.[E.id];return ue==="timeout"||ue==="failed"?"retry":Lt[E.id]?"skipped":"not-connected"},[ge,Lt]);function bt({status:E}){const ue={connected:{text:"✓ Connected",className:"auth-status-badge connected"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},retry:{text:"Retry",className:"auth-status-badge retry"}},{text:Ce,className:We}=ue[E];return t.jsx("span",{"data-testid":"provider-status-badge",className:We,"data-status":E,children:Ce})}const Dt=i.useCallback(()=>{if(Ve)return"connected";const E=ge.github;return E==="pending"?"pending":E==="failed"||E==="timeout"?"failed":ke?"skipped":"not-connected"},[Ve,ge,ke]);function Ft({status:E}){const ue={connected:{text:"✓ Connected",className:"auth-status-badge connected"},pending:{text:"⏳ Connecting…",className:"auth-status-badge pending"},failed:{text:"✗ Connection failed",className:"auth-status-badge retry"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"}},{text:Ce,className:We}=ue[E];return t.jsx("span",{"data-testid":"github-status-badge",className:We,"data-status":E,children:Ce})}const Ht=i.useCallback(async()=>{try{const E=await Ks();ee(E.models)}catch{}},[]),rn=i.useCallback(async()=>{try{const E=await Yi();if(E.defaultProvider&&E.defaultModelId){const ue=`${E.defaultProvider}/${E.defaultModelId}`;W(ue)}}catch{}},[]);i.useEffect(()=>{Promise.all([Gt(),Ht(),rn()]).finally(()=>A(!1))},[Gt,Ht,rn]),i.useEffect(()=>{const E=BL("ai-setup");if(E?.loginOutcomes){const ue=E.loginOutcomes,Ce={};for(const[We,At]of Object.entries(ue))At!=="pending"&&(Ce[We]=At);Object.keys(Ce).length>0&&pt(Ce)}},[]);const Xt=i.useCallback((E,ue)=>{Al(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[E]:ue}}}})},[x,b]);i.useEffect(()=>{const E=Object.entries(ge).filter(([ue,Ce])=>Ce!=="pending");for(const[ue,Ce]of E)Xt(ue,Ce)},[ge,Xt]),i.useEffect(()=>()=>{G.current&&clearInterval(G.current),Object.values(Nt.current).forEach(clearTimeout),Nt.current={}},[]);const an=i.useCallback(E=>{tt(E),Al(x,{completedSteps:b,stepData:{github:{skipped:E}}})},[x,b]),Me=i.useCallback(E=>E==="complete"?-1:aa.indexOf(E),[]),it=i.useCallback(()=>{y(ue=>[...new Set([...ue,x])]),j(ue=>ue.filter(Ce=>Ce!==x)),ci("onboarding:step-completed",{step:x}),x==="github"&&!Le&&an(!1);const E=Me(x);E>=0&&E<aa.length-1&&w(aa[E+1])},[x,Le,an,Me]),kt=i.useCallback(()=>{j(ue=>[...new Set([...ue,x])]),DL(x),ci("onboarding:step-skipped",{step:x}),x==="github"&&!Le&&an(!0);const E=Me(x);E>=0&&E<aa.length-1&&w(aa[E+1])},[x,Le,an,Me]),$t=i.useCallback(()=>{const E=x;y(Ce=>Ce.filter(We=>We!==E)),j(Ce=>Ce.filter(We=>We!==E)),E==="github"&&!Le&&an(!1);const ue=Me(x);ue>0&&w(aa[ue-1])},[x,Le,an,Me]),se=i.useCallback(()=>{kt()},[kt]),te=i.useCallback(async E=>{pt(Ce=>{const We=Ce[E];if(We&&We!=="pending"){const{[E]:At,...q}=Ce;return q}return Ce});const ue=()=>{J(Ce=>{if(!(E in Ce))return Ce;const We={...Ce};return delete We[E],We}),je(Ce=>{if(!(E in Ce))return Ce;const We={...Ce};return delete We[E],We}),xe(Ce=>{if(!(E in Ce))return Ce;const We={...Ce};return delete We[E],We})};ue(),pt(Ce=>({...Ce,[E]:"pending"})),$(E),Rt.current=0;try{const{url:Ce,instructions:We,manualCode:At}=await pN(E);We?.trim()&&J(q=>({...q,[E]:We})),At&&je(q=>({...q,[E]:At})),window.open(Di(Ce),"_blank"),G.current=setInterval(async()=>{if(Rt.current++,Rt.current>=lO){G.current&&(clearInterval(G.current),G.current=null),$(null),K(q=>q.map(we=>we.id===E?{...we,loginInProgress:!1}:we)),pt(q=>({...q,[E]:"timeout"})),ue(),n("Login timed out. Please try again.","warning");return}try{const{providers:q,ghCli:we}=await Eo(),Oe=rg(q);K(Oe),ne(we);const It=Oe.find(Kt=>Kt.id===E);if(It?.authenticated){G.current&&(clearInterval(G.current),G.current=null),$(null),pt(Kt=>({...Kt,[E]:"success"})),ue(),E==="github"&&an(!1),n("Login successful","success");return}It?.loginInProgress||(G.current&&(clearInterval(G.current),G.current=null),$(null),pt(Kt=>({...Kt,[E]:"failed"})),ue(),n("Login did not complete. Please try again.","error"))}catch{}},2e3)}catch(Ce){Ce instanceof Error&&Ce.message.includes("already in progress")||Ce&&typeof Ce=="object"&&"status"in Ce&&Ce.status===409?(n("Login already in progress. Cancel it to retry.","warning"),pt(At=>({...At,[E]:"pending"})),Gt()):(n(Ce instanceof Error?Ce.message:"Login failed","error"),pt(At=>({...At,[E]:"failed"}))),$(null),ue()}},[n,Gt,an]),De=i.useCallback(async E=>{const ue=He[E]?.trim();if(!ue){n("Paste the full redirect URL or authorization code first.","warning");return}Y(E);try{(await fN(E,ue)).submitted?(xe(We=>{if(!(E in We))return We;const At={...We};return delete At[E],At}),n("Authorization code received. Finishing login…","success")):n("That authorization code was already submitted. Waiting for login…","warning")}catch(Ce){n(Ee(Ce)||"Failed to submit authorization code","error")}finally{Y(null)}},[n,He]),ft=i.useCallback(async E=>{G.current&&(clearInterval(G.current),G.current=null),$(E),Rt.current=0,K(ue=>ue.map(Ce=>Ce.id===E?{...Ce,loginInProgress:!1}:Ce)),pt(ue=>({...ue,[E]:"cancelled"}));try{await bN(E),await Gt().catch(()=>{}),n("Login cancelled","success")}catch(ue){n(Ee(ue)||"Failed to cancel login","error")}finally{$(null),J(ue=>{if(!(E in ue))return ue;const Ce={...ue};return delete Ce[E],Ce}),je(ue=>{if(!(E in ue))return ue;const Ce={...ue};return delete Ce[E],Ce}),xe(ue=>{if(!(E in ue))return ue;const Ce={...ue};return delete Ce[E],Ce}),Y(ue=>ue===E?null:ue)}},[n,Gt]),qt=i.useCallback((E,ue)=>{B(We=>({...We,[E]:ue}));const Ce=Nt.current[E];Ce&&(clearTimeout(Ce),delete Nt.current[E]),Fe(We=>{if(!We[E])return We;const At={...We};return delete At[E],At}),qe(We=>{if(!We[E])return We;const At={...We};return delete At[E],At})},[]),zt=i.useCallback(()=>{const E=yt.current;if(!E)return;const ue=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof E.scrollTo=="function"){E.scrollTo({top:0,behavior:ue?"auto":"smooth"});return}}catch{}E.scrollTop=0},[]),Pn=i.useCallback(async(E,ue)=>{const Ce=(ue??fe[E]??"").trim(),We=sO(E,Ce);if(We){Fe(q=>({...q,[E]:We}));return}const At=Nt.current[E];At&&(clearTimeout(At),delete Nt.current[E]),$(E),Fe(q=>{const we={...q};return delete we[E],we}),qe(q=>{if(!q[E])return q;const we={...q};return delete we[E],we});try{await xN(E,Ce),await Gt(),zt(),B(q=>{const we={...q};return delete we[E],we}),Fe(q=>{if(!q[E])return q;const we={...q};return delete we[E],we}),qe(q=>({...q,[E]:"✓ Key saved"})),Nt.current[E]=setTimeout(()=>{qe(q=>{if(!q[E])return q;const we={...q};return delete we[E],we}),delete Nt.current[E]},3e3),n("API key saved","success")}catch(q){const we=q instanceof TypeError&&q.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":q instanceof Error?q.message:"Failed to save API key";Fe(Oe=>({...Oe,[E]:we})),qe(Oe=>{if(!Oe[E])return Oe;const It={...Oe};return delete It[E],It}),n(we,"error")}finally{$(null)}},[fe,n,Gt,zt]),he=i.useCallback(async E=>{$(E);try{await vN(E),await Gt(),n("API key removed","success")}catch(ue){n(ue instanceof Error?ue.message:"Failed to clear API key","error")}finally{$(null)}},[n,Gt]),ht=i.useCallback(async E=>{$(E);try{await gN(E),await Gt(),n("Logged out","success")}catch(ue){n(ue instanceof Error?ue.message:"Logout failed","error")}finally{$(null)}},[n,Gt]),at=i.useCallback(E=>{W(E)},[]),wt=i.useCallback(async()=>{try{const E={modelOnboardingComplete:!0};if(oe){const ue=oe.indexOf("/"),Ce=ue!==-1?oe.slice(0,ue):void 0,We=ue!==-1?oe.slice(ue+1):oe,At=ie.find(q=>q.id===We);At?(E.defaultProvider=At.provider,E.defaultModelId=At.id):Ce&&We&&(E.defaultProvider=Ce,E.defaultModelId=We)}await Dn(E),og()}catch{}},[oe,ie,Dn,og]),Xe=i.useCallback(async()=>{const E=[...new Set([...b,"first-task"])];pe(!0);try{await wt(),ci("onboarding:completed",{completedSteps:E,skippedSteps:S}),y(E),j(ue=>ue.filter(Ce=>Ce!=="first-task")),w("complete")}finally{pe(!1)}},[wt,b,S]),Et=i.useCallback(async()=>{if(!s)return;const E=N.trim();if(!E){z("Please enter a task description.");return}z(null),_(!0);let ue=!1;try{const Ce=await ib({description:E,source:{sourceType:"dashboard_ui"}},s);R(Ce),v(!0),ci("onboarding:first-task-created",{taskId:Ce?.id}),n("Task created","success"),ue=!0}catch(Ce){const We=Ce instanceof Error?Ce.message:"Something went wrong creating your task. Please try again.";z(We),n(We,"error")}finally{_(!1)}ue&&wt()},[s,N,n,wt]),Zt=i.useCallback(async()=>{pe(!0);try{await wt()}finally{pe(!1)}ci("onboarding:open-new-task",{}),r?.()},[wt,r]),le=i.useCallback(async()=>{if(Ve){pe(!0);try{await wt()}finally{pe(!1)}g(!1),e(),ci("onboarding:open-github-import",{}),o?.()}},[wt,Ve,e,o]),ct=i.useCallback(async()=>{ci("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:S}),pe(!0);try{await Dn({modelOnboardingComplete:!0})}catch{}g(!1),e()},[x,b,S,e]),nn=i.useCallback(()=>{ci("onboarding:finished",{}),g(!1),e()},[e]),Rn=i.useCallback(()=>{const E=l??U;E&&(wt(),c?.(E),e())},[l,U,wt,c,e]),Un=i.useCallback(()=>{wt(),e()},[wt,e]),wn=Dt(),rs=D.filter(E=>E.id!=="github"),_s=rt.host!=="web"&&!rt.activeProfileId,bn=[...rs].sort(mg),Ut=bn.some(E=>!E.type||E.type==="oauth"),xs=bn.some(E=>E.type==="api_key"),xn=rs.filter(E=>E.authenticated),Xn=xn.length>0,$n=!!s,vs=x==="github"&&!Xn,ms=i.useCallback(async()=>{if(be){dt(null),Ae(!0);try{const E=await be.saveProfile({name:me,serverUrl:_e,authToken:ut.trim()?ut:null});try{await be.setActiveProfile(E.id)}catch(ue){dt(Ee(ue)||"Saved profile but failed to activate it");return}xt(""),Qe(""),n("Remote server profile saved","success")}catch(E){dt(Ee(E)||"Failed to save shell connection")}finally{Ae(!1)}}},[be,me,_e,ut,n]);if(!p)return null;const hs=(()=>{if(!oe)return"";const E=oe.indexOf("/"),ue=E===-1?void 0:oe.slice(0,E),Ce=E===-1?oe:oe.slice(E+1),We=ie.find(At=>At.id===Ce&&(!ue||At.provider===ue));return We?.name?We.name:ue?`${Eu(ue)} ${Ce}`:oe})(),Jn=[];if($n?Jn.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):Jn.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Xn){const E=Eu(xn[0]?.id??"");Jn.push({label:"AI Provider",status:"connected",detail:`${E} connected — AI agents can work on tasks`})}else rs.length>0&&rs.some(E=>Lt[E.id])?Jn.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):Jn.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});Ve?Jn.push({label:"GitHub",status:"connected",detail:Pt?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!ye||ke?Jn.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):Jn.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),hs&&Jn.push({label:"Default Model",status:"connected",detail:hs});const ps=l??U,Ns=ps?.description?.split(`
692
+ `)[0]?.trim()||ps?.title||"",Yn=new Set(Hd),ys=bn.filter(E=>Yn.has(E.id)).sort((E,ue)=>{const Ce=Hd.indexOf(E.id),We=Hd.indexOf(ue.id);return Ce!==We?Ce-We:mg(E,ue)}),ws=bn.filter(E=>E.authenticated&&!Yn.has(E.id)),Ms=bn.filter(E=>!E.authenticated&&!Yn.has(E.id)),X=E=>{const ue=ge[E.id]==="timeout"||ge[E.id]==="failed"||ge[E.id]==="cancelled",Ce=E.loginInProgress&&!ue;if(E.id==="llama-cpp"&&E.type==="cli")return t.jsx(xL,{authenticated:E.authenticated,onToggled:()=>{Gt()}},E.id);if(E.id==="claude-cli"&&E.type==="cli")return t.jsx(fL,{authenticated:E.authenticated,onToggled:()=>{Gt()}},E.id);if(E.id==="cursor-cli"&&E.type==="cli")return t.jsx(bL,{authenticated:E.authenticated,onToggled:()=>{Gt()}},E.id);if(E.type==="api_key"){const We=Mu(E.id),At=aO(E);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${E.id}`,className:`onboarding-provider-card${E.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${E.id}`,"aria-hidden":"true",children:t.jsx(Fn,{provider:E.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(Qg,{size:14,className:"onboarding-provider-key-icon"}),E.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:We.description}),t.jsx(bt,{status:Ot(E)}),E.authenticated&&E.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",E.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(oO,{provider:E,apiKeyInfo:At,inputValue:fe[E.id]??"",isSaving:P===E.id,error:ve[E.id],success:ae[E.id],isConnected:E.authenticated,onInputChange:qt,onSave:Pn,onClear:he})})]},E.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${E.id}`,className:`onboarding-provider-card${E.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${E.id}`,"aria-hidden":"true",children:t.jsx(Fn,{provider:E.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:E.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:Mu(E.id).description}),t.jsx(bt,{status:Ot(E)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:P===E.id?E.authenticated?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void ft(E.id),children:"Cancel"})]}):Ce?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void ft(E.id),children:"Cancel"})]}):E.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>ht(E.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>te(E.id),children:"Login"})}),(P===E.id||Ce)&&k[E.id]&&t.jsx(Ud,{instructions:k[E.id],"data-testid":`onboarding-login-instructions-${E.id}`}),(P===E.id||Ce)&&ce[E.id]&&t.jsx(yL,{value:He[E.id]??"",onChange:We=>xe(At=>({...At,[E.id]:We})),onSubmit:()=>void De(E.id),prompt:ce[E.id].prompt,placeholder:ce[E.id].placeholder,helpText:ce[E.id].helpText,disabled:Ne===E.id,submitLabel:Ne===E.id?"Submitting…":"Submit code","data-testid":`onboarding-manual-code-${E.id}`}),ge[E.id]==="timeout"&&P!==E.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),ge[E.id]==="failed"&&P!==E.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},E.id)};return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",children:t.jsxs("div",{className:"modal model-onboarding-modal",ref:Se,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(as,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(si,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Am,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Am,{size:24})," Create Your First Task"]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(Gn,{size:24})," All Set!"]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:ct,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(un,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:tn.map((E,ue)=>{const Ce=Qt>ue,We=b.includes(E.key)&&Ce,At=S.includes(E.key)&&!b.includes(E.key)&&Ce,q=We||At;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[ue>0&&t.jsx("div",{className:`model-onboarding-step-connector ${ue<=Qt?"done":""}`}),q?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===E.key?"active":""} ${We?"done":""} ${At?"skipped":""}`,onClick:()=>w(E.key),"aria-label":`Go back to ${E.label}`,title:`Review ${E.label}`,children:[t.jsx("span",{className:"step-number",children:We?t.jsx(Gn,{size:14}):At?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):ue+1}),t.jsx("span",{className:"step-label",children:E.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===E.key?"active":""} ${We?"done":""} ${At?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:We?t.jsx(Gn,{size:14}):At?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):ue+1}),t.jsx("span",{className:"step-label",children:E.label})]})]},E.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:yt,children:[x==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),t.jsx("p",{className:"onboarding-helper-text",children:"Research runs require provider credentials and an enabled Research View. After onboarding, verify these in Settings → Authentication and Settings → Experimental Features."}),_s&&t.jsxs("div",{className:"card",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Connect remote Fusion server"}),t.jsx("p",{className:"onboarding-helper-text",children:"Your native shell needs an active remote profile before dashboard handoff can complete."}),t.jsx("label",{htmlFor:"onboarding-shell-profile-name",className:"onboarding-apikey-field-label",children:"Profile name"}),t.jsx("input",{id:"onboarding-shell-profile-name",className:"input",value:me,onChange:E=>re(E.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-server-url",className:"onboarding-apikey-field-label",children:"Server URL"}),t.jsx("input",{id:"onboarding-shell-server-url",className:"input",placeholder:"https://your-fusion-host",value:_e,onChange:E=>xt(E.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-token",className:"onboarding-apikey-field-label",children:"Auth token (optional)"}),t.jsx("input",{id:"onboarding-shell-token",className:"input",type:"password",value:ut,onChange:E=>Qe(E.target.value)}),Je&&t.jsx("small",{className:"field-error",children:Je}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void be?.openConnectionManager(),children:"Open manager"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void ms(),disabled:!_e.trim()||vt,children:vt?"Saving…":"Save remote server"})]})]}),!O&&D.length>0&&(()=>{const E=D.filter(q=>q.id!=="github"&&q.authenticated).length,ue=D.filter(q=>q.id!=="github").length,Ce=Object.keys(Lt).filter(q=>!D.find(we=>we.id===q)?.authenticated).length;if(ue===0)return null;let We="onboarding-provider-summary",At="";return E>0?(We+=" onboarding-provider-summary--connected",At=`✓ ${E} of ${ue} provider${ue!==1?"s":""} connected`):Ce>0?(We+=" onboarding-provider-summary--skipped",At=`${Ce} provider${Ce!==1?"s":""} skipped`):(We+=" onboarding-provider-summary--none",At="No providers connected yet"),t.jsx("div",{className:We,"data-testid":"provider-summary",children:At})})(),t.jsx(la,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(di,{summary:"What are AI providers?",children:t.jsx("p",{className:"onboarding-helper-text",children:"AI providers like OpenAI and Anthropic power the AI capabilities in Fusion. Connecting a provider lets Fusion's agents use AI models to help with your tasks."})}),D.length>0&&!D.some(E=>E.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),O?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(jt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):D.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):t.jsxs(t.Fragment,{children:[t.jsx(la,{slotId:"onboarding-provider-card",projectId:s,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{Gt()}}}),t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Quick start providers"}),ys.length>0?t.jsx("div",{className:"model-onboarding-providers",children:ys.map(E=>X(E))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),ws.length>0&&t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-connected-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Connected providers"}),t.jsx("div",{className:"model-onboarding-providers",children:ws.map(E=>X(E))})]}),t.jsxs("div",{className:"onboarding-model-section",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Default Model (Optional)"}),t.jsx("p",{className:"model-onboarding-description",children:"Pick a default model for AI tasks, or leave this blank to choose later. Models vary in speed, capability, and cost."}),t.jsx(di,{summary:"How do I choose a model?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Models vary in speed, capability, and cost. A good default is usually the latest model from your connected provider. You can always change this later in Settings."})}),ie.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No models available yet. Connect a provider above to see model options."}):t.jsx("div",{className:"onboarding-model-selector",children:t.jsx(Is,{models:ie,value:oe,onChange:at,placeholder:"Select a default model…",label:"Default model"})}),oe&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",ie.find(E=>E.id===oe)?.name??oe]})})]}),t.jsx(di,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[Ms.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Ms.map(E=>X(E))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),Pe.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:Pe.map(E=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(Fn,{provider:E.id,size:"sm"}),t.jsx("span",{children:E.name||E.id})]},E.id))}):null,Be?t.jsx(jL,{onSave:sn,onCancel:()=>{de(!1),Ue(void 0)},saving:Ie,error:st}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>de(!0),children:"Add custom provider"})]})}),Ut&&t.jsx(di,{summary:"How does login work?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Clicking Login opens the provider's website in a new tab where you sign in. Once you authorize Fusion, this page will automatically detect the connection. Your credentials are never stored in Fusion."})}),xs&&t.jsx(di,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})}),t.jsx(la,{slotId:"onboarding-setup-help",projectId:s})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[Ve?t.jsx("p",{className:"model-onboarding-description",children:Pt?"GitHub CLI is already authenticated — issue imports and pull request tracking work right now. You're all set; no further action needed.":"GitHub is connected — issue imports and pull request tracking are available. You're all set; no further action needed."}):t.jsx("p",{className:"model-onboarding-description",children:"Connecting GitHub unlocks issue imports and pull request tracking. You can skip this — task creation works without it."}),!Ve&&t.jsx("div",{className:"onboarding-feature-list",children:t.jsxs("ul",{children:[t.jsx("li",{className:"onboarding-feature-list-heading",children:t.jsx("strong",{children:"Without GitHub (available now):"})}),t.jsx("li",{className:"onboarding-helper-text",children:"Create tasks manually"}),t.jsx("li",{className:"onboarding-helper-text",children:"Describe work for AI agents"}),t.jsx("li",{className:"onboarding-helper-text",children:"Track progress on the board"}),t.jsx("li",{className:"onboarding-feature-list-heading",children:t.jsx("strong",{children:"With GitHub (after connecting):"})}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Import issues as tasks"}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Sync pull request status"}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Link code changes to tasks"})]})}),vs&&t.jsxs("div",{className:"onboarding-skip-banner",role:"status",children:[t.jsx("strong",{children:"No AI provider connected"}),t.jsx("p",{children:"AI features like task planning and code generation won't be available until you connect one. You can set this up later in Settings."})]}),t.jsx(di,{summary:"What does GitHub integration do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Without GitHub, you can still create and manage tasks manually. GitHub integration adds the ability to import issues as tasks, track pull request status alongside your work, and automatically link commits to tasks. Connect anytime from Settings → Authentication."})}),ye?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-provider-row",children:[t.jsxs("div",{className:"onboarding-provider-info",children:[t.jsxs("strong",{children:[t.jsx(si,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Ft,{status:wn})})]}),Le&&(P==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>ht("github"),children:"Disconnect"}))]}),(wn==="not-connected"||wn==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[P==="github"||Ke?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void ft("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>te("github"),children:[t.jsx(si,{size:16}),"Connect"]}),(P==="github"||Ke)&&k.github&&t.jsx(Ud,{instructions:k.github,"data-testid":"onboarding-login-instructions-github"})]}),wn==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Pt?"GitHub CLI is authenticated. Imports and pull request tracking are available. Connect OAuth in Settings → Authentication if you want dashboard-managed sign-in controls.":"GitHub OAuth is connected. You can import issues and track pull requests."}),wn==="failed"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--error",children:[t.jsx("p",{children:"Connection failed or timed out."}),t.jsxs("div",{className:"onboarding-github-feedback-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>te("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:se,children:"Skip for now"})]})]}),wn==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),wn==="skipped"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:[t.jsx("p",{children:"GitHub was skipped. You can connect anytime from Settings → Authentication."}),t.jsx("div",{className:"onboarding-github-feedback-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:()=>te("github"),children:"Connect anyway"})})]}),wn==="not-connected"&&t.jsx("p",{className:"onboarding-helper-text",children:"No worries if you're not ready — connect GitHub anytime from Settings → Authentication."})]}):t.jsxs("div",{className:"model-onboarding-github-optional",children:[t.jsx("div",{className:"optional-icon optional-icon--github","aria-hidden":"true",children:t.jsx(Fn,{provider:"github",size:"lg"})}),Pt?t.jsx("p",{children:"GitHub CLI is already authenticated, so imports and PR tracking work now. OAuth from the dashboard is optional and only controls dashboard-managed connect/disconnect."}):t.jsx("p",{children:"GitHub OAuth isn't connected yet. You can set it up in Settings → Authentication, or continue now and connect later."}),t.jsxs("div",{className:"model-onboarding-github-optional__actions",children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>w("project-setup"),children:Pt?"Continue with gh CLI auth →":"Continue without GitHub →"}),Pt&&(P==="github"||Ke?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(jt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>te("github"),children:[t.jsx(Fn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),Pt&&(P==="github"||Ke)&&k.github&&t.jsx(Ud,{instructions:k.github,"data-testid":"onboarding-login-instructions-github"})]})]}),x==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),$n?t.jsx("div",{className:"onboarding-project-ready","data-testid":"onboarding-project-ready",role:"status",children:t.jsx("p",{children:"Project selected — task creation and imports are available."})}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project is required before first-task actions are available."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:a,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"}),t.jsx("p",{className:"onboarding-helper-text",children:"In the setup wizard, pick an existing directory or paste a GitHub clone URL."})]}),t.jsx(di,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),x==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),C&&ps?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(Gn,{size:56,className:"success-icon"}),t.jsx("h3",{className:"onboarding-task-created__title",children:"Your first task is ready!"}),t.jsx("div",{className:"onboarding-task-created__task-id",children:ps.id}),Ns&&t.jsx("p",{className:"onboarding-task-created__description",children:Ns}),t.jsx("p",{className:"onboarding-task-created__hint",children:"Your task has been created and will appear on the board."}),t.jsxs("div",{className:"onboarding-task-created__actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:Rn,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:Un,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[$n?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-first-task-form",children:[t.jsx("label",{className:"onboarding-first-task-form__label",htmlFor:"onboarding-first-task-input",children:"Describe your first task"}),t.jsx("textarea",{id:"onboarding-first-task-input",className:"input onboarding-first-task-form__input","data-testid":"onboarding-first-task-input",value:N,onChange:E=>{I(E.target.value),z(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:Et,disabled:F,"data-testid":"onboarding-first-task-submit",children:F?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),M&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:M}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:a,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(rO,{items:Jn}),$n&&t.jsxs(t.Fragment,{children:[t.jsx(di,{summary:"What happens when I create a task?",children:t.jsx("p",{className:"onboarding-helper-text",children:"A task describes something you want done. Fusion's AI agents will read your description and work on implementing it. You can track progress on the board and review the results."})}),t.jsxs("div",{className:"onboarding-cta-options",children:[t.jsxs("button",{className:"onboarding-cta-card primary",onClick:Zt,disabled:L,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Mn,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Create a New Task"}),t.jsx("span",{children:"Describe what you need built and AI will work on it"})]})]}),t.jsxs("button",{className:`onboarding-cta-card${Ve?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:le,disabled:L||!Ve,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(si,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Import from GitHub"}),t.jsx("span",{children:"Turn GitHub issues into tasks you can track here"}),!Ve&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),x==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(Gn,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:ct,disabled:L,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:kt,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:it,children:"Next →"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:$t,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:kt,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:it,children:"Next →"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:$t,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:it,disabled:!$n,children:"Next →"})]}),x==="first-task"&&!C&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:$t,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Xe,disabled:L,children:L?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:nn,children:[t.jsx(Gn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function Dv({toasts:e}){return t.jsx("div",{className:"toast-container",id:"toasts",children:e.map(n=>t.jsx("div",{className:`toast toast-${n.type}`,children:n.message},n.id))})}const dO=i.lazy(()=>Sn(()=>import("./SetupWizardModal-DuzYPbuJ.js"),__vite__mapDeps([13,1,14,15,16,17,5,6,18])).then(e=>({default:e.SetupWizardModal}))),uO=i.lazy(()=>Sn(()=>import("./SettingsModal-DL7tjJQa.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23])).then(e=>({default:e.SettingsModal})));function mO(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{Sn(()=>import("./SettingsModal-DL7tjJQa.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23]))},{timeout:1500})}function hO({projectId:e,tasks:n,projects:s,currentProject:a,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:d,taskHandlers:u,taskOperations:m,deepLink:h,settings:f,onSettingsClose:p,onReopenOnboarding:g}){const[x,w]=i.useState(null),b=c.detailTask?(()=>{const N=n.find(I=>I.id===c.detailTask?.id);return N?"prompt"in c.detailTask?{...c.detailTask,...N,prompt:c.detailTask.prompt,log:c.detailTask.log}:N:c.detailTask})():null,y=p??c.closeSettings,S=i.useCallback(()=>{c.openNewTask()},[c]),j=i.useCallback(()=>{c.openGitHubImport()},[c]),C=i.useCallback(N=>{w(null),c.closeModelOnboarding(),c.openDetailTask(N)},[c]),v=i.useCallback(async N=>{const I=await u.handleModalCreate(N);return c.modelOnboardingOpen&&w(I),I},[u.handleModalCreate,c.modelOnboardingOpen]);return i.useEffect(()=>{!c.modelOnboardingOpen&&x&&w(null)},[c.modelOnboardingOpen,x]),i.useEffect(()=>{mO()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(_a,{children:t.jsx(MP,{task:b,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,mobileHeaderMode:c.detailTaskOrigin==="list-mobile"?"back":"close",onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onResetTask:m.resetTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:f.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(_a,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(uO,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:f.themeMode,colorTheme:f.colorTheme,onThemeModeChange:f.setThemeMode,onColorThemeChange:f.setColorTheme,dashboardFontScalePct:f.dashboardFontScalePct,onDashboardFontScaleChange:f.setDashboardFontScalePct,onReopenOnboarding:g})})}),t.jsx(B$,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:u.handleGitHubImport,tasks:n,projectId:e}),t.jsx(_a,{children:t.jsx(K$,{isOpen:c.isPlanningOpen,onClose:c.closePlanning,onTaskCreated:u.handlePlanningTaskCreated,onTasksCreated:u.handlePlanningTasksCreated,tasks:n,initialPlan:c.planningInitialPlan??void 0,projectId:e,resumeSessionId:c.planningResumeSessionId})}),t.jsx(_a,{children:t.jsx(s4,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:u.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(S4,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(E4,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(J4,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),c.todosOpen&&t.jsx(Q4,{isOpen:!0,onClose:c.closeTodos,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan}),t.jsx(rD,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(DD,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(CD,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(_a,{children:t.jsx(AD,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:v,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(BD,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:a,onOpenTaskDetail:N=>{const I=n.find(F=>F.id===N);I&&c.openDetailTask(I)}}),t.jsx(_a,{children:t.jsx(HD,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(_a,{children:t.jsx(ZD,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(pL,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(dO,{onProjectRegistered:d.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(cO,{onComplete:d.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:d.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:j,firstCreatedTask:x,onViewTask:C}),t.jsx(Dv,{toasts:o,onRemove:l})]})}function pO({errorMessage:e,isRetrying:n,onRetry:s,onManageConnection:a}){return t.jsxs("div",{className:"project-overview-empty",role:"alert","aria-live":"polite",children:[t.jsx("h2",{children:"Can't reach the Fusion backend"}),t.jsx("p",{className:"settings-muted",children:"Fusion couldn't load your projects right now. Please make sure the backend is running and try again."}),t.jsxs("p",{className:"settings-muted",children:["Error: ",e]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:s,disabled:n,children:n?"Retrying…":"Retry Connection"}),a&&t.jsx("button",{type:"button",className:"btn",onClick:a,children:"Manage Connection"})]})]})}const Au=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function fO(e,n){if(n==="ready")return"done";const s=Au.findIndex(r=>r.id===n),a=Au.findIndex(r=>r.id===e);return a<s?"done":a===s?"active":"pending"}function gO({stage:e}){const[n]=i.useState(()=>aj());return t.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":n?"Updating Fusion dashboard":"Loading Fusion dashboard","data-stage":e,"data-version-update":n?"true":void 0,children:t.jsxs("div",{className:"dashboard-loader__content",children:[t.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),n?t.jsx("p",{className:"dashboard-loader__message dashboard-loader__message--update",children:"Updating to a new frontend version..."}):t.jsx("p",{className:"dashboard-loader__message",children:"Initializing dashboard..."}),t.jsx("ol",{className:"dashboard-loader__steps","aria-label":"Dashboard loading progress",children:Au.map(s=>{const a=fO(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${a}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:a==="done"?"✓":a==="active"?t.jsx(jt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const bO=5e3;function xO(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function vO(e,n,s){let a=0,r=0,o=0,l=0,c=0;for(const d of e){switch(d.column){case"in-progress":a++,Gl(d,n,s)&&o++;break;case"todo":l++;break;case"in-review":c++;break}d.blockedBy&&d.blockedBy.length>0&&r++}return{runningTaskCount:a,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:c}}function yO(e,n,s,a){const[r,o]=i.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=i.useState(!0),[d,u]=i.useState(null),m=i.useRef(null),h=i.useRef(null),f=i.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),u(null);const w=await d1(n);o(w)}catch(w){if(w instanceof Error&&w.name==="AbortError")return;u(w instanceof Error?w.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);i.useEffect(()=>(f(),()=>{h.current&&h.current.abort()}),[f]),i.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{f()},bO),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=vO(e,s,a),g=xO(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:d,refresh:f}}const wO={planning:$i,subtask:$a,mission_interview:Rs,milestone_interview:Rs,slice_interview:Rs},kO={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function jO({sessions:e,generating:n,needsInput:s,onOpenSession:a,onDismissSession:r}){const{confirm:o}=pi(),[l,c]=i.useState(!1),[d,u]=i.useState(new Set),m=i.useRef(null),h=i.useRef(new Map),f=i.useRef(null),{activeTabMap:p}=Fr(),g=i.useMemo(()=>Va(),[]);if(i.useEffect(()=>{if(!l)return;const b=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),i.useEffect(()=>{const b=new Set,y=new Map;for(const S of e){const j=p.get(S.id),C=[S.status,S.updatedAt,j?.tabId??S.lockedByTab??"",j?.stale?"stale":"fresh"].join("|"),v=h.current.get(S.id);v&&v!==C&&b.add(S.id),y.set(S.id,C)}if(h.current=y,b.size!==0)return u(b),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{u(new Set),f.current=null},500),()=>{f.current&&(clearTimeout(f.current),f.current=null)}},[p,e]),e.length===0)return null;const x=e.length,w=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${w?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(b=>!b),title:`${x} background AI task${x!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(jt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(Jd,{size:12}),t.jsxs("span",{children:["AI ",x]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(b=>{const y=wO[b.type],S=b.status==="generating",j=b.status==="awaiting_input",C=b.status==="error",v=p.get(b.id),N=v?.tabId??b.lockedByTab??null,I=!!(N&&N!==g&&!v?.stale),F=d.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${F?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:F?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:F?"translateY(-1px)":void 0},onClick:async()=>{I&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(a(b),c(!1))},children:[C?t.jsx(Ws,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:b.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[C?"Failed":kO[b.type],S&&" — generating...",j&&!I&&" — needs input",j&&I&&" — active in another tab"]})]}),S&&t.jsx(jt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),j&&!I&&t.jsx(Jd,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),j&&I&&t.jsx(pc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:_=>{_.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(un,{size:12})})]},b.id)})})]})]})}function NO(e){if(!e)return"no activity";const n=Date.now(),s=new Date(e).getTime(),a=n-s,r=Math.floor(a/1e3),o=Math.floor(r/60),l=Math.floor(o/60),c=Math.floor(l/24);return c>0?`${c}d ago`:l>0?`${l}h ago`:o>0?`${o}m ago`:r>10?`${r}s ago`:"just now"}function SO(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:is};case"paused":return{label:"Paused",color:"var(--triage)",icon:vi};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:as}}}function CO({tasks:e,projectId:n,taskStuckTimeoutMs:s,staleHighFanoutBlockerAgeThresholdMs:a,backgroundSessions:r,backgroundGenerating:o,backgroundNeedsInput:l,onOpenBackgroundSession:c,onDismissBackgroundSession:d,lastFetchTimeMs:u,currentProjectPath:m,onOpenProjectDirectory:h,keyboardOpen:f}){if(f)return null;const{stats:p,loading:g,error:x}=yO(e,n,s,u),[w,b]=i.useState(!1),y=i.useMemo(()=>SO(p.executorState),[p.executorState]),S=i.useMemo(()=>NO(p.lastActivityAt),[p.lastActivityAt]),j=i.useMemo(()=>{const v=Ju(e,{staleHighFanoutAgeThresholdMs:a??Rb});return Array.from(v.values()).map(I=>I.escalation).filter(I=>!!I).sort((I,F)=>F.activeTodoCount!==I.activeTodoCount?F.activeTodoCount-I.activeTodoCount:F.totalActiveCount!==I.totalActiveCount?F.totalActiveCount-I.totalActiveCount:F.blockingAgeMs!==I.blockingAgeMs?F.blockingAgeMs-I.blockingAgeMs:I.blockerId.localeCompare(F.blockerId,"en",{numeric:!0,sensitivity:"base"}))[0]??null},[e,a]),C=y.icon;return x?t.jsx("div",{className:"executor-status-bar executor-status-bar--error",role:"status","aria-label":"Executor status",children:t.jsxs("span",{className:"executor-status-bar__error",children:[t.jsx(Oo,{size:14}),x]})}):g&&p.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${p.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[r&&r.length>0&&c&&d&&t.jsxs(t.Fragment,{children:[t.jsx(jO,{sessions:r,generating:o??0,needsInput:l??0,onOpenSession:c,onDismissSession:d}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:p.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${p.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:p.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:p.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),p.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:p.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${p.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${p.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:p.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:p.inReviewCount})]}),j&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--fanout",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--fanout executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Escalated"}),t.jsxs("span",{className:"executor-status-bar__fanout-summary",title:`Escalated blocker ${j.blockerId}: ${j.activeTodoCount} todo waiting (threshold ${Wu}), ${j.totalActiveCount} active total`,children:[j.blockerId," · ",j.activeTodoCount," todo"]})]})]}),m&&h&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${w?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>b(v=>!v),"aria-label":w?"Hide project directory":"Show project directory","aria-expanded":w,"data-testid":"executor-project-path-toggle",title:w?"Hide project directory":"Show project directory",children:t.jsx(Es,{size:12,"aria-hidden":"true"})}),w&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:h,title:m,"data-testid":"executor-project-path-link",children:m})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(Ji,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:S})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(C,{size:12,style:{color:y.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:y.color},children:y.label})]})]})}const EO={planning:$i,subtask:$a,mission_interview:Rs,milestone_interview:Rs,slice_interview:Rs},_O={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Lv="fusion:session-banner-dismissed";function xo(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function MO(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(Lv);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[a,r]of Object.entries(n)){const o=typeof r=="number"?r:xo(r);s.set(a,o)}return s}catch{return new Map}}function AO(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(Lv,JSON.stringify(n))}catch{}}const Vi=MO();function RO({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:a}){const[r,o]=i.useState(0),l=()=>{AO(Vi),o(g=>g+1)};i.useEffect(()=>{if(Vi.size===0)return;const g=new Map(e.map(w=>[w.id,w]));let x=!1;for(const[w,b]of Vi){const y=g.get(w);if(!y)continue;if(!(y.status==="awaiting_input"||y.status==="error")){Vi.delete(w),x=!0;continue}xo(y.updatedAt)>b&&(Vi.delete(w),x=!0)}x&&l()},[e]);const c=i.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const x=Vi.get(g.id);return x===void 0?!0:xo(g.updatedAt)>x}),[e,r]);if(c.length===0)return null;const d=c.filter(g=>g.status==="awaiting_input").length,u=c.filter(g=>g.status==="error").length;let m="";d>0&&u>0?m=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input, ${u} failed`:d>0?m=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input`:u>0&&(m=`${u} AI session${u===1?"":"s"} failed`);const h=g=>{Vi.set(g.id,Math.max(xo(g.updatedAt),Date.now())),l()},f=g=>{Vi.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const x of c)Vi.set(x.id,Math.max(xo(x.updatedAt),g));l(),a()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[t.jsxs("div",{className:"session-notification-banner__header",children:[t.jsxs("div",{className:"session-notification-banner__headline",children:[t.jsx(Ws,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(un,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(g=>{const x=EO[g.type],w=g.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${w?" session-notification-banner__item--error":""}`,"data-session-type":g.type,"data-session-status":g.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[w?t.jsx(Ws,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(x,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:g.title,children:g.title}),t.jsx("p",{className:"session-notification-banner__meta",children:w?"Failed":_O[g.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>f(g),children:w?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(g),s(g.id)},"aria-label":`Dismiss ${g.title}`,children:t.jsx(un,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const Ov="fusion:cli-binary-banner-dismissed";function IO(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Ov)==="1"}catch{return!1}}function TO(){if(!(typeof window>"u"))try{window.localStorage.setItem(Ov,"1")}catch{}}function PO({onOpenSettings:e}){const[n,s]=i.useState(null),[a,r]=i.useState(()=>IO()),[o,l]=i.useState(!1),[c,d]=i.useState(null);i.useEffect(()=>{if(a)return;let y=!1;return nN().then(S=>{y||s(S)}).catch(()=>{}),()=>{y=!0}},[a]);const u=i.useCallback(async()=>{l(!0),d(null);try{const y=await sN();s({binary:y.binary,expectedVersion:y.expectedVersion,state:y.state,install:y.install}),y.installResult.success||d(y.installResult.permissionsHint||y.installResult.stderr||`Install failed (exit ${y.installResult.exitCode??"n/a"})`)}catch(y){d(y instanceof Error?y.message:String(y))}finally{l(!1)}},[]),m=i.useCallback(()=>{TO(),r(!0)},[]);if(a||!n||n.state==="installed"||n.state==="skipped")return null;const h=n.state==="version-mismatch",f=n.binary.version,p=n.expectedVersion,g=h?"Update the Fusion CLI":"Install the Fusion CLI",x=h?t.jsxs(t.Fragment,{children:["Your installed ",t.jsx("code",{children:"fn"}),"/",t.jsx("code",{children:"fusion"})," CLI is"," ",t.jsxs("strong",{children:["v",f??"unknown"]})," but this dashboard expects"," ",t.jsxs("strong",{children:["v",p]}),". Update to stay in sync."]}):t.jsxs(t.Fragment,{children:["Get the ",t.jsx("code",{children:"fn"})," and ",t.jsx("code",{children:"fusion"})," commands on your terminal so you can drive Fusion from anywhere. One click below or copy the command into your shell."]}),w=h?"Update with npm":"Install with npm",b=h?"Updating…":"Installing…";return t.jsxs("div",{className:"cli-binary-banner",role:"status",children:[t.jsxs("div",{className:"cli-binary-banner__body",children:[t.jsx("div",{className:"cli-binary-banner__title",children:g}),t.jsx("div",{className:"cli-binary-banner__text",children:x}),t.jsxs("div",{className:"cli-binary-banner__actions",children:[t.jsx("button",{type:"button",className:"cli-binary-banner__primary",onClick:()=>void u(),disabled:o,children:o?b:w}),t.jsx("button",{type:"button",className:"cli-binary-banner__secondary",onClick:e,children:"Open Settings"})]}),c&&t.jsx("div",{className:"cli-binary-banner__error",children:c})]}),t.jsx("button",{type:"button",className:"cli-binary-banner__dismiss","aria-label":"Dismiss",onClick:m,children:t.jsx(un,{size:16})})]})}function $O({latestVersion:e,currentVersion:n,onDismiss:s}){return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:["Update available: v",e," (current: v",n,"). Run ",t.jsx("code",{children:"fn update"})," for an installed CLI, or pull this source checkout."," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/blob/main/CHANGELOG.md",target:"_blank",rel:"noreferrer",children:"Release notes"})," ","·"," ",t.jsx("a",{className:"update-available-banner__link",href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",children:"Learn more"})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":"Dismiss update notice",onClick:s,children:t.jsx(un,{size:16,"aria-hidden":"true"})})]})}function DO({pendingCount:e,onOpenMailbox:n,onDismiss:s}){const a=e===1?"request":"requests";return t.jsx("section",{className:"approval-notification-banner",role:"region","aria-live":"polite","aria-label":"Approval requests",children:t.jsxs("div",{className:"approval-notification-banner__content",children:[t.jsxs("div",{className:"approval-notification-banner__headline",children:[t.jsx("span",{className:"status-dot","aria-hidden":"true"}),t.jsx(Oo,{"aria-hidden":"true"}),t.jsxs("span",{children:[e," approval ",a," need your attention"]})]}),t.jsxs("div",{className:"approval-notification-banner__actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:n,children:[t.jsx(ra,{"aria-hidden":"true"}),t.jsx("span",{children:"Open Mailbox"})]}),t.jsx("button",{type:"button",className:"btn-icon approval-notification-banner__dismiss",onClick:s,"aria-label":"Dismiss approval notification banner",children:t.jsx(un,{"aria-hidden":"true"})})]})]})})}function LO({onResume:e}){const n=FL();if(!n)return null;const s=n.completedSteps.length,a=aa.length,r=s>0?`${s} of ${a} step${s!==1?"s":""} complete — You're on the `:"You're on the ";return t.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":"Resume onboarding",children:[t.jsxs("div",{className:"onboarding-resume-card__main",children:[t.jsx("div",{className:"onboarding-resume-card__icon","aria-hidden":"true",children:t.jsx(gs,{size:20})}),t.jsxs("div",{className:"onboarding-resume-card__content",children:[t.jsx("h2",{className:"onboarding-resume-card__title",children:"Continue Setup"}),t.jsxs("p",{className:"onboarding-resume-card__description",children:[r,t.jsx("strong",{children:n.label})," step. Continue where you left off to complete your dashboard setup."]})]})]}),t.jsx("div",{className:"onboarding-resume-card__actions",children:t.jsxs("button",{className:"onboarding-resume-card__resume-btn btn btn-primary btn-sm",onClick:()=>{ci("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(is,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function OO({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Rr(),a=Iv(),[r,o]=i.useState(!0),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});i.useEffect(()=>{if(!s||a){o(!1);return}let b=!1;return(async()=>{try{o(!0),c(!1);const[S,j]=await Promise.all([Eo(),Yi()]);if(b)return;const C=S.providers??[],v=C.find(M=>M.id==="github"),I=!C.some(M=>M.id!=="github"&&M.authenticated),F=!j.defaultProvider&&!j.defaultModelId,_=v?!v.authenticated:!1;h({needsAiProvider:I,needsDefaultModel:F,needsGitHub:_})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,a]);const f=i.useCallback(()=>{LL(),u(!0)},[]),p=i.useCallback(()=>{n()},[n]),g=i.useCallback(()=>{e("global-models")},[e]),x=i.useCallback(()=>{e("authentication")},[e]),w=i.useMemo(()=>{const b=[];return m.needsAiProvider&&b.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:as}),m.needsDefaultModel&&b.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:g,icon:Qg}),m.needsGitHub&&b.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:x,icon:si}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,x,g,p]);return!s||a||d||r||l||w.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx($i,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:w.map(b=>{const y=b.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsx("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:t.jsx(y,{size:14,"aria-hidden":!0})}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:b.title}),t.jsx("span",{children:b.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:b.onAction,children:b.actionLabel})]},b.id)})}),t.jsx(la,{slotId:"post-onboarding-recommendation",renderPlaceholder:!1,actions:{openSettingsSection:e,openModelOnboarding:n}})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:f,"aria-label":"Dismiss recommendations",children:t.jsx(un,{size:16,"aria-hidden":!0})})]})}function FO({size:e=20}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:t.jsx("path",{d:"M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.203 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.942.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"})})}function ro(e){return e>99?"99+":String(e)}function zO({view:e,onChangeView:n,footerVisible:s,modalOpen:a=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,mailboxPendingApprovalCount:m=0,chatHasUnreadResponse:h=!1,stashOrphanCount:f=0,onOpenGitManager:p,onOpenWorkflowSteps:g,onOpenSchedules:x,onOpenScripts:w,onToggleTerminal:b,onOpenFiles:y,onOpenTodos:S,todosOpen:j=!1,onOpenGitHubImport:C,onOpenPlanning:v,onResumePlanning:N,activePlanningSessionCount:I=0,onOpenUsage:F,onRunScript:_,projectId:M,onViewAllProjects:z,showSkillsTab:U,experimentalFeatures:R,onOpenNodes:D,pluginDashboardViews:K=[],shellConnectionControl:Z}){const ne=ri(),[O,A]=i.useState(!1),[P,$]=i.useState(!1),[k,J]=i.useState({}),[ce,je]=i.useState(!1),He=i.useMemo(()=>Object.entries(k).sort(([ae],[qe])=>ae.localeCompare(qe)),[k]);i.useEffect(()=>{if(!P)return;let ae=!1;return je(!0),_o(M).then(qe=>{ae||J(qe)}).catch(()=>{ae||J({})}).finally(()=>{ae||je(!1)}),()=>{ae=!0}},[P,M]);const xe=i.useCallback(()=>A(!1),[]),Ne=i.useCallback(ae=>{xe(),ae?.()},[xe]);if(i.useEffect(()=>{if(!O)return;const ae=qe=>{qe.key==="Escape"&&A(!1)};return document.addEventListener("keydown",ae),()=>document.removeEventListener("keydown",ae)},[O]),ne!=="mobile"||a||r)return null;const Y=I>0&&N?N:v,ie=!!U,ee=!!R?.todoView,oe=ie,W=ie&&!oe,fe=K.filter(ae=>ae.view.placement==="primary").sort((ae,qe)=>(ae.view.order??Number.MAX_SAFE_INTEGER)-(qe.view.order??Number.MAX_SAFE_INTEGER)).slice(0,1),B=new Set(fe.map(ae=>`${ae.pluginId}:${ae.view.viewId}`)),ve=K.filter(ae=>!B.has(`${ae.pluginId}:${ae.view.viewId}`)).sort((ae,qe)=>(ae.view.order??Number.MAX_SAFE_INTEGER)-(qe.view.order??Number.MAX_SAFE_INTEGER)),Fe=e==="documents"||!!R?.evalsView&&e==="evals"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||j&&ee||e==="skills"&&!oe||e==="graph"||e==="stash-recovery"||fr(e)&&!fe.some(ae=>yo(ae.pluginId,ae.view.viewId)===e);return t.jsxs(t.Fragment,{children:[t.jsxs("nav",{className:`mobile-nav-bar${s?" mobile-nav-bar--with-footer":""}`,role:"tablist","aria-label":"Primary navigation",children:[t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="board"||e==="list"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-tasks",role:"tab","aria-selected":e==="board"||e==="list",onClick:()=>{n(e==="board"||e==="list"?e:"board")},children:[t.jsx(ma,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Tasks"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="agents"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-agents",role:"tab","aria-selected":e==="agents",onClick:()=>n("agents"),children:[t.jsx(Kn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Agents"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="missions"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-missions",role:"tab","aria-selected":e==="missions",onClick:()=>n("missions"),children:[t.jsx(Rs,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Missions"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="chat"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-chat",role:"tab","aria-selected":e==="chat",onClick:()=>n("chat"),children:[t.jsxs("span",{className:"mobile-nav-tab-icon-wrapper",children:[t.jsx(Ki,{}),h&&e!=="chat"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":"Unread chat response"})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Chat"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="mailbox"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-mailbox",role:"tab","aria-selected":e==="mailbox",onClick:()=>n("mailbox"),children:[t.jsxs("span",{className:"mobile-nav-tab-icon-wrapper",children:[t.jsx(Da,{}),m>0&&e!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":"Pending approvals"})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:ro(u)})]}),oe&&t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="skills"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-skills",role:"tab","aria-selected":e==="skills",onClick:()=>n("skills"),children:[t.jsx(as,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),fe.map(ae=>{const qe=yo(ae.pluginId,ae.view.viewId),Pe=Vl(ae.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===qe||e==="graph"&&ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${ae.pluginId}-${ae.view.viewId}`,role:"tab","aria-selected":e===qe||e==="graph"&&ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph",onClick:()=>n(ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?"graph":qe),children:[t.jsx(Pe,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:ae.view.label})]},`${ae.pluginId}:${ae.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${Fe?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>A(ae=>!ae),children:[t.jsx(Yd,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),O&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:xe}),t.jsxs("div",{className:"mobile-more-sheet",children:[t.jsx("div",{className:"mobile-more-sheet-handle"}),t.jsx("div",{className:"mobile-more-sheet-title",children:"Navigate"}),Z?t.jsx("div",{className:"mobile-more-shell-connection","data-testid":"mobile-more-shell-connection",children:Z}):null,t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>Ne(d),children:[t.jsx(Da,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:ro(u)}),m>0&&t.jsx("span",{className:"mobile-more-item-badge",children:ro(m)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>Ne(l),children:[t.jsx(Ys,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>Ne(c),children:[t.jsx(yr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>Ne(p),children:[t.jsx(Fs,{}),t.jsx("span",{children:"Git Manager"})]}),t.jsxs("div",{className:"mobile-more-split-row",children:[t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-split-primary","data-testid":"mobile-more-item-terminal",onClick:()=>Ne(b),children:[t.jsx(Gi,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>$(ae=>!ae),"aria-expanded":P,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(On,{size:14,className:`mobile-more-chevron${P?" mobile-more-chevron--open":""}`})})]}),P&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:ce?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(jt,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):He.length>0?t.jsxs(t.Fragment,{children:[He.map(([ae,qe])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${ae}`,onClick:()=>{_&&_(ae,qe),xe(),$(!1)},children:[t.jsx(is,{}),t.jsx("span",{children:ae})]},ae)),w&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{xe(),$(!1),w()},children:[t.jsx(xi,{}),t.jsx("span",{children:"Manage Scripts…"})]})]}):w&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{xe(),$(!1),w()},children:[t.jsx(xi,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>Ne(y),children:[t.jsx(Es,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>Ne(Y),children:[t.jsx($i,{}),t.jsx("span",{children:"Planning"}),I>0&&t.jsx("span",{className:"mobile-more-item-badge",children:ro(I)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>Ne(g),children:[t.jsx(Bl,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>Ne(x),children:[t.jsx(Ji,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>Ne(C),children:[t.jsx(FO,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>Ne(F),children:[t.jsx(Ys,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>Ne(z),children:[t.jsx(uc,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>Ne(()=>n("documents")),children:[t.jsx(ua,{}),t.jsx("span",{children:"Documents"})]}),R?.evalsView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-evals",onClick:()=>Ne(()=>n("evals")),children:[t.jsx(Rs,{}),t.jsx("span",{children:"Evals"})]}),W&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>Ne(()=>n("skills")),children:[t.jsx(as,{}),t.jsx("span",{children:"Skills"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-stash-recovery",onClick:()=>Ne(()=>n("stash-recovery")),children:[t.jsx(Pa,{}),t.jsx("span",{children:"Stash Recovery"}),f>0?t.jsx("span",{className:"mobile-more-item-badge",children:ro(f)}):null]}),R?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>Ne(()=>n("research")),children:[t.jsx(Wi,{}),t.jsx("span",{children:"Research"})]}),R?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>Ne(()=>n("insights")),children:[t.jsx(gs,{}),t.jsx("span",{children:"Insights"})]}),R?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>Ne(()=>n("memory")),children:[t.jsx(So,{}),t.jsx("span",{children:"Memory"})]}),R?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{Ne(()=>n("dev-server"))},children:[t.jsx(yr,{}),t.jsx("span",{children:"Dev Server"})]}),R?.nodesView&&D&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>Ne(D),children:[t.jsx(fk,{}),t.jsx("span",{children:"Nodes"})]}),ee&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>Ne(()=>S?.()),children:[t.jsx($u,{}),t.jsx("span",{children:"Todos"})]}),ve.map(ae=>{const qe=yo(ae.pluginId,ae.view.viewId),Pe=Vl(ae.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${ae.pluginId}-${ae.view.viewId}`,onClick:()=>Ne(()=>n(ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?"graph":qe)),children:[t.jsx(Pe,{}),t.jsx("span",{children:ae.view.label})]},`${ae.pluginId}:${ae.view.viewId}`)}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>Ne(o),children:[t.jsx(vo,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function hg(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function Fv(e,n){const s=n.trim();if(!s)return!0;const a=hg(s);return hg(e).includes(a)||e.toLowerCase().includes(s.toLowerCase())}function BO({agents:e,filter:n,highlightedIndex:s,visible:a,onSelect:r,position:o="below",roomMemberIds:l,roomName:c}){const d=i.useMemo(()=>e.filter(g=>Fv(g.name,n)),[e,n]),u=!!l,m=u&&n.trim().length>0,h=i.useMemo(()=>u?d.filter(g=>l?.has(g.id)):d,[d,l,u]),f=i.useMemo(()=>u?d.filter(g=>!l?.has(g.id)):[],[d,l,u]),p=m?[...h,...f]:h;return a?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:p.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):t.jsxs(t.Fragment,{children:[u&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:c?`Members of #${c}`:"Room members"}),h.map((g,x)=>t.jsxs("button",{type:"button",className:`agent-mention-item${x===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${g.id}`,onMouseDown:w=>w.preventDefault(),onClick:()=>r(g),role:"option","aria-selected":x===s,children:[t.jsx(sc,{agent:g,size:20}),u&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":"Room member"}),t.jsx("span",{className:"agent-mention-name",children:g.name}),t.jsx("span",{className:"agent-mention-role",children:g.role})]},g.id)),u&&!m&&f.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:"Type to search other agents"}),u&&m&&f.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:"Other agents"}),f.map((g,x)=>{const w=h.length+x;return t.jsxs("button",{type:"button",className:`agent-mention-item${w===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${g.id}`,onMouseDown:b=>b.preventDefault(),onClick:()=>r(g),role:"option","aria-selected":w===s,children:[t.jsx(sc,{agent:g,size:20}),t.jsx("span",{className:"agent-mention-name",children:g.name}),t.jsx("span",{className:"agent-mention-role",children:g.role})]},g.id)})]})]})}):null}function pg(e){const{sessionId:n,tempUserMessageId:s,setStreamingText:a,setStreamingThinking:r,setStreamingToolCalls:o,cancelStreamingFlushesRef:l,addToast:c,onDone:d,onError:u,onFallbackSession:m}=e;let h="",f="",p=[],g,x=null,w=null;const b=()=>{x=null,a(h)},y=()=>{w=null,r(f)},S=()=>{x!==null&&(cancelAnimationFrame(x),x=null),w!==null&&(cancelAnimationFrame(w),w=null)};return l.current=S,{handlers:{onThinking:C=>{f+=C,w===null&&(w=requestAnimationFrame(y))},onText:C=>{h+=C,x===null&&(x=requestAnimationFrame(b))},onToolStart:C=>{p=[...p,{toolName:C.toolName,args:C.args,isError:!1,status:"running"}],o(p)},onToolEnd:C=>{const v=[...p];for(let N=v.length-1;N>=0;N--){const I=v[N];if(I?.toolName===C.toolName&&I.status==="running"){v[N]={...I,status:"completed",isError:C.isError,result:C.result},p=v,o(v);return}}p=[...v,{toolName:C.toolName,isError:C.isError,result:C.result,status:"completed"}],o(p)},onFallback:C=>{g=C,m?.(C,n),c?.(`Primary model unavailable. Switched to fallback ${C.fallbackModel}.`,"warning")},onDone:C=>{S(),d({messageId:C.messageId,message:C.message,accumulated:{text:h,thinking:f,toolCalls:p,fallbackInfo:g}})},onError:C=>{S(),u(C,s)}},cancelFlushes:S}}const UO=["load failed","failed to fetch","networkerror when attempting to fetch resource.","connection aborted","connection closed unexpectedly","network error"];function HO(e){const n=e.trim().toLowerCase();return n?UO.some(s=>n.includes(s)):!1}function qO(){const e=i.useRef(null),n=i.useRef(null);i.useEffect(()=>{if(typeof document>"u")return;const r=()=>{const o=Date.now();if(document.visibilityState==="hidden"){e.current=o;return}document.visibilityState==="visible"&&(n.current=o)};return r(),document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)},[]);const s=i.useCallback(()=>typeof document<"u"&&document.visibilityState==="hidden",[]),a=i.useCallback((r=5e3)=>{const o=e.current;if(o===null)return!1;const l=Date.now();if(s())return l-o<=r;const c=n.current;return c===null||c<o?!1:l-c<=r},[s]);return i.useMemo(()=>({isHiddenNow:s,wasRecentlyHidden:a}),[s,a])}const pr="__fn_agent__";function zv(e,n){const s=typeof e=="string"?e.trim():"",a=typeof n=="string"?n.trim():"";return!s||!a?{}:{modelProvider:s,modelId:a}}function Rl(e,n,s){const a=typeof e=="string"?e.trim():"",r=zv(n,s),o=a||(r.modelProvider&&r.modelId?pr:"");return o?{agentId:o,...r}:null}function Il(e,n,s){const a=zv(n,s),r=a.modelProvider??"",o=a.modelId??"";return`${e}::${r}/${o}`}function fg(e){const n=typeof e=="string"?e.trim():"",s=n.indexOf("/");return!n||s<=0||s>=n.length-1?{}:{modelProvider:n.slice(0,s),modelId:n.slice(s+1)}}function VO(e){const n=e?.toolCalls;if(!Array.isArray(n))return;const s=n.map(a=>{if(!a||typeof a!="object")return null;const r=a,o=typeof r.toolName=="string"?r.toolName:"";if(!o)return null;const l=r.args;return{toolName:o,...l&&typeof l=="object"?{args:l}:{},isError:!!r.isError,result:r.result,status:"completed"}}).filter(a=>a!==null);return s.length>0?s:void 0}function WO(e){const n=e?.fallback;if(!n||typeof n!="object")return;const s=n,a=typeof s.primaryModel=="string"?s.primaryModel:"",r=typeof s.fallbackModel=="string"?s.fallbackModel:"",o=s.triggerPoint;if(!(!a||!r||o!=="session-creation"&&o!=="prompt-time"))return{primaryModel:a,fallbackModel:r,triggerPoint:o}}function cr(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:VO(e.metadata),fallbackInfo:WO(e.metadata),createdAt:e.createdAt}}function KO(e,n){const[s,a]=i.useState(null),[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState([]),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,x]=i.useState(""),[w,b]=i.useState(""),[y,S]=i.useState([]),[j,C]=i.useState(""),v=i.useRef(null),N=i.useRef(!1),I=i.useRef(null),F=i.useRef(""),_=i.useRef(f);_.current=f;const M=i.useRef(null),z=i.useRef(""),U=i.useRef(null),R=i.useRef(s);R.current=s;const D=i.useRef(0),K=3,Z=i.useRef(!1);i.useEffect(()=>{F.current=j},[j]);const ne=i.useCallback(async()=>{c(!0);try{const W=await ah(e);o(W.sessions)}catch(W){console.error("[useQuickChat] Failed to refresh sessions:",W)}finally{c(!1)}},[e]),O=i.useCallback(async W=>{const L={agentId:W.agentId};return W.modelProvider&&W.modelId&&(L.modelProvider=W.modelProvider,L.modelId=W.modelId),(await T0(L,e)).session},[e]),A=i.useCallback((W,L)=>{if(v.current||!W)return!0;N.current=!1,L&&(x(L.streamingText),b(L.streamingThinking),S(L.toolCalls)),p(!0);const{handlers:pe}=pg({sessionId:W,tempUserMessageId:"",setStreamingText:x,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:I,addToast:n,onFallbackSession:(fe,B)=>{const ve=fg(fe.fallbackModel);o(Fe=>Fe.map(ae=>ae.id===B?{...ae,...ve}:ae)),a(Fe=>Fe&&Fe.id===B?{...Fe,...ve}:Fe)},onDone:()=>{x(""),b(""),S([]),p(!1),_.current=!1,v.current=null,Wr(W,{limit:50},e).then(fe=>{u(fe.messages.map(cr))}).catch(()=>{})},onError:fe=>{x(""),b(""),S([]),p(!1),_.current=!1,v.current=null;const B=typeof fe=="string"&&fe.trim()?fe:"Failed to get response";n?.(B,"error"),Wr(W,{limit:50},e).then(ve=>{u(ve.messages.map(cr))}).catch(()=>{})}});return v.current=O0(W,pe,e,{...typeof L?.replayFromEventId=="number"?{lastEventId:L.replayFromEventId}:{}}),!0},[n,e]),P=i.useCallback(async(W,L,pe)=>{const fe=Rl(W,L,pe);if(!fe)return;const B=Il(fe.agentId,fe.modelProvider,fe.modelId);c(!0);try{const{session:ve}=await I0({agentId:fe.agentId,modelProvider:fe.modelProvider,modelId:fe.modelId},e);if(ve)a(ve),z.current=B,ve.isGenerating&&A(ve.id,ve.inFlightGeneration);else{const Fe=await O(fe);a(Fe),z.current=B}D.current=0}catch(ve){console.error("[useQuickChat] Failed to initialize session:",ve),D.current+=1,D.current<=K&&n?.("Failed to initialize chat","error")}finally{c(!1)}},[A,e,n,O]),$=i.useCallback(async()=>{if(s){h(!0);try{const W=await Wr(s.id,{limit:50},e);u(W.messages.map(cr))}catch(W){console.error("[useQuickChat] Failed to load messages:",W)}finally{h(!1)}}},[s,e]);i.useEffect(()=>{s?$():u([])},[s,$]),i.useEffect(()=>{if(!s?.isGenerating||(v.current||A(s.id,s.inFlightGeneration),!_.current||v.current||!s))return;const W=setInterval(async()=>{if(!_.current||v.current||!s){clearInterval(W);return}try{if(!(await P0(s.id,e)).session.isGenerating){clearInterval(W);const pe=await Wr(s.id,{limit:50},e);u(pe.messages.map(cr)),x(""),b(""),S([]),p(!1)}}catch{}},3e3);return()=>clearInterval(W)},[s,A,e]);const k=i.useCallback(async()=>{if(s){h(!0);try{const W=await Wr(s.id,{limit:50},e);u(W.messages.map(cr))}catch(W){console.error("[useQuickChat] Failed to reload messages:",W)}finally{h(!1)}}},[s,e]),J=i.useCallback(()=>{I.current?.(),I.current=null,F.current="",C(""),x(""),b(""),S([]),p(!1)},[]),ce=i.useCallback(async(W,L,pe)=>{const fe=Rl(W,L,pe);if(!fe)return;const B=Il(fe.agentId,fe.modelProvider,fe.modelId);U.current=fe;const ve=B===z.current&&R.current;if(ve||(v.current&&(v.current.close(),v.current=null),J()),ve){await k();return}a(null),u([]),z.current=B,await P(fe.agentId,fe.modelProvider,fe.modelId)},[P,k,J]),je=i.useCallback(async W=>{const L=Rl(W.agentId,W.modelProvider??void 0,W.modelId??void 0);L&&(U.current=L,z.current=Il(L.agentId,L.modelProvider,L.modelId),v.current&&(v.current.close(),v.current=null),J(),a(W),W.isGenerating&&A(W.id,W.inFlightGeneration))},[A,J]),He=i.useCallback(async(W,L)=>{await ce(pr,W,L)},[ce]),xe=i.useCallback(async(W,L,pe)=>{const B=Rl(W??"",L,pe)??U.current;if(!B)return;U.current=B;const ve=Il(B.agentId,B.modelProvider,B.modelId);Z.current=!0,D.current=0,v.current&&(v.current.close(),v.current=null),J(),u([]),a(null),c(!0);try{const Fe=await O(B);a(Fe),z.current=ve;const ae=await ah(e);o(ae.sessions)}catch(Fe){console.error("[useQuickChat] Failed to start a fresh session:",Fe),n?.("Failed to start a new chat","error")}finally{Z.current=!1,c(!1)}},[n,O,e,J]),Ne=i.useCallback(()=>{s&&(N.current=!0,I.current?.(),I.current=null,v.current?.close(),v.current=null,$0(s.id,e).catch(()=>{}),p(!1),x(""),b(""),S([]))},[s,e]),Y=i.useCallback(()=>{F.current="",C("")},[]),ie=i.useRef(()=>Promise.resolve()),ee=qO(),oe=i.useCallback((W,L)=>{if(!s||!W.trim()&&(!L||L.length===0))return Promise.resolve();if(_.current)return L&&L.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(F.current=W,C(W),Promise.resolve());const pe=new Promise((fe,B)=>{M.current={resolve:fe,reject:B},N.current=!1,v.current&&(v.current.close(),v.current=null);const ve=`temp-${Date.now()}`,Fe={id:ve,sessionId:s.id,role:"user",content:W,createdAt:new Date().toISOString()};u(qe=>[...qe,Fe]),x(""),b(""),S([]),p(!0);const{handlers:ae}=pg({sessionId:s.id,tempUserMessageId:ve,setStreamingText:x,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:I,addToast:n,onFallbackSession:(qe,Pe)=>{const nt=fg(qe.fallbackModel);o(Be=>Be.map(de=>de.id===Pe?{...de,...nt}:de)),a(Be=>Be&&Be.id===Pe?{...Be,...nt}:Be)},onDone:({messageId:qe,message:Pe,accumulated:nt})=>{const Be=Pe?cr(Pe):{id:qe||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:nt.text,thinkingOutput:nt.thinking||void 0,toolCalls:nt.toolCalls.length>0?nt.toolCalls:void 0,fallbackInfo:nt.fallbackInfo,createdAt:new Date().toISOString()};u(Ie=>[...Ie,Be]),x(""),b(""),S([]),p(!1),_.current=!1,v.current=null,M.current?.resolve(),M.current=null;const de=F.current.trim();de&&(F.current="",C(""),ie.current(de))},onError:qe=>{x(""),b(""),S([]),p(!1),_.current=!1,v.current=null,console.error("[useQuickChat] Stream error:",qe);const Pe=typeof qe=="string"&&qe.trim()?qe:"Failed to get response";if(typeof qe=="string"&&HO(qe)&&(ee.isHiddenNow()||ee.wasRecentlyHidden(5e3))?(console.info("[useQuickChat] Suppressed tab-suspension stream error:",qe),M.current?.resolve()):(n?.(Pe,"error"),M.current?.reject(new Error(Pe))),M.current=null,!N.current){const Be=F.current.trim();Be&&(F.current="",C(""),ie.current(Be))}k()}});v.current=L0(s.id,W,ae,L,e)});return pe.catch(()=>{}),pe},[s,e,n,k,ee]);return ie.current=oe,i.useEffect(()=>()=>{v.current&&(v.current.close(),v.current=null)},[]),i.useMemo(()=>({activeSession:s,sessions:r,sessionsLoading:l,messages:d,messagesLoading:m,isStreaming:f,streamingText:g,streamingThinking:w,streamingToolCalls:y,pendingMessage:j,sendMessage:oe,stopStreaming:Ne,clearPendingMessage:Y,switchSession:ce,selectSession:je,startModelChat:He,startFreshSession:xe,refreshSessions:ne,loadMessages:$,reloadMessages:k,skipNextSessionInitRef:Z}),[s,r,l,d,m,f,g,w,y,j,oe,Ne,Y,ce,je,He,xe,ne,$,k])}function GO(e,n){const[s,a]=i.useState([]),[r,o]=i.useState(null),[l,c]=i.useState(!1),d=i.useCallback(async p=>{c(!0);try{const g=n?.filterState,x=g&&g!=="all"?{state:g}:void 0,w=n?.showSystemAgents??!1,b=await $r({...x,...p,includeEphemeral:p?.includeEphemeral??w},e),y=Array.from(new Map(b.map(S=>[S.id,S])).values());a(y)}catch(g){console.error("Failed to load agents:",g)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),u=i.useCallback(async()=>{try{const p=await YS(e);o(p)}catch(p){console.error("Failed to load agent stats:",p)}},[e]);i.useEffect(()=>{d(),u()},[d,u]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=()=>{d(),u()};return hi(`/api/events${p}`,{events:{"agent:created":g,"agent:updated":g,"agent:deleted":g,"agent:stateChanged":g,"approval:requested":g,"approval:updated":g,"approval:decided":g}})},[e,d,u]);const m=i.useCallback(async()=>{await Promise.all([d(),u()])},[d,u]),h=n?.showSystemAgents??!1,f=s.filter(p=>p.state!=="active"&&p.state!=="running"?!1:h||!RC(p));return{agents:s,activeAgents:f,stats:r,isLoading:l,loadAgents:d,loadStats:u,refreshAgents:m}}function JO({visible:e,position:n,files:s,selectedIndex:a,onSelect:r,loading:o}){return e?t.jsxs("div",{className:"file-mention-popup",style:{top:n.top,left:n.left},"data-testid":"file-mention-popup",onMouseDown:l=>{l.preventDefault()},children:[o&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!o&&s.length===0&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:"No files found"}),!o&&s.length>0&&t.jsx("ul",{className:"file-mention-popup-list",role:"listbox",children:s.map((l,c)=>{const d=mC(l.path),u=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===a?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===a,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Jg,{size:14})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:u}),d&&t.jsx("span",{className:"file-mention-popup-item-path",children:d})]})]},l.path)})})]}):null}const YO=200;function QO(e={}){const{projectId:n,workspace:s="project"}=e,[a,r]=i.useState(!1),[o,l]=i.useState(""),[c,d]=i.useState(-1),[u,m]=i.useState([]),[h,f]=i.useState(!1),[p,g]=i.useState(0),x=i.useRef(null),w=i.useRef(null);i.useEffect(()=>()=>{x.current&&clearTimeout(x.current),w.current?.abort()},[]);const b=i.useCallback((v,N)=>{if(N<0||N>v.length){r(!1);return}const I=F=>/[a-zA-Z0-9/_.-]/.test(F);for(let F=N-1;F>=0;F--){if(v[F]==="#")if(F===0){const _=v.slice(F+1,N);d(F),l(_),g(0),r(!0);return}else{const _=v[F-1];if(/[\s,.;:!?'"()[\]{}]/.test(_)){const M=v.slice(F+1,N);d(F),l(M),g(0),r(!0);return}r(!1);return}if(!I(v[F])){r(!1);return}}r(!1)},[]),y=i.useCallback(()=>{r(!1),l(""),d(-1),m([]),g(0),f(!1)},[]),S=i.useCallback(async v=>{if(!v.trim()){m([]),f(!1);return}w.current?.abort(),w.current=new AbortController;try{f(!0);const N=await tS(v,s,n);m(N.files),g(0)}catch(N){N.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);i.useEffect(()=>{if(a)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{S(o)},YO),()=>{x.current&&clearTimeout(x.current)}},[o,a,S]);const j=i.useCallback((v,N)=>{if(!a||c<0)return N;const I=N.slice(0,c),F=N.slice(c+1),_=F.match(/[\s]|$/),M=_?_.index:F.length,z=F.slice(M);return`${I}#${v.path}${z}`},[a,c]),C=i.useCallback((v,N)=>{if(!a||u.length===0)return!1;switch(v.key){case"ArrowDown":return v.preventDefault(),g(I=>Math.min(I+1,u.length-1)),!0;case"ArrowUp":return v.preventDefault(),g(I=>Math.max(I-1,0)),!0;case"Enter":case"Tab":return u[p]?(v.preventDefault(),!0):!1;case"Escape":return v.preventDefault(),y(),!0;default:return!1}},[a,u,p,y]);return{mentionActive:a,files:u,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:b,selectFile:j,dismissMention:y,handleKeyDown:C}}function XO(e){return`${e.name?.trim()||e.id} (${e.role})`}function oo(e){const n=e.trim(),s=n.indexOf("/");return!n||s<=0||s>=n.length-1?null:{modelProvider:n.slice(0,s),modelId:n.slice(s+1)}}function ZO(e,n){return n?e?.name?.trim()?e.name.trim():n.modelId.replace(/[-_]/g," ").replace(/\s+/g," ").replace(/^\w/,s=>s.toUpperCase()).trim():null}function Ll(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function eF(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,a])=>{const r=typeof a=="string"?a:(()=>{try{return JSON.stringify(a)}catch{return String(a)}})();return`${s}=${Ll(r,50)}`}).join(", ")}function tF(e){if(e===void 0)return null;if(typeof e=="string")return Ll(e,200);try{return Ll(JSON.stringify(e),200)}catch{return Ll(String(e),200)}}function Bv(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",x=f.status==="completed"&&f.isError,w=eF(f.args),b=tF(f.result),y=g?w:b?`result: ${b}`:w?`args: ${w}`:null,S=n?null:y,j=g?"running":x?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${x?" chat-tool-call--error":""}`,open:g,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",title:f.toolName,children:f.toolName}),S&&t.jsx("span",{className:"chat-tool-call-preview",title:S,children:S}),t.jsx("span",{className:"chat-tool-call-status-text",children:j})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[w&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:w})]}),b&&t.jsxs("div",{className:`chat-tool-call-row${x?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:b})]})]})]},`${f.toolName}-${p}`)},a=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:a,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Im,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),s(e[0],0)]});const r=e.filter(f=>f.status==="running").length,o=e.filter(f=>f.status==="completed"&&f.isError).length,l=r>0,c=Array.from(new Set(e.map(f=>f.toolName))),d=c.slice(0,5),u=Math.max(0,c.length-d.length),m=u>0?`${d.join(", ")}, +${u} more`:d.join(", "),h=l?`(${r} running)`:o>0?`(${o} ${o===1?"error":"errors"})`:null;return t.jsx("div",{className:a,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:`chat-tool-calls-group${n?" chat-tool-calls-group--compact":""}`,"data-testid":"chat-tool-calls-group",open:l,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(Im,{size:12,"aria-hidden":"true"}),t.jsxs("span",{className:"chat-tool-calls-count",children:[e.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:m,children:m}),h&&t.jsx("span",{className:"chat-tool-calls-group-status",children:h})]}),e.map((f,p)=>s(f,p))]})})}const Uv={pre:({children:e,...n})=>t.jsx("pre",{...n,className:"quick-chat-markdown-pre",children:e}),table:({children:e,...n})=>t.jsx("table",{...n,className:"quick-chat-markdown-table",children:e})};function gg(e){const n=/(^|[\s])\/([^\s]*)$/.exec(e);if(!n)return null;const s=n[1]??"",a=n[2]??"",r=n.index+s.length;return{filter:a,start:r,end:e.length}}function nF(e,n){const s=e.slice(0,n),a=/(^|[\s])@([\w-]*)$/.exec(s);if(!a)return null;const r=a[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}const Tl={width:320,height:400},sF=new Set(["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/x-log","text/csv","application/xml","text/markdown"]),iF=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function aF(e){return e.type.startsWith("image/")}function rF(e){if(sF.has(e.type))return!0;const n=e.name.toLowerCase();return iF.some(s=>n.endsWith(s))}const dr={width:280,height:260},Os=768,ur=8;function oF(e,n){const s=i.useCallback(()=>{if(typeof window>"u")return 0;const j=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return j&&parseFloat(j)||0},[]),a=i.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=i.useState(()=>{if(typeof window>"u")return a();const j=`fusion-quick-chat-position-${e||"default"}`;try{const C=localStorage.getItem(j);if(C){const v=JSON.parse(C);if(typeof v.x=="number"&&typeof v.y=="number"&&!isNaN(v.x)&&!isNaN(v.y))return v}}catch{}return a()}),[l,c]=i.useState(!1),d=i.useRef(null),u=i.useRef(r),m=i.useRef(null),h=i.useRef(null),f=n??i.useRef(!1);i.useEffect(()=>{u.current=r},[r]);const p=i.useCallback(j=>{if(typeof window>"u")return j;const C=48,v=window.innerWidth<=768?4:8,N=window.innerWidth<=768?44:0,I=window.innerWidth>768?s():0,F=window.innerWidth-C-v,_=window.innerHeight-C-v-N-I;return{x:Math.max(v,Math.min(F,j.x)),y:Math.max(v,Math.min(_,j.y))}},[s]),g=i.useCallback(j=>{if(typeof window>"u")return;const C=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(C,JSON.stringify(j))}catch{}},[e]),x=i.useCallback(()=>{if(!d.current)return;const j=h.current,C=m.current;j&&C!==null&&typeof j.releasePointerCapture=="function"&&j.releasePointerCapture(C),d.current=null,m.current=null,h.current=null,c(!1),document.body.style.userSelect="",f.current&&g(u.current),document.removeEventListener("pointermove",w),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y)},[g]),w=i.useCallback(j=>{if(!d.current||m.current!==null&&j.pointerId!==m.current)return;const C=j.clientX-d.current.pointerX,v=j.clientY-d.current.pointerY;if((Math.abs(C)>=5||Math.abs(v)>=5)&&(f.current=!0),!f.current)return;const N=d.current.x-C,I=d.current.y-v,F=p({x:N,y:I});u.current=F,o(F)},[p]),b=i.useCallback(j=>{m.current!==null&&j.pointerId!==m.current||x()},[x]),y=i.useCallback(j=>{m.current!==null&&j.pointerId!==m.current||x()},[x]),S=i.useCallback(j=>{if(j.button!==0&&j.pointerType==="mouse")return;const C=j.currentTarget;j.preventDefault(),typeof C.setPointerCapture=="function"&&C.setPointerCapture(j.pointerId);const v=u.current;d.current={x:v.x,y:v.y,pointerX:j.clientX,pointerY:j.clientY},m.current=j.pointerId,h.current=C,f.current=!1,c(!0),document.body.style.userSelect="none",document.addEventListener("pointermove",w,{passive:!0}),document.addEventListener("pointerup",b),document.addEventListener("pointercancel",y)},[y,w,b]);return i.useEffect(()=>()=>{document.removeEventListener("pointermove",w),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y),document.body.style.userSelect=""},[y,w,b]),{position:r,isDragging:l,handlePointerDown:S}}function lF(e,n,s){const a=`fusion:quick-chat-size-${e||"default"}`,r=i.useCallback(()=>typeof window<"u"&&window.innerWidth>Os,[]),o=i.useCallback((f,p,g)=>{if(typeof window>"u")return f;const x=Math.max(dr.width,window.innerWidth-p-ur),w=Math.max(dr.height,window.innerHeight-g-ur);return{width:Math.max(dr.width,Math.min(x,f.width)),height:Math.max(dr.height,Math.min(w,f.height))}},[]),l=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Os)return Tl;try{const f=localStorage.getItem(a);if(!f)return Tl;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?Tl:{width:p.width,height:p.height}}catch{return Tl}},[a]),[c,d]=i.useState(l),[u,m]=i.useState({right:0,bottom:0});i.useEffect(()=>{if(!r())return;const f={right:n+u.right,bottom:s+u.bottom};d(p=>o(p,f.right,f.bottom))},[o,r,n,s,u]),i.useEffect(()=>{if(r())try{localStorage.setItem(a,JSON.stringify(c))}catch{}},[r,c,a]);const h=i.useCallback(f=>{if(!r())return;const p=f.currentTarget.dataset.resizeDirection;if(!p)return;f.preventDefault(),f.stopPropagation();const g=f.currentTarget;typeof g.setPointerCapture=="function"&&g.setPointerCapture(f.pointerId);const x={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:u.right,anchorBottom:u.bottom};document.body.style.userSelect="none";const w=y=>{const S=y.clientX-x.pointerX,j=y.clientY-x.pointerY;let C=x.width,v=x.height,N=x.anchorRight,I=x.anchorBottom;if(p.includes("w")&&(C=x.width-S),p.includes("e")){const R=S;C=x.width+R,N=x.anchorRight-R}if(p.includes("n")&&(v=x.height-j),p.includes("s")){const R=j;v=x.height+R,I=x.anchorBottom-R}const F=n+N,_=s+I,M=o({width:C,height:v},F,_),z=Math.max(ur-n,Math.min(window.innerWidth-n-dr.width-ur,N)),U=Math.max(ur-s,Math.min(window.innerHeight-s-dr.height-ur,I));d(M),m({right:z,bottom:U})},b=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",w),document.removeEventListener("pointerup",b);try{localStorage.setItem(a,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",w),document.addEventListener("pointerup",b)},[u.bottom,u.right,o,s,n,r,c.height,c.width,a]);return{panelSize:c,anchorOffset:u,handleResizeStart:h}}const bg=i.memo(function({message:n,forcePlain:s,mentionAgentsByName:a,roomContext:r,onToggleRender:o}){const l=n.role==="user",c=i.useMemo(()=>{if(!l)return null;const u=n.content,m=/@([\w-]+)/g,h=[];let f=0,p=m.exec(u);for(;p;){const[g,x=""]=p,w=p.index;w>f&&h.push(u.slice(f,w));const b=x.replace(/_/g," ").toLowerCase(),y=a.get(b);if(y){const S=!!(r&&!r.memberIds.has(y.id)),j=S?`Not a member of ${r?.roomName}`:void 0;h.push(t.jsxs("span",{className:`chat-mention-chip${S?" chat-mention-chip--non-member":""}`,title:j,"aria-label":j,children:["@",y.name.replace(/\s+/g,"_")]},`${y.id}-${w}`))}else h.push(g);f=w+g.length,p=m.exec(u)}return f<u.length&&h.push(u.slice(f)),h.length===0?u:h},[l,n.content,a,r]),d=i.useMemo(()=>l?null:s?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:n.content}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(ki,{remarkPlugins:[ji],components:Uv,children:n.content})}),[l,s,n.content]);return t.jsxs("div",{className:`quick-chat-panel-message ${l?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${n.id}`,children:[l?t.jsx("p",{children:c}):t.jsxs(t.Fragment,{children:[d,t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${s?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":s?"Show rendered markdown":"Show plain text",onClick:()=>o(n.id),children:s?t.jsx(Pu,{size:14}):t.jsx(Tr,{size:14})})]}),Bv(n.toolCalls,!0)]})});function cF({projectId:e,addToast:n,showFAB:s=!0,open:a,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:d,roomContext:u=null}){const{agents:m}=GO(e),[h,f]=i.useState(!1),p=a!==void 0,g=p?a:h,x=p?q=>{r?.(typeof q=="function"?q(g):q)}:f,{keyboardOpen:w}=Zi({enabled:g}),b=ri(),y=b==="mobile",[S,j]=i.useState("agent"),[C,v]=i.useState(""),[N,I]=i.useState(!1),[F,_]=i.useState("model"),[M,z]=i.useState(""),[U,R]=i.useState(""),[D,K]=i.useState([]),[Z,ne]=i.useState(!1),[O,A]=i.useState(""),[P,$]=i.useState(""),[k,J]=i.useState(""),[ce,je]=i.useState([]),[He,xe]=i.useState(!1),[Ne,Y]=i.useState(!1),[ie,ee]=i.useState(""),[oe,W]=i.useState(0),[L,pe]=i.useState(""),[fe,B]=i.useState(!1),[ve,Fe]=i.useState(0),[ae,qe]=i.useState(-1),[Pe,nt]=i.useState(()=>new Set),[Be,de]=i.useState(!1),[Ie,$e]=i.useState([]),[st,Ue]=i.useState(!1),[me,re]=i.useState(!1),[,_e]=i.useState(!1),[xt,ut]=i.useState({top:0,left:0}),Qe=QO({projectId:e}),vt=i.useCallback(q=>{if(!q||!Qe.mentionActive)return;const we=q.getBoundingClientRect();ut({top:we.top-260,left:we.left+8})},[Qe.mentionActive]),Ae=i.useRef(!1),Je=i.useRef(!1),dt=i.useRef(""),Nt=i.useRef(0),yt=i.useRef(null),Se=i.useRef(null),G=i.useRef(0),{position:ge,isDragging:pt,handlePointerDown:ke}=oF(e,Ae),tt=ge.y+60,{panelSize:Rt,anchorOffset:Re,handleResizeStart:be}=lF(e,ge.x,tt),rt=typeof window<"u"&&window.innerWidth>Os,{activeSession:lt,messages:gt,isStreaming:St,streamingText:Lt,streamingThinking:Yt,streamingToolCalls:tn,sessions:mn,sessionsLoading:Qt,messagesLoading:yn,sendMessage:Gt,stopStreaming:on,pendingMessage:sn,clearPendingMessage:ln,switchSession:Wt,selectSession:ye,startModelChat:Le,startFreshSession:Ke,refreshSessions:mt,skipNextSessionInitRef:Ve}=KO(e,n),Pt=i.useRef(null),Ot=i.useRef(null),bt=i.useRef(null),Dt=i.useRef(null),Ft=i.useRef(null),Ht=i.useRef([]),rn=i.useRef(!1),Xt=i.useRef(!1),an=i.useRef(!1),Me=i.useRef(null),it=i.useRef(!1),kt=i.useRef(!1),$t=i.useRef({isOpen:!1,sessionId:null});i.useEffect(()=>{if(!g||typeof window>"u"||typeof document>"u"||window.innerWidth>Os)return;const q=window.scrollY,we=document.documentElement,Oe=document.body,It={htmlOverflow:we.style.overflow,bodyOverflow:Oe.style.overflow};return window.scrollTo(0,0),we.style.overflow="hidden",Oe.style.overflow="hidden",()=>{we.style.overflow=It.htmlOverflow,Oe.style.overflow=It.bodyOverflow,window.scrollTo(0,q)}},[g]),i.useLayoutEffect(()=>{if(!g||typeof window>"u"||!window.visualViewport)return;const q=Pt.current;if(!q)return;const we=window.visualViewport,Oe=()=>{it.current||(q.style.setProperty("--vv-height",`${we.height}px`),q.style.setProperty("--vv-offset-top",`${we.offsetTop||0}px`))};return Oe(),we.addEventListener("resize",Oe),we.addEventListener("scroll",Oe),()=>{we.removeEventListener("resize",Oe),we.removeEventListener("scroll",Oe)}},[g]);const se=O||P,te=i.useMemo(()=>oo(se),[se]),De=i.useMemo(()=>S==="model"&&lt?.modelProvider&&lt?.modelId?`${lt.modelProvider}/${lt.modelId}`:se,[lt?.modelId,lt?.modelProvider,S,se]),ft=i.useMemo(()=>oo(De),[De]),qt=i.useMemo(()=>D.find(q=>`${q.provider}/${q.id}`===De)??null,[De,D]),zt=i.useMemo(()=>ZO(qt,ft),[qt,ft]),Pn=i.useMemo(()=>S==="model"?te?`${pr}::${te.modelProvider}/${te.modelId}`:"":C?`${C}::`:"",[S,C,te]),ht=!(S==="agent"?!!C:!!te)||!lt;i.useEffect(()=>{if(m.length===0){v(""),j("model");return}m.some(we=>we.id===C)||v(m[0]?.id??"")},[m,C]),i.useEffect(()=>{!g||Je.current||(Je.current=!0,ne(!0),Ks().then(q=>{const we=q.models??[];if(K(we),O||we.length===0)return;const Oe=q.defaultProvider,It=q.defaultModelId;if(Oe&&It){const fn=`${Oe}/${It}`;if(we.some(jn=>`${jn.provider}/${jn.id}`===fn)){$(fn),A(fn),j("model");return}}$("");const Kt=we[0];Kt&&A(`${Kt.provider}/${Kt.id}`)}).catch(q=>{console.error("[QuickChatFAB] Failed to load models:",q),K([]),$("")}).finally(()=>{ne(!1)}))},[g,m.length,O]),i.useEffect(()=>{!g||!e||(xe(!0),R0(e).then(q=>{je(q)}).catch(()=>{je([])}).finally(()=>{xe(!1)}))},[g,e]),i.useEffect(()=>{g&&mt()},[g,mt]),i.useEffect(()=>{if(!g){dt.current="";return}if(!Pn){dt.current="";return}if(Ve.current){dt.current=Pn;return}const q=Pn===dt.current&&!lt&&!Qt;if(!(Pn===dt.current&&!q)){if(dt.current=Pn,S==="model"&&te){Le(te.modelProvider,te.modelId);return}S==="agent"&&C&&Wt(C)}},[g,S,te,C,Pn,lt,Qt,Le,Wt,Ve]),i.useEffect(()=>{g||(B(!1),pe(""),qe(-1),Y(!1),ee(""),W(0),Ht.current.forEach(q=>{q.previewUrl&&URL.revokeObjectURL(q.previewUrl)}),$e([]))},[g]),i.useEffect(()=>{Ht.current=Ie},[Ie]),i.useEffect(()=>{if(!g){rn.current=!1;return}typeof window>"u"||(rn.current=window.innerWidth<=Os)},[g]),i.useEffect(()=>{if(!g||ht||!rn.current)return;const q=Dt.current;if(!q)return;const we=document.activeElement,Oe=we?Pt.current?.contains(we):!1,It=we===document.body,Kt=we===Me.current;if(!Oe&&!It&&!Kt){rn.current=!1;return}if(Kt){q.focus({preventScroll:!0}),rn.current=!1;return}const fn=requestAnimationFrame(()=>{q.focus(),rn.current=!1});return()=>cancelAnimationFrame(fn)},[g,ht]),i.useEffect(()=>()=>{Ht.current.forEach(q=>{q.previewUrl&&URL.revokeObjectURL(q.previewUrl)})},[]);const at=i.useCallback(()=>{I(!0),_("model"),z(m[0]?.id??""),R(O||P||"")},[m,P,O]),wt=i.useMemo(()=>m.find(q=>q.id===C)??null,[m,C]),Xe=i.useMemo(()=>{const q=ie.trim().toLowerCase();return(q?ce.filter(Oe=>Oe.name.toLowerCase().includes(q)):ce).slice(0,10)},[ce,ie]),Et=i.useMemo(()=>{const q=m.filter(It=>Fv(It.name,L));if(!u)return q;const we=q.filter(It=>u.memberIds.has(It.id));if(L.trim().length===0)return we;const Oe=q.filter(It=>!u.memberIds.has(It.id));return[...we,...Oe]},[m,L,u]),Zt=i.useMemo(()=>{const q=new Map;for(const we of m)q.set(we.name.toLowerCase(),we);return q},[m]);i.useEffect(()=>{W(0)},[Xe]),i.useEffect(()=>{Fe(0)},[L,fe]),i.useEffect(()=>()=>{yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null),Se.current!==null&&(window.clearTimeout(Se.current),Se.current=null)},[]),i.useEffect(()=>{if(!g)return;const q=Oe=>{const It=Oe.target;Pt.current?.contains(It)||Ot.current?.contains(It)||It.closest(".model-combobox-dropdown--portal")||x(!1)},we=Oe=>{Oe.key==="Escape"&&x(!1)};return document.addEventListener("mousedown",q),document.addEventListener("keydown",we),()=>{document.removeEventListener("mousedown",q),document.removeEventListener("keydown",we)}},[g,x]);const le=i.useCallback(()=>{const q=bt.current;if(!q)return;const Oe=q.scrollTop+q.clientHeight>=q.scrollHeight-50;re(!Oe),kt.current=!Oe},[]),ct=i.useCallback(q=>{if(!q.isConnected)return;let we=0,Oe=0,It=-1;const Kt=6,fn=()=>{if(q.isConnected){if(q.scrollTop=q.scrollHeight,q.scrollHeight===It?Oe+=1:(Oe=0,It=q.scrollHeight),we+=1,we>=Kt||Oe>=2){re(!1),kt.current=!1;return}window.requestAnimationFrame(fn)}};fn()},[]),nn=i.useCallback(()=>{const q=bt.current;q&&ct(q)},[ct]);i.useLayoutEffect(()=>{const q=lt?.id??null,we=$t.current;if($t.current={isOpen:g,sessionId:q},!g||!q)return;const Oe=!we.isOpen&&g,It=we.isOpen&&we.sessionId!==q;if(!Oe&&!It)return;const Kt=bt.current;Kt&&ct(Kt)},[g,lt?.id,ct]),i.useEffect(()=>{if(!y||!g||!lt)return;const q=()=>{const Oe=bt.current;Oe&&ct(Oe)},we=()=>{document.visibilityState==="visible"&&q()};return document.addEventListener("visibilitychange",we),window.addEventListener("pageshow",q),()=>{document.removeEventListener("visibilitychange",we),window.removeEventListener("pageshow",q)}},[y,g,lt,ct]),i.useEffect(()=>{g&&(kt.current||nn())},[gt,Lt,Yt,St,g,nn]);const Rn=i.useMemo(()=>{const q=new Map(m.map(Oe=>[Oe.id,Oe.name?.trim()||Oe.id])),we=new Map(D.map(Oe=>[`${Oe.provider}/${Oe.id}`,Oe.name?.trim()||""]));return mn.map((Oe,It)=>{const Kt=Oe.title?.trim()||`Session ${It+1}`;let fn=null;if(Oe.agentId&&Oe.agentId!==pr)fn=q.get(Oe.agentId)||Oe.agentId;else if(Oe.modelProvider&&Oe.modelId){const An=`${Oe.modelProvider}/${Oe.modelId}`,jn=we.get(An);fn=jn?`${jn} [${An}]`:An}return{id:Oe.id,label:fn?`${Kt} — ${fn}`:Kt}})},[m,D,mn]),Un=i.useMemo(()=>S==="agent"?wt?`Message ${wt.name||wt.id}`:"Select an agent to start chatting":zt?`Message ${zt}`:"Select a model to start chatting",[S,wt,zt]),wn=i.useCallback(q=>{const we=mn.find(Oe=>Oe.id===q);we&&(we.modelProvider&&we.modelId?(j("model"),A(`${we.modelProvider}/${we.modelId}`)):(j("agent"),v(we.agentId)),ye(we))},[ye,mn]),rs=i.useCallback(async()=>{if(!Qt){if(F==="agent"){if(!M)return;j("agent"),v(M),await Ke(M)}else{const q=oo(U||O||P);if(!q)return;j("model"),A(`${q.modelProvider}/${q.modelId}`),await Ke(pr,q.modelProvider,q.modelId)}await mt(),I(!1),_("model")}},[P,M,F,U,mt,O,Qt,Ke]),_s=sn.length>50?`${sn.slice(0,50)}…`:sn,bn=i.useCallback(q=>{if(!q||q.length===0)return;const we=[];for(let Oe=0;Oe<q.length;Oe+=1){const It=q[Oe];rF(It)&&we.push({file:It,previewUrl:aF(It)?URL.createObjectURL(It):""})}we.length>0&&$e(Oe=>[...Oe,...we])},[]),Ut=i.useCallback(q=>{$e(we=>{const Oe=we[q];return Oe?.previewUrl&&URL.revokeObjectURL(Oe.previewUrl),we.filter((It,Kt)=>Kt!==q)})},[]),xs=i.useCallback(q=>{bn(q.clipboardData?.files)},[bn]),xn=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth>Os)return;const q=Dt.current;!q||q.disabled||q.focus({preventScroll:!0})},[]),Xn=i.useCallback(()=>{typeof window>"u"||window.innerWidth>Os||(an.current=!0)},[]),$n=i.useCallback(async()=>{const q=k.trim(),we=Ht.current;if(!(!q&&we.length===0)&&!ht){if(J(""),B(!1),pe(""),qe(-1),q==="/help"){de(!0),xn(),an.current=!1;return}if(q==="/clear"||q==="/new"){on(),ln(),we.forEach(Oe=>{Oe.previewUrl&&URL.revokeObjectURL(Oe.previewUrl)}),$e(Oe=>Oe.filter(It=>!we.includes(It)));try{if(S==="model"){const Oe=oo(se);if(!Oe)return;await Ke(pr,Oe.modelProvider,Oe.modelId)}else C&&await Ke(C)}catch{n("Failed to clear conversation","error")}finally{xn(),an.current=!1}return}try{de(!1),await Gt(q,we.map(Oe=>Oe.file)),we.forEach(Oe=>{Oe.previewUrl&&URL.revokeObjectURL(Oe.previewUrl)}),$e(Oe=>Oe.filter(It=>!we.includes(It)))}catch{}finally{xn(),an.current=!1}}},[n,S,ln,xn,ht,k,se,C,Gt,Ke,on]),vs=i.useCallback(q=>{q.preventDefault(),G.current+=1,Ue(!0)},[]),ms=i.useCallback(q=>{q.preventDefault(),q.dataTransfer.dropEffect="copy",Ue(!0)},[]),hs=i.useCallback(q=>{q.preventDefault(),G.current=Math.max(0,G.current-1),G.current===0&&Ue(!1)},[]),Jn=i.useCallback(q=>{q.preventDefault(),G.current=0,Ue(!1),bn(q.dataTransfer?.files)},[bn]),ps=i.useCallback((q,we)=>{const Oe=nF(q,we);if(Oe){B(!0),pe(Oe.filter),qe(Oe.start);return}B(!1),pe(""),qe(-1)},[]),Ns=i.useCallback(q=>{J(we=>{const Oe=gg(we);if(!Oe)return we;const It=`/skill:${q.name} `,Kt=we.slice(0,Oe.start)+It+we.slice(Oe.end);return window.requestAnimationFrame(()=>{Dt.current&&Dt.current.focus()}),Kt}),Y(!1),ee(""),W(0)},[]),Yn=i.useCallback(q=>{const we=Dt.current;if(!we||ae<0)return;const Oe=we.selectionStart??Nt.current,It=we.selectionEnd??Oe,Kt=Math.max(Oe,It),fn=Math.min(ae,Kt),jn=`${`@${q.name.replace(/\s+/g,"_")}`} `,En=k.slice(0,fn)+jn+k.slice(Kt),ts=fn+jn.length;J(En),B(!1),pe(""),Fe(0),qe(-1),window.requestAnimationFrame(()=>{Dt.current&&(Dt.current.focus(),Dt.current.setSelectionRange(ts,ts))})},[ae,k]),ys=i.useCallback(q=>{const we=q.target.value,Oe=q.target.selectionStart??we.length;Nt.current=Oe,J(we),Be&&we.trim().length>0&&de(!1),ps(we,Oe);const It=gg(we);It?(Y(!0),ee(It.filter)):(Y(!1),ee("")),Qe.detectMention(we,Oe),_e(Qe.mentionActive),Qe.mentionActive&&vt(q.target)},[Be,ps,Qe,vt]),ws=i.useCallback(()=>{if(an.current){window.requestAnimationFrame(()=>{xn()});return}typeof window<"u"&&window.innerWidth<=Os&&Pt.current&&(it.current=!0,Pt.current.style.removeProperty("--vv-height"),Pt.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{it.current=!1},450)),yt.current!==null&&window.clearTimeout(yt.current),yt.current=window.setTimeout(()=>{B(!1),pe(""),qe(-1),_e(!1),Qe.dismissMention(),yt.current=null},120),Se.current!==null&&window.clearTimeout(Se.current),Se.current=window.setTimeout(()=>{Y(!1),Se.current=null},120)},[Qe,xn]),Ms=i.useCallback(()=>{it.current=!1,yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null),Se.current!==null&&(window.clearTimeout(Se.current),Se.current=null)},[]),X=i.useCallback(q=>{const we=q.currentTarget,Oe=we.selectionStart??we.value.length;Nt.current=Oe,ps(we.value,Oe),Qe.detectMention(we.value,Oe),_e(Qe.mentionActive),Qe.mentionActive&&vt(we)},[ps,Qe,vt]),E=i.useCallback(q=>{q.key!=="Escape"&&X(q)},[X]),ue=i.useCallback(q=>{nt(we=>{const Oe=new Set(we);return Oe.has(q)?Oe.delete(q):Oe.add(q),Oe})},[]),Ce=i.useCallback((q,we=!1)=>we?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:q}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(ki,{remarkPlugins:[ji],components:Uv,children:q})}),[]),We=i.useCallback(q=>{if(Nt.current=q.currentTarget.selectionStart??Nt.current,Qe.mentionActive&&Qe.files.length>0){if(Qe.handleKeyDown(q,k),q.key==="Enter"||q.key==="Tab"){const we=Qe.files[Qe.selectedIndex];if(we){const Oe=Qe.selectFile(we,k);J(Oe),Qe.dismissMention(),_e(!1)}}return}if(fe&&q.key==="ArrowDown"){q.preventDefault(),Et.length>0&&Fe(we=>(we+1)%Et.length);return}if(fe&&q.key==="ArrowUp"){q.preventDefault(),Et.length>0&&Fe(we=>we===0?Et.length-1:we-1);return}if(fe&&q.key==="Enter"){q.preventDefault();const we=Et[ve]??Et[0];we&&Yn(we);return}if(fe&&q.key==="Escape"){q.preventDefault(),q.stopPropagation(),B(!1),pe(""),qe(-1);return}if(Ne&&Xe.length>0&&q.key==="ArrowDown"){q.preventDefault(),W(we=>(we+1)%Xe.length);return}if(Ne&&Xe.length>0&&q.key==="ArrowUp"){q.preventDefault(),W(we=>we===0?Xe.length-1:we-1);return}if(Ne&&(q.key==="Enter"||q.key==="Tab")){q.preventDefault();const we=Xe[oe]??Xe[0];we&&Ns(we);return}if(Ne&&q.key==="Escape"){q.preventDefault(),Y(!1),ee("");return}q.key!=="Enter"||q.shiftKey||(q.preventDefault(),$n())},[fe,Et,ve,Yn,$n,Qe,k,Ne,Xe,oe,Ns]),At=i.useCallback(()=>{if(Ae.current){Ae.current=!1;return}if(g){x(!1);return}typeof window<"u"&&window.innerWidth<=Os&&Me.current?.focus({preventScroll:!0}),x(!0)},[g,x]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:Me,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:Ot,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":pt?"true":"false",style:{right:ge.x,bottom:ge.y},onPointerDown:ke,onClick:At,children:t.jsx(Ki,{size:24})}),g&&t.jsxs("div",{className:`quick-chat-panel${y&&w?" quick-chat-panel--keyboard-open":""}`,ref:Pt,"data-testid":"quick-chat-panel",style:{...rt?{right:ge.x+Re.right,bottom:tt+Re.bottom,width:Rt.width,height:Rt.height}:{}},children:[rt&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:be,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from top"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"s","data-testid":"quick-chat-resize-s",onPointerDown:be,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from bottom"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"e","data-testid":"quick-chat-resize-e",onPointerDown:be,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from right"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"w","data-testid":"quick-chat-resize-w",onPointerDown:be,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from left"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"nw","data-testid":"quick-chat-resize-nw",onPointerDown:be,role:"separator","aria-label":"Resize panel from top-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"ne","data-testid":"quick-chat-resize-ne",onPointerDown:be,role:"separator","aria-label":"Resize panel from top-right corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"sw","data-testid":"quick-chat-resize-sw",onPointerDown:be,role:"separator","aria-label":"Resize panel from bottom-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"se","data-testid":"quick-chat-resize-se",onPointerDown:be,role:"separator","aria-label":"Resize panel from bottom-right corner"})]}),t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{className:"quick-chat-panel-title-wrap",children:[t.jsx("h3",{children:"Quick Chat"}),S==="model"&&zt&&(()=>{const q=qt?.provider??ft?.modelProvider??"";return b==="mobile"&&zt.length>12&&q?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:zt,"aria-label":zt,children:t.jsx(Fn,{provider:q,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:zt,children:zt})})()]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-new-chat-btn","data-testid":"quick-chat-new-thread","aria-label":"Start a new chat",onClick:at,disabled:Qt,children:t.jsx(Mn,{size:16})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>x(!1),children:t.jsx(un,{size:16})})]})]}),t.jsxs("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-session-select",children:[t.jsx("label",{htmlFor:"quick-chat-session-select",className:"visually-hidden",children:"Select session"}),t.jsxs("select",{id:"quick-chat-session-select",value:lt?.id??"",onChange:q=>wn(q.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:Qt?"Loading sessions…":"Select a session"}),Rn.map(q=>t.jsx("option",{value:q.id,children:q.label},q.id))]})]}),N&&t.jsxs("div",{className:"quick-chat-new-session-chooser","data-testid":"quick-chat-new-session-chooser",children:[t.jsxs("div",{className:"quick-chat-inline-mode-toggle","data-testid":"quick-chat-inline-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${F==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>_("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${F==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>_("agent"),children:"Agent"})]}),F==="agent"?t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-new-agent-select",className:"visually-hidden",children:"Select agent for new chat"}),t.jsx("select",{id:"quick-chat-new-agent-select",value:M,onChange:q=>z(q.target.value),"data-testid":"quick-chat-new-agent-select",children:m.map(q=>t.jsx("option",{value:q.id,children:XO(q)},q.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(Is,{id:"quick-chat-new-model-select",models:D,value:U,onChange:R,label:"Select model override",placeholder:Z?"Loading models…":"Select a model",disabled:Z||D.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:d})}),t.jsxs("div",{className:"quick-chat-new-session-actions",children:[t.jsx("button",{type:"button",className:"btn","data-testid":"quick-chat-new-session-cancel",onClick:()=>{I(!1),_("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void rs(),disabled:Qt||(F==="agent"?!M:!oo(U||O||P)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:bt,"data-testid":"quick-chat-messages",onScroll:le,children:Qt?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):St?t.jsxs(t.Fragment,{children:[gt.map(q=>t.jsx(bg,{message:q,forcePlain:q.role!=="user"&&Pe.has(q.id),mentionAgentsByName:Zt,roomContext:u,onToggleRender:ue},q.id)),Be&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Ce("Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")}),t.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[Lt?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Ce(Lt,Pe.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${Pe.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":Pe.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>ue("__streaming__"),children:Pe.has("__streaming__")?t.jsx(Pu,{size:14}):t.jsx(Tr,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Yt?"Thinking…":"Connecting…"}),Bv(tn,!0),Yt&&t.jsxs("details",{className:"chat-message-thinking","data-testid":"quick-chat-streaming-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:Yt})]})]})]}):yn?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):gt.length===0&&!Lt&&!Yt&&!St&&!Be?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[gt.map(q=>t.jsx(bg,{message:q,forcePlain:q.role!=="user"&&Pe.has(q.id),mentionAgentsByName:Zt,roomContext:u,onToggleRender:ue},q.id)),Be&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Ce("Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")})]})}),me&&t.jsxs("button",{type:"button",className:"btn btn-sm quick-chat-jump-to-latest","data-testid":"quick-chat-jump-to-latest",onClick:nn,children:[t.jsx(pn,{size:14}),"Latest"]}),Ie.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:Ie.map((q,we)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${we}`,children:[q.previewUrl?t.jsx("img",{src:q.previewUrl,alt:q.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:q.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${we}`,"aria-label":`Remove ${q.file.name}`,onClick:()=>Ut(we),children:"×"})]},`${q.file.name}-${we}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${st?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:vs,onDragOver:ms,onDragLeave:hs,onDrop:Jn,children:[t.jsx("input",{ref:Ft,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,tabIndex:-1,"aria-hidden":"true",className:"quick-chat-attachment-input",onChange:q=>{bn(q.target.files),q.target.value=""}}),t.jsxs("div",{className:"quick-chat-input-row","data-testid":"quick-chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-attach-btn","data-testid":"quick-chat-attach-btn","aria-label":"Attach files",onClick:()=>Ft.current?.click(),children:t.jsx(Xg,{size:16})}),t.jsx("input",{ref:Dt,type:"text",value:k,onChange:ys,onKeyDown:We,onKeyUp:E,onClick:X,onBlur:ws,onFocus:Ms,onPaste:xs,onTouchStart:q=>{typeof window>"u"||window.innerWidth>Os||document.activeElement!==q.currentTarget&&(q.preventDefault(),q.currentTarget.focus({preventScroll:!0}))},placeholder:Un,disabled:ht,"data-testid":"quick-chat-input"}),St?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:q=>{typeof window>"u"||window.innerWidth>Os||(q.preventDefault(),q.pointerType&&q.pointerType!=="mouse"&&(Xt.current=!0,on()))},onTouchStart:q=>{typeof window>"u"||window.innerWidth>Os||(q.preventDefault(),Xt.current=!0,on())},onMouseDown:q=>{typeof window>"u"||window.innerWidth>Os||q.preventDefault()},onClick:()=>{if(Xt.current){Xt.current=!1;return}on()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(Ii,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:q=>{typeof window>"u"||window.innerWidth>Os||(q.preventDefault(),q.pointerType&&q.pointerType!=="mouse"&&(Xt.current=!0,Xn(),xn(),$n()))},onTouchStart:q=>{typeof window>"u"||window.innerWidth>Os||(q.preventDefault(),Xt.current=!0,Xn(),xn(),$n())},onMouseDown:q=>{typeof window>"u"||window.innerWidth>Os||q.preventDefault()},onClick:()=>{if(Xt.current){Xt.current=!1;return}$n()},disabled:ht||k.trim().length===0&&Ie.length===0,"data-testid":"quick-chat-send",children:t.jsx(Ia,{size:16})})]}),t.jsx(BO,{agents:m,filter:L,highlightedIndex:ve,visible:fe,onSelect:Yn,position:"above",roomMemberIds:u?.memberIds,roomName:u?.roomName}),t.jsx(JO,{visible:Qe.mentionActive&&!fe,position:xt,files:Qe.files,selectedIndex:Qe.selectedIndex,onSelect:q=>{const we=Qe.selectFile(q,k);J(we),Qe.dismissMention(),_e(!1),Dt.current?.focus()},loading:Qe.loading}),Ne&&t.jsx("div",{className:"chat-skill-menu","data-testid":"quick-chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:He?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):Xe.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:ie?"No skills found":"No skills available"}):Xe.map((q,we)=>t.jsxs("button",{type:"button",role:"option","aria-selected":we===oe,className:`chat-skill-menu-item${we===oe?" chat-skill-menu-item--highlighted":""}`,onMouseDown:Oe=>Oe.preventDefault(),onMouseEnter:()=>W(we),onClick:()=>Ns(q),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:q.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:q.relativePath,children:q.relativePath})]},q.id))}),sn&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${_s}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:ln,children:"×"})]})]})})]})]})}function lo(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function xg(e){return e.status==="generating"||e.status==="awaiting_input"}function co(e){return e==="complete"||e==="error"}function dF(e){const[n,s]=i.useState([]),a=i.useRef(new Map),r=i.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:d}=Fr(),u=i.useCallback(()=>{zu(e).then(p=>{const g=p.filter(w=>{const b=lo(w.updatedAt),y=r.current.get(w.id);return y===void 0?!0:b<=y?!1:(r.current.delete(w.id),!0)}),x=new Map;for(const w of g)x.set(w.id,lo(w.updatedAt));a.current=x,s(g)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);i.useEffect(()=>{d(),u()},[u,d]),i.useEffect(()=>{s(p=>{if(o.size===0)return p;let g=!1;const x=new Map(p.map(w=>[w.id,w]));for(const w of o.values()){if(e&&w.projectId&&w.projectId!==e)continue;const b=w.lastEventTimestamp,y=a.current.get(w.sessionId)??0;if(b<y)continue;const S=r.current.get(w.sessionId);if(S!==void 0&&b<=S)continue;if(S!==void 0&&b>S&&!co(w.status)&&r.current.delete(w.sessionId),co(w.status)){x.delete(w.sessionId)&&(g=!0),a.current.set(w.sessionId,b);continue}const j=x.get(w.sessionId),C=w.type??j?.type,v=w.title??j?.title;if(!j&&(!C||!v))continue;const N={id:w.sessionId,type:C??"planning",status:w.status,title:v??"AI Session",projectId:w.projectId??j?.projectId??e??null,lockedByTab:w.owningTabId??j?.lockedByTab??null,updatedAt:w.updatedAt??j?.updatedAt??new Date(b).toISOString()},I=x.get(w.sessionId);(!I||I.status!==N.status||I.title!==N.title||I.type!==N.type||I.projectId!==N.projectId||I.lockedByTab!==N.lockedByTab||I.updatedAt!==N.updatedAt)&&(x.set(w.sessionId,N),a.current.set(w.sessionId,b),g=!0)}return g?[...x.values()].sort((w,b)=>lo(b.updatedAt)-lo(w.updatedAt)):p})},[e,o]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=w=>{try{const b=JSON.parse(w.data),y=lo(b.updatedAt)||Date.now();s(S=>{const j=a.current.get(b.id)??0;if(y<j)return S;const C=r.current.get(b.id);if(C!==void 0&&y<=C)return S;if(C!==void 0&&y>C&&!co(b.status)&&r.current.delete(b.id),a.current.set(b.id,y),co(b.status))return S.filter(N=>N.id!==b.id);const v=S.findIndex(N=>N.id===b.id);if(v>=0){const N=[...S];return N[v]=b,N}return xg(b)?[b,...S]:S}),l({sessionId:b.id,status:b.status,needsInput:b.status==="awaiting_input",type:b.type,title:b.title,projectId:b.projectId,owningTabId:b.lockedByTab,updatedAt:b.updatedAt,timestamp:y}),co(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},x=w=>{try{const b=JSON.parse(w.data),y=Date.now();r.current.set(b,y),a.current.set(b,Math.max(a.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(S=>S.filter(j=>j.id!==b))}catch{}};return hi(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":x},onReconnect:()=>{u()}})},[c,l,e,u]);const m=i.useCallback(async p=>{const x=n.find(S=>S.id===p)?.type,w=Va();let b=!1;if(x==="planning")try{await lb(p,e,w)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(x==="subtask")try{await ub(p,e,w)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(x==="mission_interview")try{await gb(p,e,w)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}b&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),a.current.set(p,Math.max(a.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await bb(p)}catch{}s(S=>S.filter(j=>j.id!==p))},[c,e,n]),h=i.useMemo(()=>n.filter(p=>xg(p)),[n]),f=i.useMemo(()=>h.filter(p=>p.type==="planning"),[h]);return{sessions:h,generating:h.filter(p=>p.status==="generating").length,needsInput:h.filter(p=>p.status==="awaiting_input").length,planningSessions:f,dismissSession:m,refresh:u}}const rc="fusion:hide-session-banners",Ru="fusion:session-banner-pref-changed";function uF(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(rc)==="1"}catch{return!1}}function mF(e){if(typeof window>"u")return()=>{};const n=a=>{a.key===rc&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(Ru,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(Ru,s)}}function r8(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(rc,"1"):window.localStorage.removeItem(rc),window.dispatchEvent(new Event(Ru))}catch{}}function hF(){return i.useSyncExternalStore(mF,uF,()=>!1)}function As(e){return{...e,column:Ab(e.column),dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function vg(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function pF(e,n){return{...n,columnMovedAt:e.columnMovedAt??n.columnMovedAt,executionStartedAt:e.executionStartedAt??n.executionStartedAt,executionCompletedAt:e.executionCompletedAt??n.executionCompletedAt,worktree:n.worktree??e.worktree,modifiedFiles:n.modifiedFiles??e.modifiedFiles,timedExecutionMs:n.timedExecutionMs??e.timedExecutionMs,workflowStepResults:n.workflowStepResults??e.workflowStepResults,tokenUsage:n.tokenUsage??e.tokenUsage,mergeDetails:n.mergeDetails??e.mergeDetails}}function qd(e,n){if(vg(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return pF(e,n);const a=vg(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:a>=0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function fF(e){const n=e?.projectId,s=e?.searchQuery,a=e?.sseEnabled??!0,[r,o]=i.useState([]),[l,c]=i.useState(!1),d=i.useRef(l);d.current=l;const u=i.useRef(r),m=i.useRef(0),h=i.useRef(0),f=i.useRef(s),p=i.useRef(null),g=i.useRef(void 0),x=i.useRef(0),w=i.useRef(n);u.current=r,f.current=s,w.current!==n&&(w.current=n,x.current++);const b=1e3,y=i.useCallback(async ne=>{const O=++m.current,A=n,P=ne?.searchQueryOverride??f.current,$=ne?.includeArchivedOverride??d.current;try{const k=await _j(void 0,void 0,A,P,$);if(m.current!==O||n!==A)return;o(k.map(As)),g.current=Date.now()}catch{if(m.current!==O||n!==A)return;if(ne?.clearOnError){o([]);return}o(k=>k)}},[n]);p.current=y;const S=i.useCallback(async()=>{d.current||(c(!0),d.current=!0,await p.current({includeArchivedOverride:!0}))},[]),j=i.useRef(s);i.useEffect(()=>{if(s===void 0&&j.current===void 0)return;j.current=s;const ne=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(ne)},[s]),i.useEffect(()=>{y({clearOnError:!0});const ne=()=>{if(document.visibilityState!=="visible")return;const O=Date.now();O-h.current<b||(h.current=O,y())};return document.addEventListener("visibilitychange",ne),()=>{document.removeEventListener("visibilitychange",ne)}},[y]),i.useEffect(()=>{if(a===!1)return;const ne=x.current,O=n?`?projectId=${encodeURIComponent(n)}`:"",A=()=>x.current!==ne;let P=!0;const $=xe=>{if(A())return;const Ne=As(JSON.parse(xe.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(Y=>{const ie=Y.findIndex(L=>L.id===Ne.id);if(ie===-1)return[...Y,Ne];const ee=Y[ie],oe=qd(ee,Ne);if(oe===ee)return Y;const W=[...Y];return W[ie]=oe,W}),g.current=Date.now()},k=xe=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:Ne,to:Y}=JSON.parse(xe.data),ie=As(Ne),ee={...ie,column:Ab(Y,ie.column)};o(oe=>{const W=oe.findIndex(pe=>pe.id===ee.id);if(W===-1)return[...oe,ee];const L=[...oe];return L[W]=ee,L}),g.current=Date.now()},J=xe=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const Ne=As(JSON.parse(xe.data));o(Y=>{const ie=Y.findIndex(L=>L.id===Ne.id);if(ie===-1)return[...Y,Ne];const ee=Y[ie],oe=qd(ee,Ne);if(oe===ee)return Y;const W=[...Y];return W[ie]=oe,W}),g.current=Date.now()},ce=xe=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const Ne=As(JSON.parse(xe.data));o(Y=>Y.filter(ie=>ie.id!==Ne.id))},je=xe=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:Ne}=JSON.parse(xe.data),ie={...As(Ne),column:"done"};o(ee=>{const oe=ee.findIndex(L=>L.id===ie.id);if(oe===-1)return[...ee,ie];const W=[...ee];return W[oe]=ie,W})},He=hi(`/api/events${O}`,{events:{"task:created":$,"task:moved":k,"task:updated":J,"task:deleted":ce,"task:merged":je},onReconnect:()=>{P&&(A()||p.current())}});return()=>{P=!1,He()}},[n,a]);const C=i.useCallback(async ne=>{const O=As(await ib(ne,n));return o(A=>A.some(P=>P.id===O.id)?A:[...A,O]),O},[n]),v=i.useCallback(async(ne,O,A)=>As(await Aj(ne,O,n,A)),[n]),N=i.useCallback(async ne=>As(await ab(ne,n)),[n]),I=i.useCallback(async(ne,O)=>As(await Rj(ne,n,O)),[n]),F=i.useCallback(async ne=>Ij(ne,n),[n]),_=i.useCallback(async ne=>As(await Tj(ne,n)),[n]),M=i.useCallback(async ne=>As(await Pj(ne,n)),[n]),z=i.useCallback(async ne=>{const O=As(await $j(ne,n));return o(A=>A.some(P=>P.id===O.id)?A:[...A,O]),O},[n]),U=i.useCallback(async(ne,O)=>{const A=u.current.find($=>$.id===ne),P=A?{...A,...O,updatedAt:new Date().toISOString()}:void 0;P&&o($=>$.map(k=>k.id===ne?P:k));try{const $=As(await Hs(ne,O,n));return o(k=>k.map(J=>J.id===ne?$:J)),$}catch($){throw A&&o(k=>k.map(J=>J.id===ne?A:J)),$}},[n]),R=i.useCallback(async ne=>{const O=As(await Lj(ne,n));return o(A=>A.map(P=>P.id===ne?O:P)),O},[n]),D=i.useCallback(async ne=>{const O=As(await Oj(ne,n));return o(A=>A.map(P=>P.id===ne?O:P)),O},[n]),K=i.useCallback(async()=>{const O=(await Fj(n)).map(As);return o(A=>A.map(P=>O.find(k=>k.id===P.id)||P)),O},[n]),Z=i.useCallback(ne=>{if(ne.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const O=ne.map(As);o(A=>{let P=A;for(const $ of O){const k=P.findIndex(je=>je.id===$.id);if(k===-1){P===A&&(P=[...A]),P.push($);continue}const J=P[k],ce=qd(J,$);ce!==J&&(P===A&&(P=[...A]),P[k]=ce)}return P}),g.current=Date.now()},[]);return{tasks:r,createTask:C,moveTask:v,pauseTask:N,deleteTask:I,mergeTask:F,retryTask:_,resetTask:M,duplicateTask:z,updateTask:U,archiveTask:R,unarchiveTask:D,archiveAllDone:K,loadArchivedTasks:S,includeArchived:l,ingestCreatedTasks:Z,lastFetchTimeMs:g.current}}const gF=5e3,bF=1e3;function xF(e){const s=(e1(e)?e.nodeMappings??e.projectNodeMappings??e.pathMappings??[]:[]).filter(a=>!!a?.nodeId&&!!a?.path).map(a=>({nodeId:a.nodeId,nodeName:a.nodeName,path:a.path,available:a.available!==!1}));return s.length>0?s:e.nodeId&&e.path?[{nodeId:e.nodeId,nodeName:e._sourceNodeName,path:e.path,available:!0}]:[]}function yg(e){return e.map(n=>({...n,nodeMappings:xF(n)}))}function vF(){const[e,n]=i.useState([]),[s,a]=i.useState(!0),[r,o]=i.useState(null),l=i.useRef(null),c=i.useRef(0),d=i.useCallback(async()=>{try{o(null);const f=await Xm();n(yg(f))}catch(f){o(f instanceof Error?f.message:"Failed to fetch projects")}},[]);i.useEffect(()=>{let f=!1;async function p(){a(!0);const x=performance.now();try{const w=await Xm(),b=yg(w),y=Math.round(performance.now()-x);console.log(`[useProjects] initial fetchProjectsAcrossNodes took ${y}ms (${b.length} projects)`),f||(n(b),o(null))}catch(w){const b=Math.round(performance.now()-x);console.warn(`[useProjects] initial fetch failed after ${b}ms: ${w instanceof Error?w.message:String(w)}`),f||o(w instanceof Error?w.message:"Failed to fetch projects")}finally{f||a(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-c.current<bF||(c.current=x,d())};return document.addEventListener("visibilitychange",g),()=>{f=!0,document.removeEventListener("visibilitychange",g)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},gF),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async f=>{const p=await l1(f);return n(g=>[...g,p]),p},[]),m=i.useCallback(async(f,p)=>{const g=await f1(f,p);return n(x=>x.map(w=>w.id===f?g:w)),g},[]),h=i.useCallback(async f=>{await hb(f),n(p=>p.filter(g=>g.id!==f))},[]);return{projects:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h}}const yF="kb-dashboard-current-project";function wF(e){return e??"local"}function kF(e,n={}){const{nodeId:s=null}=n,[a,r]=i.useState(null),[o,l]=i.useState(!0),c=i.useRef(!1),d=i.useRef(!1),u=i.useRef(null),m=wF(s);i.useEffect(()=>{let p=!1;async function g(){try{const x=await Yi();if(p)return;u.current=x.dashboardCurrentProjectIdByNode??{};const w=u.current[m];if(w){const b=e.find(y=>y.id===w);b&&(r(b),c.current=!0)}if(!w)try{const b=localStorage.getItem(yF);if(b){const y=JSON.parse(b);y?.id&&e.some(j=>j.id===y.id)&&(r(y),c.current=!0,u.current={...u.current,[m]:y.id},await Dn({dashboardCurrentProjectIdByNode:u.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return g(),()=>{p=!0}},[m,e]),i.useEffect(()=>{if(!o){if(a){if(!e.some(x=>x.id===a.id)&&e.length>0){const x=e.find(w=>w.status==="active");r(x||e[0]||null);return}const g={...u.current,[m]:a.id};u.current=g,Dn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}else if(e.length>0&&!d.current){const p=e.find(g=>g.status==="active");p&&r(p)}}},[a,e,o,m]);const h=i.useCallback(p=>{if(d.current=!1,r(p),p){const g={...u.current,[m]:p.id};u.current=g,Dn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=i.useCallback(()=>{d.current=!0,r(null);const p={...u.current};delete p[m],u.current=p,Dn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:a,setCurrentProject:h,clearCurrentProject:f,loading:o}}const Hv=i.createContext(null);function jF({children:e}){const[n,s]=i.useState([]),a=i.useRef(0),r=i.useRef(new Map),o=i.useCallback(c=>{const d=r.current.get(c);d!==void 0&&(clearTimeout(d),r.current.delete(c)),s(u=>u.filter(m=>m.id!==c))},[]),l=i.useCallback((c,d="info")=>{const u=a.current++;s(h=>[...h,{id:u,message:c,type:d}]);const m=setTimeout(()=>o(u),4e3);r.current.set(u,m)},[o]);return i.useEffect(()=>()=>{r.current.forEach(c=>clearTimeout(c)),r.current.clear()},[]),Ol.createElement(Hv.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function NF(){const e=i.useContext(Hv);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const qv="kb-dashboard-theme-mode",Vv="kb-dashboard-color-theme",Wv="kb-dashboard-font-scale-pct",Iu=100,SF=85,CF=125,Kv=[...MC],Tu="theme-data",uo="theme-data.css";function EF(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.startsWith("http://")||e.startsWith("https://")?new URL(`/${uo}`,e).toString():e.startsWith("file://")?e.endsWith("/")?e.slice(0,-1)+`/${uo}`:e.replace(/\/[^/]+$/,`/${uo}`):`/${uo}`:`/${uo}`}const Qs=typeof window<"u",_F=Qs?i.useLayoutEffect:i.useEffect;function Gv(e){return e==="dark"||e==="light"||e==="system"}function wg(){if(!Qs)return"dark";try{const e=localStorage.getItem(qv);if(Gv(e))return e}catch{}return"dark"}function kg(){if(!Qs)return"default";try{const e=localStorage.getItem(Vv);if(e&&Kv.includes(e))return e}catch{}return"default"}function jg(e){if(Qs)try{localStorage.setItem(qv,e)}catch{}}function Ng(e){if(Qs)try{localStorage.setItem(Vv,e)}catch{}}function Io(e){return typeof e!="number"||!Number.isFinite(e)?Iu:Math.min(CF,Math.max(SF,Math.round(e)))}function Sg(){if(!Qs)return Iu;try{const e=Number(localStorage.getItem(Wv));return Io(e)}catch{return Iu}}function Cg(e){if(Qs)try{localStorage.setItem(Wv,String(Io(e)))}catch{}}function MF(e,n){return e==="system"?n?"dark":"light":e}function AF(e,n,s,a){if(!Qs)return;const r=MF(e,a);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${Io(s)}%`}function Eg(){if(!Qs)return;const e=EF(),n=document.getElementById(Tu);if(n){n.href!==e&&(n.href=e),n.parentNode===document.head&&document.head.lastChild!==n&&document.head.appendChild(n);return}const s=document.createElement("link");s.rel="stylesheet",s.href=e,s.id=Tu,document.head.appendChild(s)}function _g(){if(!Qs)return;const e=document.getElementById(Tu);e&&e.remove()}function RF(){const[e,n]=i.useState(()=>wg()),[s,a]=i.useState(()=>kg()),[r,o]=i.useState(()=>Sg()),[l,c]=i.useState(!0),[d,u]=i.useState(()=>Qs?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),m=i.useRef(e),h=i.useRef(s),f=i.useRef(r),p=i.useRef(!1),g=i.useRef(!1),x=i.useRef(!1);i.useEffect(()=>{m.current=e},[e]),i.useEffect(()=>{h.current=s},[s]),i.useEffect(()=>{f.current=r},[r]),i.useEffect(()=>{if(!Qs||!l)return;let S=!1;return Yi().then(j=>{if(!S&&(Gv(j.themeMode)&&!p.current&&(m.current!==j.themeMode&&(m.current=j.themeMode,n(j.themeMode)),wg()!==j.themeMode&&jg(j.themeMode)),j.colorTheme&&Kv.includes(j.colorTheme)&&!g.current&&(h.current!==j.colorTheme&&(h.current=j.colorTheme,a(j.colorTheme)),kg()!==j.colorTheme&&Ng(j.colorTheme)),!x.current)){const C=Io(j.dashboardFontScalePct);f.current!==C&&(f.current=C,o(C)),Sg()!==C&&Cg(C)}}).catch(j=>{console.warn("[useTheme] Failed to hydrate theme from global settings",j)}).finally(()=>{S||c(!1)}),()=>{S=!0}},[l]),i.useEffect(()=>{if(!Qs)return;const S=window.matchMedia("(prefers-color-scheme: dark)"),j=C=>{u(C.matches)};return S.addEventListener("change",j),()=>S.removeEventListener("change",j)},[]),_F(()=>{AF(e,s,r,d)},[e,s,r,d]),i.useEffect(()=>{!Qs||l||(s!=="default"?Eg():_g())},[s,l]);const w=i.useCallback(S=>{p.current=!0,m.current=S,n(S),jg(S),Dn({themeMode:S}).catch(j=>{console.warn("[useTheme] Failed to persist themeMode to global settings",j)})},[]),b=i.useCallback(S=>{g.current=!0,h.current=S,a(S),Ng(S),S!=="default"?Eg():_g(),Dn({colorTheme:S}).catch(j=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",j)})},[]),y=i.useCallback(S=>{const j=Io(S);x.current=!0,f.current=j,o(j),Cg(j),Dn({dashboardFontScalePct:j}).catch(C=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",C)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:w,setColorTheme:b,setDashboardFontScalePct:y,isSystemDark:d}}function IF(e){const{planningSessions:n}=e,[s,a]=i.useState(!1),[r,o]=i.useState(!1),[l,c]=i.useState(null),[d,u]=i.useState(void 0),[m,h]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(void 0),[w,b]=i.useState(null),[y,S]=i.useState("definition"),[j,C]=i.useState(null),[v,N]=i.useState(!1),[I,F]=i.useState(void 0),[_,M]=i.useState(!1),[z,U]=i.useState(!1),[R,D]=i.useState(!1),[K,Z]=i.useState(null),[ne,O]=i.useState(!1),[A,P]=i.useState(!1),[$,k]=i.useState(void 0),[J,ce]=i.useState(!1),[je,He]=i.useState(!1),[xe,Ne]=i.useState("project"),[Y,ie]=i.useState(!1),[ee,oe]=i.useState(!1),[W,L]=i.useState(!1),[pe,fe]=i.useState(!1),[B,ve]=i.useState(!1),[Fe,ae]=i.useState(!1),[qe,Pe]=i.useState(!1),nt=!!(w||v||s||r||m||A||J||je||Y||ee||W||B||pe||R||ne||_||z||Fe||qe),Be=i.useCallback(()=>a(!0),[]),de=i.useCallback(()=>a(!1),[]),Ie=i.useCallback(()=>o(!0),[]),$e=i.useCallback(bt=>{c(bt),o(!0)},[]),st=i.useCallback(()=>{const bt=n[0];bt&&(u(bt.id),o(!0))},[n]),Ue=i.useCallback(bt=>{u(bt),o(!0)},[]),me=i.useCallback(()=>{o(!1),c(null),u(void 0)},[]),re=i.useCallback(bt=>{p(bt),h(!0)},[]),_e=i.useCallback(bt=>{x(bt),h(!0)},[]),xt=i.useCallback(()=>{h(!1),p(null),x(void 0)},[]),ut=i.useCallback((bt,Dt="definition",Ft)=>{b(bt),S(Dt),C(Ft?.origin??null)},[]),Qe=i.useCallback(bt=>{b(bt),S("changes"),C(null)},[]),vt=i.useCallback(bt=>{b(Dt=>Dt&&{...Dt,...bt})},[]),Ae=i.useCallback(()=>{b(null),C(null)},[]),Je=i.useCallback(bt=>{F(bt),N(!0)},[]),dt=i.useCallback(()=>{N(!1),F(void 0)},[]),Nt=i.useCallback(()=>M(!0),[]),yt=i.useCallback(()=>M(!1),[]),Se=i.useCallback(()=>U(!0),[]),G=i.useCallback(()=>U(!1),[]),ge=i.useCallback(bt=>{Z(bt??null),D(!0)},[]),pt=i.useCallback(()=>{D(!1),Z(null)},[]),ke=i.useCallback(()=>O(!0),[]),tt=i.useCallback(()=>O(!1),[]),Rt=i.useCallback(()=>{P(bt=>!bt)},[]),Re=i.useCallback(()=>{P(!1),k(void 0)},[]),be=i.useCallback(()=>ce(!0),[]),rt=i.useCallback(()=>ce(!1),[]),lt=i.useCallback(()=>He(!0),[]),gt=i.useCallback(()=>He(!1),[]),St=i.useCallback(bt=>{Ne(bt)},[]),Lt=i.useCallback(()=>ie(!0),[]),Yt=i.useCallback(()=>ie(!1),[]),tn=i.useCallback(()=>oe(!0),[]),mn=i.useCallback(()=>oe(!1),[]),Qt=i.useCallback(()=>L(!0),[]),yn=i.useCallback(()=>L(!1),[]),Gt=i.useCallback(()=>fe(!0),[]),on=i.useCallback(()=>fe(!1),[]),sn=i.useCallback(()=>ve(!0),[]),ln=i.useCallback(()=>ve(!1),[]),Wt=i.useCallback(async(bt,Dt)=>{ve(!1),k(Dt),P(!0)},[]),ye=i.useCallback(()=>ae(!0),[]),Le=i.useCallback(()=>ae(!1),[]),Ke=i.useCallback(()=>Pe(!0),[]),mt=i.useCallback(()=>Pe(!1),[]),Ve=i.useCallback((bt,Dt)=>{Dt(`Created ${bt.id} from planning mode`,"success"),o(!1),c(null)},[]),Pt=i.useCallback((bt,Dt)=>{const Ft=bt.map(Ht=>Ht.id).join(", ");Dt(`Created ${Ft} from planning mode`,"success"),o(!1),c(null)},[]),Ot=i.useCallback((bt,Dt)=>{const Ft=bt.map(Ht=>Ht.id).join(", ");Dt(`Created ${Ft} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:d,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:w,detailTaskInitialTab:y,detailTaskOrigin:j,settingsOpen:v,settingsInitialSection:I,schedulesOpen:_,githubImportOpen:z,usageOpen:R,usageAnchorRect:K,systemStatsOpen:ne,terminalOpen:A,terminalInitialCommand:$,filesOpen:J,todosOpen:je,fileBrowserWorkspace:xe,activityLogOpen:Y,gitManagerOpen:ee,workflowStepsOpen:W,agentsOpen:pe,scriptsOpen:B,setupWizardOpen:Fe,modelOnboardingOpen:qe,anyModalOpen:nt,openNewTask:Be,closeNewTask:de,openPlanning:Ie,openPlanningWithInitialPlan:$e,resumePlanning:st,openPlanningWithSession:Ue,closePlanning:me,openSubtaskBreakdown:re,openSubtaskWithSession:_e,closeSubtask:xt,openDetailTask:ut,openDetailWithChangesTab:Qe,updateDetailTask:vt,closeDetailTask:Ae,openSettings:Je,closeSettings:dt,openSchedules:Nt,closeSchedules:yt,openGitHubImport:Se,closeGitHubImport:G,openUsage:ge,closeUsage:pt,openSystemStats:ke,closeSystemStats:tt,toggleTerminal:Rt,closeTerminal:Re,openFiles:be,closeFiles:rt,openTodos:lt,closeTodos:gt,setFileWorkspace:St,openActivityLog:Lt,closeActivityLog:Yt,openGitManager:tn,closeGitManager:mn,openWorkflowSteps:Qt,closeWorkflowSteps:yn,openAgents:Gt,closeAgents:on,openScripts:sn,closeScripts:ln,runScript:Wt,openSetupWizard:ye,closeSetupWizard:Le,openModelOnboarding:Ke,closeModelOnboarding:mt,onPlanningTaskCreated:Ve,onPlanningTasksCreated:Pt,onSubtaskTasksCreated:Ot}}function TF(e){const[n,s]=i.useState(2),[a,r]=i.useState("."),[o,l]=i.useState(!0),[c,d]=i.useState(!1),[u,m]=i.useState(!1),[h,f]=i.useState(void 0),[p,g]=i.useState(7200*1e3),[x,w]=i.useState(!1),[b,y]=i.useState(!1),[S,j]=i.useState(!1),[C,v]=i.useState({}),[N,I]=i.useState(!1),[F,_]=i.useState(!1),[M,z]=i.useState(!1),[U,R]=i.useState(!1),[D,K]=i.useState(!0),Z=i.useCallback(async()=>{const[k,J]=await Promise.allSettled([Uj(e),gc(e)]);if(k.status==="fulfilled"&&(s(k.value.maxConcurrent),r(k.value.rootDir)),J.status==="fulfilled"){const ce=J.value;l(!!ce.autoMerge),d(!!ce.globalPause),m(!!ce.enginePaused),y(!!ce.prAuthAvailable),f(ce.taskStuckTimeoutMs),g(ce.staleHighFanoutBlockerAgeThresholdMs??7200*1e3),w(ce.showQuickChatFAB===!0),v(ce.experimentalFeatures??{});const je=ce.experimentalFeatures??{};I(je.insights===!0),_(je.memoryView===!0),z(je.devServerView===!0||je.devServer===!0),R(je.todoView===!0);const He=ce.autoReloadOnVersionChange!==!1;K(He),Tc(He)}j(!0)},[e]);i.useEffect(()=>{j(!1),v({}),I(!1),_(!1),z(!1),R(!1),Z()},[Z]);const ne=i.useCallback(async()=>{const k=!o;l(k);try{await Xo({autoMerge:k},e)}catch{l(!k)}},[o,e]),O=i.useCallback(async()=>{const k=!c;d(k);try{await Xo({globalPause:k,globalPauseReason:k?"manual":void 0},e)}catch{d(!k)}},[c,e]),A=i.useCallback(async()=>{const k=!u;m(k);try{await Xo({enginePaused:k},e)}catch{m(!k)}},[u,e]),P=i.useCallback(async()=>{const k=!x;w(k);try{await Xo({showQuickChatFAB:k},e)}catch{w(!k)}},[x,e]),$=i.useCallback(async()=>{const k=!D;K(k),Tc(k);try{await Dn({autoReloadOnVersionChange:k})}catch{K(!k),Tc(!k)}},[D]);return{maxConcurrent:n,rootDir:a,autoMerge:o,globalPaused:c,enginePaused:u,taskStuckTimeoutMs:h,staleHighFanoutBlockerAgeThresholdMs:p,showQuickChatFAB:x,prAuthAvailable:b,settingsLoaded:S,experimentalFeatures:C,insightsEnabled:N,memoryEnabled:F,devServerEnabled:M,todosEnabled:U,autoReloadOnVersionChange:D,toggleAutoMerge:ne,toggleGlobalPause:O,toggleEnginePause:A,toggleShowQuickChatFAB:P,toggleAutoReloadOnVersionChange:$,refresh:Z}}function PF(e){const{projectId:n,projects:s,projectsLoading:a,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:d}=e,u=i.useRef(!1),m=i.useRef(!1),h=i.useRef(null);return i.useEffect(()=>{if(!m.current){const b=window.location.pathname.match(/^\/tasks\/([A-Z]+-\d+)\/?$/);if(b){const y=b[1];if(/^[A-Z]+-\d+$/.test(y)){const S=new URLSearchParams(window.location.search);S.set("task",y);const j=S.toString(),C=window.history.state??{};window.history.replaceState(C,"",j?`/?${j}`:"/"),m.current=!0}}}const p=new URLSearchParams(window.location.search),g=p.get("project"),x=p.get("task");if(!x||a)return;if(g){const b=s.find(y=>y.id===g);if(!b){l(`Project '${g}' not found`,"error");return}r?.id!==b.id&&o(b)}if(u.current)return;u.current=!0,La(x,g??n).then(b=>{c(b),h.current=x}).catch(()=>{l(`Task ${x} not found`,"error")})},[n,s,a,r,o,l,c]),{handleDetailClose:i.useCallback(()=>{if(h.current){const p=new URLSearchParams(window.location.search);p.delete("task");const g=p.toString(),x=window.history.state??{};window.history.replaceState(x,"",g?`${window.location.pathname}?${g}`:window.location.pathname),h.current=null}d()},[d])}}function $F(){const[e,n]=i.useState([]),[s,a]=i.useState([]),[r,o]=i.useState([]),l=i.useRef(s),c=i.useRef(r);i.useEffect(()=>{Ks().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,a(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),i.useEffect(()=>{l.current=s},[s]),i.useEffect(()=>{c.current=r},[r]);const d=i.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];l.current=p,a(()=>p);try{await Dn({favoriteProviders:p,favoriteModels:c.current})}catch(g){throw l.current=h,a(()=>h),g}},[]),u=i.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];c.current=p,o(()=>p);try{await Dn({favoriteProviders:l.current,favoriteModels:p})}catch(g){throw c.current=h,o(()=>h),g}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:d,toggleFavoriteModel:u}}function DF({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:a}){const r=i.useRef(!1),o=i.useRef(n);o.current=n,i.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,c=!1;Eo().then(({providers:d})=>{const u=d.some(h=>h.authenticated);if(d.length>0&&!u||d.length>0&&u)return Yi().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!u||!f)&&!Rr()?l=!0:!u&&!Rr()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(ci("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(ci("onboarding:auto-triggered",{trigger:"missing-provider"}),a("authentication"))}).catch(()=>{})},[e,n,s,a])}const Mg="kb-update-banner-dismissed";function LF(){const[e,n]=i.useState(!0),[s,a]=i.useState(!1),[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1);i.useEffect(()=>{const h=sessionStorage.getItem(Mg)==="true";u(h);let f=!1;return Hj().then(p=>{f||p.disabled||(a(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{f||n(!1)}),()=>{f=!0}},[]);const m=i.useCallback(()=>{u(!0),sessionStorage.setItem(Mg,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:d,dismiss:m}}const OF=["board","list","graph","agents","missions","chat","documents","research","evals","skills","mailbox","insights","memory","devserver","dev-server","stash-recovery"];function FF(e){return e!==null&&OF.includes(e)}function Vd(e){return e!==null&&(FF(e)||fr(e))}const zF=Wo("fusion-plugin-roadmap","roadmaps");function Ag(e){return e==="devserver"?"dev-server":e}function Rg(e){return e!=="roadmaps"?"board":Sb("fusion-plugin-roadmap","roadmaps")?zF:"board"}function BF(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:a,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:d,setThemeMode:u}=e,[m,h]=i.useState(()=>{if(typeof window<"u"){const b=window.localStorage.getItem("kb-dashboard-view-mode");if(b==="overview"||b==="project")return b}return"overview"}),[f,p]=i.useState(()=>{const b=zn("kb-dashboard-task-view");return b==="roadmaps"?Rg(b):Vd(b)?b:"board"}),g=i.useRef(!1);i.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),i.useEffect(()=>{const b=zn("kb-dashboard-task-view",r?.id);if(b==="roadmaps")p(Rg(b));else if(Vd(b)){const y=!g.current&&b==="devserver";p(y?"devserver":Ag(b))}else p("board");r?.id&&(g.current=!0)},[r?.id]),i.useEffect(()=>{us("kb-dashboard-task-view",f,r?.id)},[r?.id,f]),i.useEffect(()=>{if(typeof window>"u")return;const b=new URLSearchParams(window.location.search).get("view");b&&Vd(b)&&p(Ag(b))},[]),i.useEffect(()=>{n||a||r&&m==="overview"&&h("project")},[n,a,r,m]),i.useEffect(()=>{if(n||a||l||s||o>0||r)return;const b=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(b)},[n,s,o,a,r,l,c]);const x=i.useCallback(b=>{p(b)},[]),w=i.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(d),S=b[(y+1)%b.length];u(S)},[d,u]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:w}}function UF(e){const{enabled:n}=e,s=i.useRef([]),a=i.useRef(!1),r=i.useRef(n);r.current=n;const o=i.useCallback(c=>{if(!r.current||a.current)return;const d=s.current[s.current.length-1];if(d){const h=d.type==="modal"?d.close:d.revert,f=c.type==="modal"?c.close:c.revert;if(h===f)return}s.current.push(c);const u=s.current.length,m=typeof window<"u"&&window.history.state?window.history.state:{};window.history.pushState({...m,navIndex:u},"")},[]),l=i.useCallback(c=>{if(!r.current||s.current.length===0)return;s.current[s.current.length-1]=c;const d=s.current.length,u=typeof window<"u"&&window.history.state?window.history.state:{};window.history.replaceState({...u,navIndex:d},"")},[]);return i.useEffect(()=>{if(typeof window>"u")return;const c=d=>{if(!r.current)return;const u=d.state?.navIndex??0,m=s.current.length;if(u>=m)return;const h=m-u;if(!(h<=0)){a.current=!0;try{for(let f=0;f<h;f++){const p=s.current.pop();p&&(p.type==="modal"?p.close():p.revert())}}finally{a.current=!1}}};return window.addEventListener("popstate",c),()=>{window.removeEventListener("popstate",c)}},[]),{pushNav:o,replaceCurrent:l}}const Wd=new Map,HF=6e4;function qF(e){const[n,s]=i.useState([]),[a,r]=i.useState(!0),[o,l]=i.useState(null),[c,d]=i.useState(0),u=i.useRef(!1),m=i.useCallback(()=>{const h=e??"default";Wd.delete(h),d(f=>f+1)},[e]);return i.useEffect(()=>{const h=e??"default";let f=!1;async function p(){const g=Wd.get(h);if(g&&Date.now()<g.expiresAt){if(f)return;s(g.views),r(!1);return}u.current||r(!0),l(null);try{const x=await A0(e);if(f)return;Wd.set(h,{views:x,expiresAt:Date.now()+HF}),s(x)}catch(x){if(f)return;l(x instanceof Error?x.message:"Failed to fetch plugin dashboard views")}finally{f||(r(!1),u.current=!0)}}return p(),()=>{f=!0}},[e,c]),i.useMemo(()=>({views:n,loading:a,error:o,refetch:m}),[n,a,o,m])}function VF({taskView:e,context:n}){return t.jsx(gC,{viewId:e,context:n})}let Ig=!1;function Ir(e,n){return function(){return i.createElement("span",null,`Bundled plugin view unavailable: ${e}#${n}`)}}async function WF(){const e="@fusion-plugin-examples/dependency-graph/dashboard-view",n="DependencyGraphDashboardView",a=(await Sn(()=>import("./dashboard-view-MB-86hAu.js"),__vite__mapDeps([24,1,25,5,6,26])))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Ir(e,n)})}async function KF(){const e="@fusion-plugin-examples/roadmap/dashboard-view",n="RoadmapDashboardView",a=(await Sn(()=>import("./dashboard-view-BWGH_fAq.js"),__vite__mapDeps([27,1,25,28])))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Ir(e,n)})}async function GF(){const e="@fusion-plugin-examples/cli-printing-press/dashboard-view",n="CliPrintingPressWizardView";try{const a=(await import(e))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Ir(e,n)})}catch{return{default:Ir(e,n)}}}async function JF(){const e="@fusion-plugin-examples/cli-printing-press/manage-view",n="CliPrintingPressManageView";try{const a=(await import(e))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Ir(e,n)})}catch{return{default:Ir(e,n)}}}function Jv(){Ig||(Ig=!0,sl("fusion-plugin-dependency-graph","graph",i.lazy(WF)),sl("fusion-plugin-roadmap","roadmaps",i.lazy(KF)),sl("fusion-plugin-cli-printing-press","wizard",i.lazy(GF)),sl("fusion-plugin-cli-printing-press","manage",i.lazy(JF)))}function YF(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:a,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:d,openSettings:u,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:f}=e,p=i.useCallback(I=>{n(I),a("project")},[n,a]),g=i.useCallback(()=>{s(),a("overview")},[s,a]),x=i.useCallback(()=>{u()},[u]),w=i.useCallback(()=>{m()},[m]),b=i.useCallback(I=>{h(),n(I),a("project"),d(`Project ${I.name} registered successfully`,"success"),o()},[h,n,a,d,o]),y=i.useCallback(()=>{f()},[f]),S=i.useCallback(async I=>{try{await h1(I.id),d(`Project ${I.name} paused`,"success"),await o()}catch{d(`Failed to pause project ${I.name}`,"error")}},[d,o]),j=i.useCallback(async I=>{try{await p1(I.id),d(`Project ${I.name} resumed`,"success"),await o()}catch{d(`Failed to resume project ${I.name}`,"error")}},[d,o]),C=i.useCallback(async I=>{try{await hb(I.id),d(`Project ${I.name} removed`,"success"),r?.id===I.id&&(s(),a("overview")),await o()}catch{d(`Failed to remove project ${I.name}`,"error")}},[r,s,a,d,o]),v=i.useCallback(async I=>{try{await l(I)}catch{d("Failed to update favorites","error")}},[l,d]),N=i.useCallback(async I=>{try{await c(I)}catch{d("Failed to update model favorites","error")}},[c,d]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:x,handleAddProject:w,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:S,handleResumeProject:j,handleRemoveProject:C,handleToggleFavorite:v,handleToggleModelFavorite:N}}function QF(e){const{createTask:n,ingestCreatedTasks:s,onPlanningTaskCreated:a,onPlanningTasksCreated:r,onSubtaskTasksCreated:o,addToast:l}=e,c=i.useCallback(async p=>n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),d=i.useCallback(async p=>await n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),u=i.useCallback(p=>{s([p]),a(p,l)},[l,s,a]),m=i.useCallback(p=>{s(p),r(p,l)},[l,s,r]),h=i.useCallback(p=>{s(p),o(p,l)},[l,s,o]),f=i.useCallback(p=>{l(`Imported ${p.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:c,handleModalCreate:d,handlePlanningTaskCreated:u,handlePlanningTasksCreated:m,handleSubtaskTasksCreated:h,handleGitHubImport:f}}function XF(e,n){const{projectId:s,searchQuery:a}=n??{},[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(null),g=i.useRef(null),x=i.useCallback(async()=>{if(!e){o([]),c([]),u(null),h(!1),p(null);return}g.current?.abort();const b=new AbortController;g.current=b,h(!0),p(null);try{const y=[F0(e),z0(e)];s&&(y.push(B0(e,s,a)),y.push(U0(e,s)));const S=await Promise.allSettled(y);if(b.signal.aborted)return;const j=S[0],C=S[1];if(j.status==="rejected"){p(`Failed to fetch node health: ${j.reason}`),h(!1);return}if(u(j.value),C.status==="rejected"){p(`Failed to fetch projects: ${C.reason}`),h(!1);return}if(o(C.value),s&&S[2]){const v=S[2];if(v.status==="rejected"){p(`Failed to fetch tasks: ${v.reason}`),h(!1);return}v.status==="fulfilled"&&c(v.value)}h(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,a]);i.useEffect(()=>(x(),()=>{g.current?.abort()}),[x]);const w=i.useCallback(()=>{x()},[x]);return{projects:r,tasks:l,health:d,loading:m,error:f,refresh:w}}function ZF(e){const[n,s]=i.useState(!1),[a,r]=i.useState(null);return i.useEffect(()=>{if(!e){s(!1),r(null);return}const o=`/api/proxy/${encodeURIComponent(e)}/events`;return hi(o,{events:{"task:created":l=>{r({type:"task:created",data:l.data})},"task:moved":l=>{r({type:"task:moved",data:l.data})},"task:updated":l=>{r({type:"task:updated",data:l.data})},"task:deleted":l=>{r({type:"task:deleted",data:l.data})},"task:merged":l=>{r({type:"task:merged",data:l.data})}},onOpen:()=>s(!0),onError:()=>s(!1)})},[e]),{isConnected:n,lastEvent:a}}const ez="fusion-dashboard-current-node",Yv=i.createContext(null);function tz({children:e}){const[n,s]=i.useState(null),[a,r]=i.useState(!0),o=i.useRef(!1),l=i.useRef(void 0);i.useEffect(()=>{let m=!1;async function h(){try{const f=await Yi();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(ez);if(g){const x=JSON.parse(g);x?.id&&x?.type==="remote"&&(l.current=x.id,await Dn({dashboardCurrentNodeId:x.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),i.useEffect(()=>{if(!a)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,Dn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,Dn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,a]);const c=i.useCallback(m=>{s(m)},[]),d=i.useCallback(()=>{s(null),l.current=void 0,Dn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),u={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:d};return t.jsx(Yv.Provider,{value:u,children:e})}function nz(){const e=i.useContext(Yv);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}const sz=["shellKind","shellMode","profileId","serverBaseUrl","serverLabel","shellCanOpenConnectionManager","hostKind","mode","connectionId","serverUrl","canOpenConnectionManager"],iz=["__FUSION_SHELL_HOST_CONTEXT__","__fusionShellHostContext","__FUSION_SHELL_CONTEXT__"];let oc=null,Tg=!1;function az(e){if(typeof e=="boolean")return e;if(typeof e=="string"){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1}}function rz(e){if(!(typeof e!="string"||e.trim().length===0))try{const n=new URL(e);return n.protocol!=="http:"&&n.protocol!=="https:"?void 0:n.toString().replace(/\/$/,"")}catch{return}}function Qv(e){if(e==="browser"||e==="desktop-shell"||e==="mobile-shell")return e;if(e==="desktop")return"desktop-shell";if(e==="mobile")return"mobile-shell"}function oz(e){return e==="local"||e==="remote"?e:void 0}function Xv(e){const n=oz(e.mode),s=typeof e.connectionId=="string"&&e.connectionId.trim()?e.connectionId:void 0,a=rz(e.serverUrl),r=az(e.canOpenConnectionManager);return{kind:e.kind,...n?{mode:n}:{},...s?{connectionId:s}:{},...a?{serverUrl:a}:{},...r!==void 0?{canOpenConnectionManager:r}:{}}}function lz(e){for(const n of iz){const s=e[n];if(!s||typeof s!="object")continue;const a=s,r=Qv(a.kind??a.shellKind??a.hostKind);if(r)return r==="browser"?{kind:r}:Xv({kind:r,mode:a.mode??a.shellMode,connectionId:a.connectionId??a.profileId,serverUrl:a.serverUrl??a.serverBaseUrl,canOpenConnectionManager:a.canOpenConnectionManager??a.shellCanOpenConnectionManager})}return null}function cz(e){let n;try{n=new URL(e.location.href)}catch{return null}const s=n.searchParams,a=Qv(s.get("hostKind")??s.get("kind")??s.get("shellKind"));return a?a==="browser"?{kind:a}:Xv({kind:a,mode:s.get("mode")??s.get("shellMode"),connectionId:s.get("connectionId")??s.get("profileId"),serverUrl:s.get("serverUrl")??s.get("serverBaseUrl"),canOpenConnectionManager:s.get("canOpenConnectionManager")??s.get("shellCanOpenConnectionManager")}):null}function dz(e){try{const n=new URL(e.location.href);let s=!1;for(const r of sz)n.searchParams.has(r)&&(n.searchParams.delete(r),s=!0);if(!s)return;const a=n.pathname+(n.search?n.search:"")+n.hash;e.history.replaceState(e.history.state,"",a)}catch{}}function uz(e=window){const n=lz(e);if(n)return n;const s=cz(e);return s||(typeof e.fusionAPI<"u"?{kind:"desktop-shell"}:{kind:"browser"})}function Zv(e=window){return!Tg&&typeof window<"u"&&(oc=uz(e),dz(e),Tg=!0),oc??{kind:"browser"}}function mz(){return oc||(typeof window>"u"?{kind:"browser"}:Zv(window))}const hz={kind:"browser"},ey=i.createContext({host:hz,isNativeShell:!1,kind:"browser"});function pz(e){const n=e.kind!=="browser";return{host:e,isNativeShell:n,kind:e.kind,...n?{mode:e.mode,connectionId:e.connectionId,serverUrl:e.serverUrl,canOpenConnectionManager:e.canOpenConnectionManager}:{}}}function fz({children:e}){const n=i.useMemo(()=>pz(mz()),[]);return t.jsx(ey.Provider,{value:n,children:e})}function gz(){return i.useContext(ey)}function bz(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function xz({open:e,shellApi:n,shellState:s,onComplete:a}){const[r,o]=i.useState(s.desktopMode??"remote"),[l,c]=i.useState("Remote Server"),[d,u]=i.useState(""),[m,h]=i.useState(""),[f,p]=i.useState(null),[g,x]=i.useState(!1),[w,b]=i.useState(!1),y=s.host==="desktop-shell";i.useEffect(()=>{y&&o(s.desktopMode??"remote")},[y,s.desktopMode]);const S=i.useMemo(()=>y&&r==="local"?!0:d.trim().length>0,[y,r,d]);return e?t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-onboarding-modal",children:[t.jsx("div",{className:"modal-header",children:t.jsx("h2",{children:"Welcome to Fusion"})}),t.jsxs("div",{className:"native-shell-onboarding-body",children:[t.jsx("p",{children:"Fusion helps you plan, run, and review AI-assisted engineering work."}),y&&t.jsxs("div",{className:"native-shell-onboarding-mode-row",children:[t.jsx("button",{type:"button",className:`btn ${r==="local"?"btn-primary":""}`,onClick:()=>o("local"),children:"Local Fusion"}),t.jsx("button",{type:"button",className:`btn ${r==="remote"?"btn-primary":""}`,onClick:()=>o("remote"),children:"Remote Server"})]}),(!y||r==="remote")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn",onClick:async()=>{p(null),x(!0);try{const j=await n.startQrScan();u(j.serverUrl),h(j.authToken??"")}catch(j){p(j.message)}finally{x(!1)}},disabled:g,children:g?"Scanning…":"Scan QR"}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-profile-name",children:"Profile name"}),t.jsx("input",{id:"native-shell-onboarding-profile-name",className:"input",value:l,onChange:j=>c(j.target.value)}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-server-url",children:"Server URL"}),t.jsx("input",{id:"native-shell-onboarding-server-url",className:"input",value:d,onChange:j=>u(j.target.value),placeholder:"https://your-fusion-host"}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-auth-token",children:"Auth token (optional)"}),t.jsx("input",{id:"native-shell-onboarding-auth-token",className:"input",type:"password",value:m,onChange:j=>h(j.target.value)})]}),f&&t.jsx("p",{className:"form-error",role:"alert",children:f})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",disabled:!S||w,onClick:async()=>{p(null),b(!0);try{if(y&&r==="local"){await n.setDesktopMode("local"),a();return}const j=await n.saveProfile({name:l.trim()||"Remote Server",serverUrl:d,authToken:m||null});if(y&&await n.setDesktopMode("remote"),await n.setActiveProfile(j.id),typeof window<"u"&&s.host!=="web"){window.location.href=bz(j.serverUrl,j.authToken??null);return}a()}catch(j){p(j.message)}finally{b(!1)}},children:w?"Saving…":"Continue"})})]})}):null}function vz({open:e,shellApi:n,shellState:s,onClose:a}){const r=i.useMemo(()=>s.profiles.find(v=>v.id===s.activeProfileId)??null,[s.activeProfileId,s.profiles]),[o,l]=i.useState(null),[c,d]=i.useState({}),[u,m]=i.useState(null),[h,f]=i.useState(null);if(!e)return null;const p=o==="__new__",g=p?null:s.profiles.find(v=>v.id===o)??r,x=c.name??g?.name??"",w=c.serverUrl??g?.serverUrl??"",b=c.authToken??g?.authToken??"",y=()=>{l(null),d({}),f(null)},S=async()=>{f(null);try{const v=new URL(w.trim());if(!/^https?:$/.test(v.protocol))throw new Error("Server URL must use http or https");const N=await n.saveProfile({id:p?void 0:o??g?.id,name:x||"Remote Server",serverUrl:w,authToken:b||null});await n.setActiveProfile(N.id),l(N.id),d({})}catch(v){f(v.message)}},j=async()=>{f(null);try{const v=await n.startQrScan();l("__new__"),d({name:"",serverUrl:v.serverUrl,authToken:v.authToken??""})}catch(v){f(v.message)}},C=async()=>{u&&(await n.deleteProfile(u.id),m(null),y())};return t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-connection-manager",role:"dialog","aria-label":"Connection Manager",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Connection Manager"}),t.jsx("button",{type:"button",className:"modal-close",onClick:a,"aria-label":"Close",children:"×"})]}),s.host==="desktop-shell"&&t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:`btn ${s.desktopMode==="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("local"),children:"Local"}),t.jsx("button",{type:"button",className:`btn ${s.desktopMode!=="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("remote"),children:"Remote"})]}),t.jsx("div",{className:"native-shell-connection-manager__profiles",children:s.profiles.length===0?t.jsxs("div",{className:"card native-shell-connection-manager__empty-state",children:[t.jsx("p",{className:"settings-muted",children:"No remote servers saved yet."}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l("__new__"),d({name:"",serverUrl:"",authToken:""}),f(null)},children:"Add server"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void j(),children:"Scan QR"})]})]}):s.profiles.map(v=>t.jsxs("div",{className:"card native-shell-connection-manager__profile",children:[t.jsxs("div",{children:[t.jsx("strong",{children:v.name}),t.jsx("div",{className:"settings-muted",children:v.serverUrl}),v.id===s.activeProfileId&&t.jsx("span",{className:"native-shell-connection-manager__active-pill",children:"Active"})]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Edit ${v.name}`,onClick:()=>{l(v.id),d(v)},children:"Edit"}),t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Use ${v.name}`,onClick:()=>void n.setActiveProfile(v.id),children:"Use"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger","aria-label":`Delete ${v.name}`,onClick:()=>m(v),children:"Delete"})]})]},v.id))}),t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:"btn",onClick:()=>{l("__new__"),d({name:"",serverUrl:"",authToken:""}),f(null)},children:"Add connection"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn",onClick:()=>void j(),children:"Scan QR"})]}),t.jsxs("div",{className:"form-group native-shell-connection-manager__editor",children:[t.jsx("label",{htmlFor:"native-shell-connection-manager-name",children:"Name"}),t.jsx("input",{id:"native-shell-connection-manager-name",className:"input",value:x,onChange:v=>d(N=>({...N,name:v.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-url",children:"Server URL"}),t.jsx("input",{id:"native-shell-connection-manager-url",className:"input",value:w,onChange:v=>d(N=>({...N,serverUrl:v.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-token",children:"Auth token (optional)"}),t.jsx("input",{id:"native-shell-connection-manager-token",className:"input",type:"password",value:b??"",onChange:v=>d(N=>({...N,authToken:v.target.value}))}),h&&t.jsx("p",{className:"form-error",role:"alert",children:h})]}),u&&t.jsxs("div",{className:"native-shell-connection-manager__delete-confirm",role:"alertdialog","aria-label":"Delete server confirmation",children:[t.jsxs("p",{children:["Delete ",t.jsx("strong",{children:u.name}),"? This removes the saved profile."]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>m(null),children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>void C(),children:"Delete"})]})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:a,children:"Close"}),t.jsx("button",{type:"button",className:"btn",onClick:y,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void S(),disabled:!w.trim(),children:"Save"})]})]})})}function yz(e){if(e.hostKind==="desktop-shell"&&e.mode==="local")return{title:"Desktop local mode",actionLabel:"Switch server",dotClassName:"status-dot status-dot--online"};const n=e.profileLabel??e.profileId,s=e.serverOrigin,a=n&&s?`${n} · ${s}`:n??s;return e.mode==="remote"?{title:a??"Connection info unavailable",actionLabel:e.hostKind==="desktop-shell"?"Switch server":"Manage connections",dotClassName:a?"status-dot status-dot--online":"status-dot status-dot--pending"}:{title:a??"Connection info unavailable",actionLabel:"Manage connections",dotClassName:a?"status-dot status-dot--online":"status-dot status-dot--pending"}}function Pg({status:e,onError:n}){if(e.hostKind==="browser"||!e.available)return null;const s=yz(e),a=i.useCallback(async()=>{const r=await e.openConnectionManager();!r.ok&&r.reason==="failed"&&n?.(r.error??"Failed to open connection manager")},[n,e]);return t.jsxs("button",{type:"button",className:"btn shell-connection-status",onClick:()=>void a(),"data-testid":"shell-connection-status-button",children:[t.jsx("span",{className:s.dotClassName,"aria-hidden":"true"}),t.jsx("span",{className:"shell-connection-status__kind",children:e.hostKind==="desktop-shell"?"Desktop":"Mobile"}),t.jsx("span",{className:"shell-connection-status__summary",title:s.title,children:s.title}),t.jsx("span",{className:"shell-connection-status__action",children:s.actionLabel})]})}function wz(e){if(e)try{return new URL(e).origin}catch{return}}function kz(e,n){const s=e.profiles.find(a=>a.id===e.activeProfileId)??null;return s||(n.kind==="browser"||!n.connectionId?null:e.profiles.find(a=>a.id===n.connectionId)??null)}async function jz(e){if(!e?.getState)return null;try{return await e.getState()}catch{return null}}async function Nz(e,n=window){const s=n.fusionAPI,a=n.fusionShell,r=await jz(a),o=r?kz(r,e):null,l=e.kind==="browser"?void 0:e.mode??r?.desktopMode,c=o?.id??(e.kind==="browser"?void 0:e.connectionId),d=o?.name,u=wz(o?.serverUrl??(e.kind==="browser"?void 0:e.serverUrl)),m=e.kind==="desktop-shell"&&typeof s?.openConnectionManager=="function",h=e.kind==="mobile-shell"&&typeof a?.openConnectionManager=="function",f=m||h;return{hostKind:e.kind,available:f,...l?{mode:l}:{},...c?{profileId:c}:{},...d?{profileLabel:d}:{},...u?{serverOrigin:u}:{},openConnectionManager:async()=>{try{return m?(await s.openConnectionManager?.(),{ok:!0}):h?(await a.openConnectionManager(),{ok:!0}):{ok:!1,reason:"unsupported"}}catch(p){return{ok:!1,reason:"failed",error:p instanceof Error?p.message:String(p)}}}}}function Sz({open:e}){const[n,s]=i.useState(""),a=i.useRef(null);i.useEffect(()=>{e&&a.current?.focus()},[e]);const r=i.useCallback(()=>{const l=n.trim();l&&(xj(l),window.location.reload())},[n]),o=i.useCallback(()=>{vj(),window.location.reload()},[]);return e?t.jsx("div",{className:"modal-overlay open auth-token-recovery-overlay",role:"presentation",onKeyDownCapture:l=>{l.key==="Escape"&&(l.preventDefault(),l.stopPropagation())},children:t.jsxs("div",{className:"modal modal-md",role:"dialog","aria-modal":"true","aria-labelledby":"auth-token-recovery-title","aria-describedby":"auth-token-recovery-description",children:[t.jsx("div",{className:"modal-header auth-token-recovery-header",children:t.jsx("h3",{id:"auth-token-recovery-title",children:"Authentication token required"})}),t.jsxs("div",{className:"auth-token-recovery-content",children:[t.jsx("p",{id:"auth-token-recovery-description",children:"This dashboard session can't authenticate with the daemon. Set a replacement token or clear the current token and retry."}),t.jsxs("div",{className:"auth-token-recovery-field",children:[t.jsx("label",{htmlFor:"auth-token-recovery-input",children:"Replacement token"}),t.jsx("input",{ref:a,id:"auth-token-recovery-input",className:"input",type:"password",value:n,onChange:l=>s(l.target.value),placeholder:"Paste token",autoComplete:"off",spellCheck:!1})]})]}),t.jsxs("div",{className:"modal-actions auth-token-recovery-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:o,children:"Clear token and retry"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:r,disabled:n.trim().length===0,children:"Set token and reload"})]})]})}):null}const Cz=200,Ez=i.lazy(()=>Sn(()=>import("./AgentsView-CpwqOVDz.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])).then(e=>({default:e.AgentsView}))),_z=i.lazy(()=>Sn(()=>import("./DocumentsView-B94U9ijs.js"),__vite__mapDeps([32,1,5,6,33])).then(e=>({default:e.DocumentsView}))),Mz=i.lazy(()=>Sn(()=>import("./InsightsView-D-Qe0tRr.js"),__vite__mapDeps([34,1,22,5,6,35])).then(e=>({default:e.InsightsView}))),Az=i.lazy(()=>Sn(()=>import("./ResearchView-CjOxKhdS.js"),__vite__mapDeps([36,1,5,6,37])).then(e=>({default:e.ResearchView}))),Rz=i.lazy(()=>Sn(()=>import("./EvalsView-O_4YWy--.js"),__vite__mapDeps([38,1,5,6,39])).then(e=>({default:e.EvalsView}))),Iz=i.lazy(()=>Sn(()=>import("./NodesView-DQzXjcLc.js"),__vite__mapDeps([40,1,17,30,5,6,41])).then(e=>({default:e.NodesView}))),Tz=i.lazy(()=>Sn(()=>import("./ChatView-DyRBOIKL.js"),__vite__mapDeps([42,1,5,6,43])).then(e=>({default:e.ChatView}))),Pz=i.lazy(()=>Sn(()=>import("./SkillsView-BIFoVNUf.js"),__vite__mapDeps([44,1,5,6,45])).then(e=>({default:e.SkillsView}))),$z=i.lazy(()=>Sn(()=>import("./MemoryView-CoRUmRvb.js"),__vite__mapDeps([46,1,20,21,5,6,47])).then(e=>({default:e.MemoryView}))),Dz=i.lazy(()=>Sn(()=>import("./DevServerView-Cdelj9-m.js"),__vite__mapDeps([48,1,5,6,49])).then(e=>({default:e.DevServerView})));i.lazy(()=>Sn(()=>import("./TodoView-sS_mT0Y7.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));const Lz=i.lazy(()=>Sn(()=>import("./StashRecoveryView-C52KsV7f.js"),__vite__mapDeps([50,1,5,6,51])).then(e=>({default:e.StashRecoveryView})));function Oz(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{Sn(()=>import("./AgentsView-CpwqOVDz.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])),Sn(()=>import("./DocumentsView-B94U9ijs.js"),__vite__mapDeps([32,1,5,6,33])),Sn(()=>import("./InsightsView-D-Qe0tRr.js"),__vite__mapDeps([34,1,22,5,6,35])),Sn(()=>import("./ResearchView-CjOxKhdS.js"),__vite__mapDeps([36,1,5,6,37])),Sn(()=>import("./EvalsView-O_4YWy--.js"),__vite__mapDeps([38,1,5,6,39])),Sn(()=>import("./NodesView-DQzXjcLc.js"),__vite__mapDeps([40,1,17,30,5,6,41])),Sn(()=>import("./ChatView-DyRBOIKL.js"),__vite__mapDeps([42,1,5,6,43])),Sn(()=>import("./SkillsView-BIFoVNUf.js"),__vite__mapDeps([44,1,5,6,45])),Sn(()=>import("./MemoryView-CoRUmRvb.js"),__vite__mapDeps([46,1,20,21,5,6,47])),Sn(()=>import("./DevServerView-Cdelj9-m.js"),__vite__mapDeps([48,1,5,6,49])),Sn(()=>import("./TodoView-sS_mT0Y7.js"),__vite__mapDeps([11,1,5,6,12])),Sn(()=>import("./StashRecoveryView-C52KsV7f.js"),__vite__mapDeps([50,1,5,6,51]))})}Jv();const Kd="kb-setup-warning-dismissed",Fz="kb-chat-active-session",$g="kb-dashboard-working-branch-filter",Dg="kb-dashboard-base-branch-filter",Lg="__fusion:no-branch__",ty="fusion:approval-banner-dismissed";function zz(e,n){return e==="awaiting-approval"&&n!=="awaiting-approval"}function Og(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Bz(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(ty);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[a,r]of Object.entries(n))typeof r=="number"&&Number.isFinite(r)&&s.set(a,r);return s}catch{return new Map}}function Fg(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(ty,JSON.stringify(n))}catch{}}function Uz(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function Hz(e,n,s){return!n||s||e.host==="web"?!1:e.host==="mobile-shell"?!e.activeProfileId:e.desktopMode==="local"?!1:!e.activeProfileId}function qz(){const{toasts:e,addToast:n,removeToast:s}=NF(),{shellApi:a,state:r,ready:o,openConnectionManagerSignal:l}=Rv(),c=gz();i.useEffect(()=>{Oz()},[]);const{projects:d,loading:u,error:m,refresh:h}=vF(),{nodes:f}=yc(),{currentNode:p,currentNodeId:g,isRemote:x,setCurrentNode:w,clearCurrentNode:b}=nz(),{currentProject:y,setCurrentProject:S,clearCurrentProject:j,loading:C}=kF(d,{nodeId:g}),{hasAiProvider:v,hasGithub:N,loading:I,hasWarnings:F}=Ev(y?.id),{updateAvailable:_,latestVersion:M,currentVersion:z,dismissed:U,dismiss:R}=LF();i.useEffect(()=>{if(g&&!p&&f.length>0){const Ye=f.find(Tt=>Tt.id===g);if(Ye){w(Ye);return}}g&&f.length>0&&(f.some(Tt=>Tt.id===g)||b())},[g,p,f,w,b]);const[D,K]=i.useState(""),[Z,ne]=i.useState(""),[O,A]=i.useState("");i.useEffect(()=>{ne(zn($g,y?.id)??""),A(zn(Dg,y?.id)??"")},[y?.id]);const P=i.useCallback(Ye=>{ne(Ye),us($g,Ye,y?.id)},[y?.id]),$=i.useCallback(Ye=>{A(Ye),us(Dg,Ye,y?.id)},[y?.id]),k=XF(g,{projectId:y?.id,searchQuery:D||void 0});ZF(g);const J=x&&k.projects.length>0?k.projects:d,{themeMode:ce,colorTheme:je,dashboardFontScalePct:He,setThemeMode:xe,setColorTheme:Ne,setDashboardFontScalePct:Y}=RF(),{sessions:ie,generating:ee,needsInput:oe,planningSessions:W,dismissSession:L}=dF(y?.id),pe=ie.filter(Ye=>Ye.status==="awaiting_input"||Ye.status==="error"),fe=hF(),B=IF({projectId:y?.id,planningSessions:W}),Fe=ri()==="mobile",{pushNav:ae,replaceCurrent:qe}=UF({enabled:!0}),{viewMode:Pe,setViewMode:nt,taskView:Be,handleChangeTaskView:de}=BF({projectsLoading:u,projectsError:m,currentProjectLoading:C,currentProject:y,projectsLength:d.length,setupWizardOpen:B.setupWizardOpen,openSetupWizard:B.openSetupWizard,themeMode:ce,setThemeMode:xe}),{views:Ie}=qF(y?.id),$e=i.useMemo(()=>{const Ye=Ie.find(Tt=>Tt.pluginId==="fusion-plugin-dependency-graph"&&Tt.view.viewId==="graph");return Ye?`plugin:${Ye.pluginId}:${Ye.view.viewId}`:Sb("fusion-plugin-dependency-graph","graph")?"plugin:fusion-plugin-dependency-graph:graph":null},[Ie]),st=i.useCallback(Ye=>{Ye==="missions"&&(an(void 0),it(void 0),$t(void 0));const Tt=Be;de(Ye),Tt!==Ye&&ae({type:"view",revert:()=>de(Tt)})},[de,Be,ae]),Ue=Be==="board"||Be==="list",{tasks:me,createTask:re,moveTask:_e,pauseTask:xt,deleteTask:ut,mergeTask:Qe,retryTask:vt,resetTask:Ae,updateTask:Je,duplicateTask:dt,archiveTask:Nt,unarchiveTask:yt,archiveAllDone:Se,loadArchivedTasks:G,ingestCreatedTasks:ge,lastFetchTimeMs:pt}=fF({...y?{projectId:y.id}:{},searchQuery:D||void 0,sseEnabled:Ue}),ke=x&&k.tasks.length>0?k.tasks:me,[tt,Rt]=i.useState(!1),[Re,be]=i.useState(0),rt=i.useRef(performance.now()),lt=i.useRef(!1),gt=i.useRef(!1),St=i.useMemo(()=>u?"projects":C?"project":"tasks",[u,C]);i.useEffect(()=>{if(!u&&!lt.current){lt.current=!0;const Ye=`projects loaded at ${Math.round(performance.now()-rt.current)}ms from mount`;console.log(`[App] ${Ye}`)}if(!C&&!gt.current){gt.current=!0;const Ye=`current-project resolved at ${Math.round(performance.now()-rt.current)}ms from mount`;console.log(`[App] ${Ye}`)}},[u,C]),i.useEffect(()=>{if(tt||u||C)return;const Ye=performance.now(),Tt=window.setTimeout(()=>{const cn=`dashboard ready at ${Math.round(performance.now()-rt.current)}ms from mount (settle delay=${Math.round(performance.now()-Ye)}ms)`;console.log(`[App] ${cn}`),Rt(!0)},Cz);return()=>{window.clearTimeout(Tt)}},[tt,u,C]);const{keyboardOpen:Lt}=Zi({enabled:Fe}),Yt=Fe&&Lt&&!B.anyModalOpen;Ni(Yt);const[tn,mn]=i.useState(0),[Qt,yn]=i.useState(0),[Gt,on]=i.useState(!1),[sn,ln]=i.useState(0),[Wt,ye]=i.useState(null),Le=i.useRef(new Map),Ke=i.useRef(new Set),mt=i.useRef(Bz()),Ve=i.useCallback(()=>{xb(y?.id).then(Ye=>{mn(Ye.unreadCount),yn(Ye.pendingApprovalCount??0)}).catch(Ye=>{console.warn("[App] Failed to fetch mailbox unread count:",Ye)})},[y?.id]);i.useEffect(()=>{const Ye=new Map,Tt=new Set;for(const cn of me)Ye.set(cn.id,cn.status),cn.status==="awaiting-approval"&&Tt.add(`task:${cn.id}`);Le.current=Ye,Ke.current=Tt},[me]),i.useEffect(()=>{Ve();const Ye=new URLSearchParams;y?.id&&Ye.set("projectId",y.id);const Tt=Ye.size>0?`?${Ye.toString()}`:"",cn=cs=>{const Hn=mt.current.get(cs.dedupeKey);Hn!==void 0&&cs.updatedAtMs<=Hn||ye(cs)};return hi(`/api/events${Tt}`,{onReconnect:Ve,events:{"message:sent":Ve,"message:received":Ve,"message:read":Ve,"message:deleted":Ve,"approval:requested":cs=>{Ve();try{const Hn=JSON.parse(cs.data),Cs=Hn.id?`approval:${Hn.id}`:Hn.taskId?`task:${Hn.taskId}`:void 0;if(!Cs||Ke.current.has(Cs))return;Ke.current.add(Cs),cn({dedupeKey:Cs,updatedAtMs:Og(Hn.updatedAt??Hn.createdAt)})}catch{}},"approval:updated":Ve,"approval:decided":Ve,"task:updated":cs=>{try{const Hn=JSON.parse(cs.data);if(!Hn?.id)return;const Cs=`task:${Hn.id}`,na=Le.current.get(Hn.id);if(Le.current.set(Hn.id,Hn.status),Hn.status!=="awaiting-approval"){Ke.current.delete(Cs),mt.current.delete(Cs),Fg(mt.current);return}if(Ke.current.has(Cs))return;zz(Hn.status,na)&&(Ke.current.add(Cs),cn({dedupeKey:Cs,updatedAtMs:Og(Hn.updatedAt)}),Ve())}catch{}}}})},[y?.id,Ve]),i.useEffect(()=>{Be==="chat"&&on(!1)},[Be]),i.useEffect(()=>{let Ye=!1;const Tt=async()=>{try{const cs=await T("/stash-recovery/orphans");Ye||ln(cs.count??0)}catch{Ye||ln(0)}};Tt();const cn=window.setInterval(()=>void Tt(),3e4);return()=>{Ye=!0,window.clearInterval(cn)}},[y?.id]),i.useEffect(()=>{const Ye=new URLSearchParams;y?.id&&Ye.set("projectId",y.id);const Tt=Ye.size>0?`?${Ye.toString()}`:"";return hi(`/api/events${Tt}`,{events:{"chat:message:added":cn=>{try{const cs=JSON.parse(cn.data),Hn=zn(Fz,y?.id);if(!Hn||cs.role!=="assistant"||Be==="chat"||cs.sessionId!==Hn||cs.projectId&&y?.id&&cs.projectId!==y.id)return;on(!0)}catch{}}}})},[y?.id,Be]);const Pt=i.useMemo(()=>Array.from(new Set(ke.map(Ye=>Ye.branch?.trim()).filter(Ye=>!!(Ye&&Ye.length>0)))).sort((Ye,Tt)=>Ye.localeCompare(Tt)),[ke]),Ot=i.useMemo(()=>Array.from(new Set(ke.map(Ye=>Ye.baseBranch?.trim()).filter(Ye=>!!(Ye&&Ye.length>0)))).sort((Ye,Tt)=>Ye.localeCompare(Tt)),[ke]),bt=i.useMemo(()=>ke.filter(Ye=>{const Tt=Ye.branch?.trim()??"",cn=Ye.baseBranch?.trim()??"";if(Z===Lg){if(Tt.length>0)return!1}else if(Z.length>0&&Tt!==Z)return!1;if(O===Lg){if(cn.length>0)return!1}else if(O.length>0&&cn!==O)return!1;return!0}),[ke,Z,O]),[Dt,Ft]=i.useState(!1),[Ht,rn]=i.useState(!1),[Xt,an]=i.useState(void 0),[Me,it]=i.useState(void 0),[kt,$t]=i.useState(void 0),[se,te]=i.useState(!1),[De,ft]=i.useState(!1),[qt,zt]=i.useState(()=>zn(Kd,y?.id)==="true");i.useEffect(()=>{zt(zn(Kd,y?.id)==="true")},[y?.id]),i.useEffect(()=>{const Ye=()=>{ft(!0)};return window.addEventListener(su,Ye),()=>{window.removeEventListener(su,Ye)}},[]);const Pn=i.useCallback(()=>{us(Kd,"true",y?.id),zt(!0)},[y?.id]),{maxConcurrent:he,autoMerge:ht,globalPaused:at,enginePaused:wt,taskStuckTimeoutMs:Xe,staleHighFanoutBlockerAgeThresholdMs:Et,showQuickChatFAB:Zt,prAuthAvailable:le,settingsLoaded:ct,experimentalFeatures:nn,insightsEnabled:Rn,memoryEnabled:Un,devServerEnabled:wn,todosEnabled:rs,toggleAutoMerge:_s,toggleGlobalPause:bn,toggleEnginePause:Ut,refresh:xs}=TF(y?.id),xn=nn.skillsView===!0,Xn=nn.nodesView===!0,$n=nn.researchView===!0,vs=nn.evalsView===!0,ms=nn.agentOnboarding===!0,hs=!0,Jn=i.useCallback(()=>{B.closeSettings(),be(Ye=>Ye+1),xs()},[B,xs]);i.useEffect(()=>{if(ct&&!fr(Be)){if(Be==="graph"&&!$e){de("board");return}Be==="skills"&&!xn&&de("board"),Be==="insights"&&!Rn&&de("board"),Be==="memory"&&!Un&&de("board"),(Be==="devserver"||Be==="dev-server")&&!wn&&de("board"),Be==="research"&&!$n&&de("board"),Be==="evals"&&!vs&&de("board")}},[Be,ct,xn,Rn,de,hs,Un,wn,$n,vs,$e]),i.useEffect(()=>{Dt&&!Xn&&Ft(!1)},[Dt,Xn]);const{availableModels:ps,favoriteProviders:Ns,favoriteModels:Yn,toggleFavoriteProvider:ys,toggleFavoriteModel:ws}=$F();DF({projectId:y?.id,setupWizardOpen:B.setupWizardOpen,openModelOnboarding:B.openModelOnboarding,openSettings:B.openSettings});const{handleSelectProject:Ms,handleViewAllProjects:X,handleAddProject:E,handleSetupComplete:ue,handleModelOnboardingComplete:Ce,handlePauseProject:We,handleResumeProject:At,handleRemoveProject:q,handleToggleFavorite:we,handleToggleModelFavorite:Oe}=YF({setCurrentProject:S,clearCurrentProject:j,setViewMode:nt,currentProject:y,refreshProjects:h,toggleFavoriteProvider:ys,toggleFavoriteModel:ws,addToast:n,openSettings:B.openSettings,openSetupWizard:B.openSetupWizard,closeSetupWizard:B.closeSetupWizard,closeModelOnboarding:B.closeModelOnboarding}),{handleDetailClose:It}=PF({projectId:y?.id,projects:d,projectsLoading:u,currentProject:y,setCurrentProject:S,addToast:n,openTaskDetail:B.openDetailTask,closeTaskDetail:B.closeDetailTask}),Kt=i.useCallback(async({insightId:Ye,title:Tt,description:cn})=>{await re({title:Tt,description:cn,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:Ye}}})},[re]),{handleBoardQuickCreate:fn,handleModalCreate:An,handlePlanningTaskCreated:jn,handlePlanningTasksCreated:En,handleSubtaskTasksCreated:ts,handleGitHubImport:Ln}=QF({createTask:re,ingestCreatedTasks:ge,onPlanningTaskCreated:B.onPlanningTaskCreated,onPlanningTasksCreated:B.onPlanningTasksCreated,onSubtaskTasksCreated:B.onSubtaskTasksCreated,addToast:n}),os=i.useCallback((Ye,Tt)=>{Tt==="changes"?B.openDetailWithChangesTab(Ye):B.openDetailTask(Ye,Tt),ae({type:"modal",close:B.closeDetailTask})},[B,ae]),fs=i.useCallback(async Ye=>{try{const Tt=await La(Ye,y?.id);B.openDetailTask(Tt,"logs"),ae({type:"modal",close:B.closeDetailTask})}catch(Tt){n(`Failed to open task logs: ${Tt.message}`,"error")}},[B,y?.id,n,ae]),[ns,Zn]=i.useState([]);i.useEffect(()=>{let Ye=!1;return Uo(y?.id).then(Tt=>{Ye||Zn(Tt)}).catch(()=>{Ye||Zn([])}),()=>{Ye=!0}},[y?.id]);const es=i.useMemo(()=>new Map(ns.map(Ye=>[Ye.id,Ye.name])),[ns]);i.useCallback(()=>{Xn&&Ft(Ye=>!Ye)},[Xn]);const Ss=i.useCallback(()=>{Xn&&(Dt?Ft(!1):(Ft(!0),ae({type:"view",revert:()=>Ft(!1)})))},[Xn,Dt,ae]),ls=i.useCallback((Ye,Tt,cn)=>{B.openDetailTask(Ye,Tt,cn),ae({type:"modal",close:B.closeDetailTask})},[B,ae]),ss=i.useCallback(Ye=>{B.openSettings(Ye),ae({type:"modal",close:Jn})},[B,ae,Jn]),Zs=i.useCallback(()=>{B.openNewTask(),ae({type:"modal",close:B.closeNewTask})},[B,ae]),Si=i.useCallback(()=>{B.openPlanning(),ae({type:"modal",close:B.closePlanning})},[B,ae]),ga=i.useCallback(Ye=>{B.openPlanningWithInitialPlan(Ye),ae({type:"modal",close:B.closePlanning})},[B,ae]),Wa=i.useCallback(()=>{B.resumePlanning(),ae({type:"modal",close:B.closePlanning})},[B,ae]),Ka=i.useCallback(Ye=>{B.openSubtaskBreakdown(Ye),ae({type:"modal",close:B.closeSubtask})},[B,ae]),Ga=i.useCallback(()=>{B.openGitHubImport(),ae({type:"modal",close:B.closeGitHubImport})},[B,ae]),oi=i.useCallback(()=>{B.terminalOpen?B.toggleTerminal():(B.toggleTerminal(),ae({type:"modal",close:B.closeTerminal}))},[B,ae]),gn=i.useCallback(()=>{B.openFiles(),ae({type:"modal",close:B.closeFiles})},[B,ae]),Fi=i.useCallback(()=>{B.openTodos(),ae({type:"modal",close:B.closeTodos})},[B,ae]),ea=i.useCallback(()=>{B.openActivityLog(),ae({type:"modal",close:B.closeActivityLog})},[B,ae]),ba=i.useCallback(()=>{B.openGitManager(),ae({type:"modal",close:B.closeGitManager})},[B,ae]),Ja=i.useCallback(()=>{B.openSystemStats(),ae({type:"modal",close:B.closeSystemStats})},[B,ae]),xa=i.useCallback(()=>{B.openSchedules(),ae({type:"modal",close:B.closeSchedules})},[B,ae]),va=i.useCallback(()=>{B.openScripts(),ae({type:"modal",close:B.closeScripts})},[B,ae]),ya=i.useCallback(()=>{B.openWorkflowSteps(),ae({type:"modal",close:B.closeWorkflowSteps})},[B,ae]),Ya=i.useCallback(Ye=>{B.openUsage(Ye),ae({type:"modal",close:B.closeUsage})},[B,ae]),wa=i.useCallback(async(Ye,Tt)=>{await B.runScript(Ye,Tt),qe({type:"modal",close:B.closeTerminal})},[B,qe]),zr=i.useCallback(()=>{B.closeSettings(),B.openModelOnboarding(),qe({type:"modal",close:B.closeModelOnboarding})},[B,qe]),ka=i.useCallback(()=>{B.setFileWorkspace("project"),B.openFiles()},[B]),Us=i.useCallback(async()=>{rn(!0);try{await h()}finally{rn(!1)}},[h]),Ci=i.useCallback(Ye=>{it(Ye),an(void 0),de("missions")},[de]),ei=i.useCallback(Ye=>{Ye.type==="planning"?B.openPlanningWithSession(Ye.id):Ye.type==="subtask"?B.openSubtaskWithSession(Ye.id):Ye.type==="mission_interview"?(it(void 0),an(Ye.id),$t(void 0),de("missions")):(Ye.type==="milestone_interview"||Ye.type==="slice_interview")&&(an(void 0),it(void 0),$t(Ye.id),de("missions"))},[de,B]),ta=i.useCallback(()=>{},[]),ja=i.useCallback(()=>{},[]),[Br,Ei]=i.useState(!1),[Na,Sa]=i.useState(!1),[zi,Qa]=i.useState(null),Ur=Hz(r,o,Br);i.useEffect(()=>{!a||l===0||Sa(!0)},[a,l]),i.useEffect(()=>{let Ye=!1;return Nz(c.host).then(Tt=>{Ye||Qa(Tt)}),()=>{Ye=!0}},[c.host,r.activeProfileId,r.desktopMode,r.host,r.profiles]),i.useEffect(()=>{r.host==="desktop-shell"&&r.desktopMode==="local"&&(r.localServer?.status!=="ready"||!r.localServer.port||window.location.port!==String(r.localServer.port)&&(window.location.href=`http://localhost:${r.localServer.port}`))},[r]),i.useEffect(()=>{if(r.host!=="desktop-shell"||r.desktopMode!=="remote")return;const Ye=r.profiles.find(cn=>cn.id===r.activeProfileId);if(!Ye||typeof window>"u")return;const Tt=Uz(Ye.serverUrl,Ye.authToken??null);window.location.href!==Tt&&(window.location.href=Tt)},[r]);const Xa=!u&&!C&&d.length===0&&!y&&!!m,Za=()=>{if(Xa)return t.jsx(pO,{errorMessage:m??"Failed to fetch projects",isRetrying:Ht,onRetry:Us,onManageConnection:a?()=>{a.openConnectionManager()}:void 0});if(Dt)return t.jsx("div",{className:"nodes-management-overlay",children:t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Iz,{addToast:n,onClose:()=>Ft(!1)})})})});if(Pe==="overview")return t.jsx($s,{children:t.jsx(WP,{projects:d,loading:u,onSelectProject:Ms,onAddProject:E,onPauseProject:We,onResumeProject:At,onRemoveProject:q,nodes:f})});const Ye=Be==="graph"?$e:fr(Be)?Be:null;return Ye?t.jsx($s,{children:t.jsx(VF,{taskView:Ye,context:{projectId:y?.id,tasks:x&&k.tasks.length>0?k.tasks:me,workflowSteps:ns,openTaskDetail:(Tt,cn)=>ls(Tt,cn),renderTaskCard:Tt=>t.jsx(Mo,{task:Tt,projectId:y?.id,onOpenDetail:cn=>ls(cn),addToast:n,workflowStepNameLookup:es,disableDrag:!0}),addToast:n}})}):Be==="skills"?!ct||!xn?null:t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Pz,{addToast:n,projectId:y?.id,onClose:()=>de("board")})})}):Be==="chat"?t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Tz,{addToast:n,projectId:y?.id,experimentalFeatures:nn})})}):Be==="mailbox"?t.jsx($s,{children:t.jsx(F$,{projectId:y?.id,addToast:n,onUnreadCountChange:mn})}):Be==="missions"?t.jsx($s,{children:t.jsx(P$,{isInline:!0,isOpen:!0,onClose:()=>{it(void 0),an(void 0),$t(void 0),de("board")},addToast:n,projectId:y?.id,onSelectTask:Tt=>{const cn=me.find(cs=>cs.id===Tt);cn&&ls(cn)},availableTasks:me.map(Tt=>({id:Tt.id,title:Tt.title})),resumeSessionId:Xt,targetMissionId:Me,milestoneSliceResumeSessionId:kt,onMilestoneSliceResumeFetchError:()=>$t(void 0)})}):Be==="agents"&&hs?t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Ez,{addToast:n,projectId:y?.id,onOpenTaskLogs:fs,agentOnboardingEnabled:ms})})}):Be==="documents"?t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(_z,{projectId:y?.id,addToast:n,onOpenDetail:ls})})}):Be==="stash-recovery"?t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Lz,{})})}):Be==="insights"?!ct||!Rn?null:t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Mz,{projectId:y?.id,addToast:n,onClose:()=>de("board"),onCreateTask:Kt})})}):Be==="research"?!ct||!$n?null:t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Az,{projectId:y?.id,addToast:n,onOpenSettings:Tt=>B.openSettings(Tt),readinessVersion:Re})})}):Be==="evals"?!ct||!vs?null:t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Rz,{projectId:y?.id,onOpenSettings:Tt=>B.openSettings(Tt),onOpenTaskDetail:Tt=>{La(Tt,y?.id).then(cn=>ls(cn)).catch(cn=>n(cn instanceof Error?cn.message:"Failed to open task detail","error"))}})})}):Be==="memory"?!ct||!Un?null:t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx($z,{addToast:n,projectId:y?.id})})}):Be==="devserver"||Be==="dev-server"?!ct||!wn?null:t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Dz,{addToast:n,projectId:y?.id})})}):Be==="board"?t.jsx($s,{children:t.jsx(qE,{tasks:bt,projectId:y?.id,maxConcurrent:he,onMoveTask:_e,onPauseTask:xt,onOpenDetail:ls,addToast:n,onQuickCreate:fn,onNewTask:Zs,onPlanningMode:ga,onSubtaskBreakdown:Ka,autoMerge:ht,onToggleAutoMerge:_s,globalPaused:at,onUpdateTask:Je,onRetryTask:vt,onArchiveTask:Nt,onUnarchiveTask:yt,onDeleteTask:ut,onArchiveAllDone:Se,onLoadArchivedTasks:G,searchQuery:D,availableModels:ps,onOpenDetailWithTab:os,favoriteProviders:Ns,favoriteModels:Yn,onToggleFavorite:we,onToggleModelFavorite:Oe,taskStuckTimeoutMs:Xe,staleHighFanoutBlockerAgeThresholdMs:Et,onOpenMission:Ci,lastFetchTimeMs:pt})}):t.jsx($s,{children:t.jsx(PP,{tasks:x&&k.tasks.length>0?k.tasks:me,projectId:y?.id,onMoveTask:_e,onRetryTask:vt,onDeleteTask:ut,onMergeTask:Qe,onResetTask:Ae,onDuplicateTask:dt,onOpenDetail:(Tt,cn)=>ls(Tt,void 0,cn),addToast:n,globalPaused:at,onNewTask:Zs,onQuickCreate:fn,onPlanningMode:ga,onSubtaskBreakdown:Ka,availableModels:ps,favoriteProviders:Ns,favoriteModels:Yn,onToggleFavorite:we,onToggleModelFavorite:Oe,taskStuckTimeoutMs:Xe,searchQuery:D,lastFetchTimeMs:pt,prAuthAvailable:le})})};if(!tt)return t.jsxs(t.Fragment,{children:[t.jsx(gO,{stage:St}),t.jsx(Dv,{toasts:e,onRemove:s})]});const er=!B.modelOnboardingOpen&&OL(),Hr=!B.modelOnboardingOpen&&!er&&Rr()&&!Iv();return t.jsxs(t.Fragment,{children:[t.jsx(yC,{shellHost:c.host,onOpenSettings:ss,onOpenGitHubImport:Ga,onOpenPlanning:Si,onResumePlanning:Wa,activePlanningSessionCount:W.length,onOpenUsage:Ya,onOpenActivityLog:ea,onOpenSystemStats:Ja,onOpenMailbox:()=>st("mailbox"),mailboxUnreadCount:tn,mailboxPendingApprovalCount:Qt,chatHasUnreadResponse:Gt,stashOrphanCount:sn,onOpenSchedules:xa,onOpenGitManager:ba,onOpenNodes:Ss,showNodesButton:Xn,onOpenWorkflowSteps:ya,onOpenScripts:va,onRunScript:wa,onToggleTerminal:oi,onOpenFiles:gn,filesOpen:B.filesOpen,onOpenTodos:Fi,todosOpen:B.todosOpen,todosEnabled:rs,globalPaused:at,enginePaused:wt,onToggleGlobalPause:bn,onToggleEnginePause:Ut,view:Be,onChangeView:Pe==="project"&&y?st:void 0,showSkillsTab:xn,showAgentsTab:hs,searchQuery:D,onSearchChange:K,branchFilter:Z,baseBranchFilter:O,branchOptions:Pt,baseBranchOptions:Ot,onBranchFilterChange:P,onBaseBranchFilterChange:$,projects:J,currentProject:y,onSelectProject:Ms,onViewAllProjects:X,projectId:y?.id,mobileNavEnabled:Fe,availableNodes:f,currentNode:p,onSelectNode:Ye=>{Ye===null?b():w(Ye)},isRemote:x,experimentalFeatures:{insights:Rn,memoryView:Un,devServer:wn,devServerView:wn,researchView:$n,evalsView:vs},pluginDashboardViews:Ie,shellConnectionControl:!Fe&&zi?t.jsx(Pg,{status:zi,onError:Ye=>n(Ye,"error")}):void 0}),Pe==="project"&&y&&!Dt&&Be!=="missions"&&!B.isPlanningOpen&&!fe&&t.jsx(RO,{sessions:pe,onResumeSession:ei,onDismissSession:ta,onDismissAll:ja}),Pe==="project"&&y&&t.jsx(PO,{onOpenSettings:()=>B.openSettings("general")}),Pe==="project"&&y&&er&&t.jsx(LO,{onResume:B.openModelOnboarding}),Pe==="project"&&y&&Hr&&t.jsx(OO,{onOpenModelOnboarding:B.openModelOnboarding,onOpenSettings:Ye=>B.openSettings(Ye)}),Pe==="project"&&y&&_&&M&&z&&!U&&t.jsx($O,{latestVersion:M,currentVersion:z,onDismiss:R}),Pe==="project"&&y&&!I&&F&&!qt&&t.jsx(_v,{hasAiProvider:v,hasGithub:N,onDismiss:Pn}),Pe==="project"&&y&&Wt&&t.jsx(DO,{pendingCount:Math.max(Qt,1),onOpenMailbox:()=>st("mailbox"),onDismiss:()=>{mt.current.set(Wt.dedupeKey,Math.max(Date.now(),Wt.updatedAtMs)),Fg(mt.current),ye(null)}}),t.jsx("div",{className:`project-content${Pe==="project"&&y&&(!Fe||!Yt)?" project-content--with-footer":""}${Fe&&!Yt?" project-content--with-mobile-nav":""}`,children:Za()}),Pe==="project"&&y&&!Dt&&t.jsx(CO,{tasks:x&&k.tasks.length>0?k.tasks:me,projectId:y.id,taskStuckTimeoutMs:Xe,staleHighFanoutBlockerAgeThresholdMs:Et,backgroundSessions:ie,backgroundGenerating:ee,backgroundNeedsInput:oe,onOpenBackgroundSession:ei,onDismissBackgroundSession:L,lastFetchTimeMs:pt,currentProjectPath:y.path,onOpenProjectDirectory:ka,keyboardOpen:Yt}),t.jsx(zO,{view:Be,onChangeView:Pe==="project"&&y?st:()=>{},footerVisible:Pe==="project"&&!!y,modalOpen:B.anyModalOpen,keyboardOpen:Yt,onOpenSettings:ss,onOpenActivityLog:ea,onOpenSystemStats:Ja,onOpenMailbox:()=>st("mailbox"),onOpenNodes:Ss,mailboxUnreadCount:tn,mailboxPendingApprovalCount:Qt,chatHasUnreadResponse:Gt,stashOrphanCount:sn,onOpenGitManager:ba,onOpenWorkflowSteps:ya,onOpenSchedules:xa,onOpenScripts:va,onToggleTerminal:oi,onOpenFiles:gn,onOpenTodos:Fi,todosOpen:B.todosOpen,onOpenGitHubImport:Ga,onOpenPlanning:Si,onResumePlanning:Wa,activePlanningSessionCount:W.length,onOpenUsage:()=>Ya(null),onViewAllProjects:X,onRunScript:wa,projectId:y?.id,showSkillsTab:xn,experimentalFeatures:{insights:Rn,memoryView:Un,devServer:wn,devServerView:wn,todoView:rs,researchView:$n,evalsView:vs,nodesView:Xn},pluginDashboardViews:Ie,shellConnectionControl:Fe&&zi?t.jsx(Pg,{status:zi,onError:Ye=>n(Ye,"error")}):void 0}),Pe==="project"&&y&&Be!=="chat"&&Be!=="mailbox"&&Be!=="insights"&&Be!=="evals"&&Be!=="devserver"&&Be!=="dev-server"&&Be!=="graph"&&!fr(Be)&&t.jsx(cF,{projectId:y.id,addToast:n,showFAB:Zt,open:se,onOpenChange:te,favoriteProviders:Ns,favoriteModels:Yn,onToggleFavorite:we,onToggleModelFavorite:Oe}),t.jsx(hO,{projectId:y?.id,tasks:me,projects:d,currentProject:y,addToast:n,toasts:e,removeToast:s,modalManager:B,projectActions:{handleAddProject:E,handleSetupComplete:ue,handleModelOnboardingComplete:Ce},taskHandlers:{handleModalCreate:An,handlePlanningTaskCreated:jn,handlePlanningTasksCreated:En,handleSubtaskTasksCreated:ts,handleGitHubImport:Ln},taskOperations:{moveTask:_e,deleteTask:ut,mergeTask:Qe,retryTask:vt,resetTask:Ae,duplicateTask:dt},deepLink:{handleDetailClose:It},settings:{prAuthAvailable:le,themeMode:ce,colorTheme:je,dashboardFontScalePct:He,setThemeMode:xe,setColorTheme:Ne,setDashboardFontScalePct:Y},onSettingsClose:Jn,onReopenOnboarding:zr}),t.jsx(Sz,{open:De}),a&&t.jsxs(t.Fragment,{children:[t.jsx(xz,{open:Ur,shellApi:a,shellState:r,onComplete:()=>Ei(!0)}),t.jsx(vz,{open:Na,shellApi:a,shellState:r,onClose:()=>Sa(!1)})]})]})}function Vz(){return t.jsx(jF,{children:t.jsx(fz,{children:t.jsx(CL,{children:t.jsx(tz,{children:t.jsx(PC,{children:t.jsx(qz,{})})})})})})}function ny(e){e.postMessage({type:"SKIP_WAITING"})}function zg(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&ny(e)})}function Wz(){if(!("serviceWorker"in navigator))return;const e=!!navigator.serviceWorker.controller;let n=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{n||!e||(n=!0,Lu("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(s=>{console.log("SW registered:",s.scope),s.waiting&&navigator.serviceWorker.controller&&ny(s.waiting),s.installing&&zg(s.installing),s.addEventListener("updatefound",()=>{const a=s.installing;a&&zg(a)})}).catch(s=>{console.log("SW registration failed:",s)})}Cj();uj();Zv();Jv();dy.createRoot(document.getElementById("root")).render(t.jsx(i.StrictMode,{children:t.jsx(mj,{children:t.jsx(Vz,{})})}));Wz();export{KS as $,Ys as A,Kn as B,Gn as C,RC as D,j6 as E,ua as F,dc as G,Zd as H,Mn as I,Fl as J,a8 as K,jt as L,Lo as M,fk as N,hL as O,Fn as P,Bd as Q,bs as R,Wi as S,Oo as T,is as U,vi as V,_n as W,un as X,cL as Y,as as Z,Sn as _,pn as a,D6 as a$,tL as a0,nL as a1,GS as a2,y6 as a3,JS as a4,T3 as a5,P3 as a6,ZN as a7,Pu as a8,Tr as a9,V5 as aA,q5 as aB,H5 as aC,B5 as aD,_j as aE,Eo as aF,L5 as aG,F5 as aH,O5 as aI,Y5 as aJ,G5 as aK,J5 as aL,Q5 as aM,O6 as aN,i8 as aO,Co as aP,Gd as aQ,Fk as aR,Ii as aS,Ak as aT,Zy as aU,UP as aV,qs as aW,eb as aX,_k as aY,P6 as aZ,$6 as a_,Ha as aa,ki as ab,ji as ac,Pi as ad,M5 as ae,P5 as af,T5 as ag,sb as ah,$5 as ai,A5 as aj,D5 as ak,R5 as al,I5 as am,gs as an,To as ao,vo as ap,Ws as aq,Yk as ar,$i as as,Kg as at,Ji as au,vy as av,z5 as aw,U5 as ax,K5 as ay,W5 as az,On as b,Fu as b$,L6 as b0,yc as b1,vF as b2,ah as b3,Wr as b4,pg as b5,O0 as b6,Nr as b7,T0 as b8,w5 as b9,x5 as bA,y5 as bB,h3 as bC,m3 as bD,u3 as bE,p3 as bF,j3 as bG,N3 as bH,y3 as bI,b3 as bJ,x3 as bK,v3 as bL,g3 as bM,f3 as bN,d3 as bO,w3 as bP,U4 as bQ,e6 as bR,Z3 as bS,r6 as bT,X3 as bU,t6 as bV,n6 as bW,s6 as bX,i6 as bY,jS as bZ,a6 as b_,k5 as ba,$0 as bb,qO as bc,L0 as bd,HO as be,C5 as bf,E5 as bg,j5 as bh,N5 as bi,S5 as bj,_5 as bk,QO as bl,Zi as bm,Fv as bn,R0 as bo,js as bp,da as bq,lc as br,BO as bs,Ia as bt,Xg as bu,JO as bv,Jg as bw,Im as bx,Ki as by,v5 as bz,et as c,bN as c$,yS as c0,wS as c1,kS as c2,vS as c3,Q3 as c4,fc as c5,Lk as c6,yr as c7,H6 as c8,q6 as c9,F3 as cA,q3 as cB,z3 as cC,B3 as cD,Ey as cE,uN as cF,W3 as cG,mN as cH,K3 as cI,di as cJ,Li as cK,hF as cL,_4 as cM,S3 as cN,z6 as cO,Qz as cP,Xz as cQ,rg as cR,A6 as cS,Zz as cT,t3 as cU,c3 as cV,l3 as cW,SN as cX,pN as cY,Di as cZ,fN as c_,V6 as ca,W6 as cb,K6 as cc,G6 as cd,J6 as ce,U6 as cf,ib as cg,Ww as ch,T as ci,Gl as cj,Mo as ck,wr as cl,l1 as cm,xj as cn,vj as co,nN as cp,sN as cq,d5 as cr,D3 as cs,$3 as ct,u5 as cu,L3 as cv,V3 as cw,U3 as cx,O3 as cy,H3 as cz,M6 as d,p6 as d$,gN as d0,xN as d1,vN as d2,_3 as d3,R6 as d4,I6 as d5,T6 as d6,Qi as d7,Z5 as d8,e8 as d9,k3 as dA,Y6 as dB,X6 as dC,t5 as dD,Z6 as dE,Q6 as dF,e5 as dG,n5 as dH,au as dI,Om as dJ,b6 as dK,v6 as dL,C0 as dM,tw as dN,Da as dO,Fs as dP,$w as dQ,s5 as dR,k6 as dS,Do as dT,MT as dU,ra as dV,x6 as dW,S6 as dX,N6 as dY,Gg as dZ,f6 as d_,B6 as da,n3 as db,Jd as dc,Es as dd,z4 as de,fL as df,bL as dg,xL as dh,la as di,Ud as dj,yL as dk,i3 as dl,e3 as dm,a3 as dn,s3 as dp,r3 as dq,o3 as dr,Oa as ds,r8 as dt,EC as du,xc as dv,t8 as dw,Vp as dx,n8 as dy,s8 as dz,E6 as e,l6 as e0,c6 as e1,eL as e2,Ea as e3,w6 as e4,m6 as e5,u6 as e6,eS as e7,h6 as e8,g6 as e9,I3 as eA,A3 as eB,i5 as ea,k0 as eb,d6 as ec,o6 as ed,mi as ee,Y3 as ef,G3 as eg,J3 as eh,a5 as ei,m5 as ej,eu as ek,f5 as el,g5 as em,p5 as en,l5 as eo,o5 as ep,c5 as eq,r5 as er,h5 as es,F6 as et,X5 as eu,M3 as ev,C3 as ew,E3 as ex,jk as ey,R3 as ez,La as f,_6 as g,Ks as h,$r as i,Dn as j,sc as k,b5 as l,Is as m,WS as n,C6 as o,ri as p,GO as q,sL as r,hi as s,zn as t,Ni as u,pi as v,us as w,gc as x,Xo as y,Ee as z};